From 9bc8fd992a2d82a9a513c91ec240ca845bdfbe2f Mon Sep 17 00:00:00 2001 From: Paula Date: Thu, 5 Nov 2026 22:37:41 -0300 Subject: [PATCH] Move effects out of cubi --- common/mod_api/server.ts | 23 ++- docs/modding/concepts/events.md | 10 +- docs/modding/entities/effects.md | 43 +++- docs/modding/entities/players.md | 2 +- mods/bworld/effects/water_breathing.json | 5 +- mods/bworld/scripts/curios.ts | 4 +- mods/bworld/scripts/effects.ts | 16 +- move_to_mods.md | 244 +++++++++++++++++++++++ server/game/entity/entity.ts | 8 +- server/game/entity/entity_manager.ts | 12 +- server/game/entity/living_entity.ts | 18 +- server/game/game_server.ts | 21 +- server/game/mod_runtime.ts | 55 ++++- server/game/player.ts | 10 - tests/base_game_test.ts | 12 ++ tests/entity_test.ts | 37 +++- tests/vitals_test.ts | 2 +- 17 files changed, 452 insertions(+), 70 deletions(-) create mode 100644 move_to_mods.md diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index b628660..79e1287 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -157,6 +157,12 @@ export interface LivingRef { readonly id: string; readonly health: number; readonly max_health: number; + // ticks of air left under water, max_air when full. it drowns 20 ticks after reaching 0. setting it over max_air + // sets max_air + air: number; + readonly max_air: number; + // the one it has of that type, like Player.effect + effect(id: Id): { readonly amplifier: number; readonly duration: number } | undefined; // cause is for events and the death message, like "magic" damage(amount: number, cause?: string): void; heal(amount: number): void; @@ -236,12 +242,17 @@ export interface BlockInteractEvent { readonly item: ItemStack | undefined; } -export interface PlayerDamageEvent { - readonly player: Player; +// a player or a mob being hurt, like neoforge's LivingIncomingDamageEvent +export interface EntityDamageEvent { + readonly entity: LivingRef; + // set when a player is hurt + readonly player: Player | undefined; // before events can change it amount: number; - // what hurt them: "fall", "void", "starve", or what a mod passed to damage + // what hurt it: "fall", "void", "starve", "mob_attack", or what a mod passed to damage readonly cause: string; + // like falling out of the world. even invulnerable entities are hurt + readonly bypasses_invulnerability: boolean; } export interface PlayerDeathEvent { @@ -259,7 +270,7 @@ export interface ServerBeforeEvents { block_place: EventSignal; block_interact: EventSignal; chat_send: EventSignal; - player_damage: EventSignal; + entity_damage: EventSignal; } export interface ServerAfterEvents { @@ -269,8 +280,8 @@ export interface ServerAfterEvents { chat_send: EventSignal>; player_join: EventSignal<{ readonly player: Player }>; player_leave: EventSignal<{ readonly player: Player }>; - // they were hurt, after before handlers had their say. amount is what they took - player_damage: EventSignal>; + // it was hurt, after before handlers had their say. amount is what it took + entity_damage: EventSignal>; // they drop what they carried and respawn right after player_death: EventSignal; server_start: EventSignal>; diff --git a/docs/modding/concepts/events.md b/docs/modding/concepts/events.md index 4c76cad..7833ced 100644 --- a/docs/modding/concepts/events.md +++ b/docs/modding/concepts/events.md @@ -48,7 +48,7 @@ showed. These events fire for **every** player's actions, since they all go thro | `block_place` | ✓ | ✓ | `player`, `block` (`{ id, x, y, z }`), `face` clicked, `hit` where on it (0-1 each axis), `item` held | | `block_interact` | ✓ | ✓ | `player`, `block`, `item` held. Before fires for every right click on a block, after only when a component's `on_interact` handled it | | `chat_send` | ✓ | ✓ | `player`, `message`. Before handlers can change `message` | -| `player_damage` | ✓ | ✓ | `player`, `amount`, `cause`. Before handlers can change `amount`, after fires only when they were hurt, with what they took | +| `entity_damage` | ✓ | ✓ | `entity`, `player`, `amount`, `cause`, `bypasses_invulnerability`. See below | | `player_death` | | ✓ | `player`, `cause`. They've dropped what they carried and respawn right after | | `player_join` | | ✓ | `player` | | `player_leave` | | ✓ | `player` | @@ -56,7 +56,13 @@ showed. These events fire for **every** player's actions, since they all go thro | `tick` | | ✓ | `dt`, in seconds. 20 times a second | | `new_day` | | ✓ | `day`. At 06:00, after every block's `on_new_day` | -`cause` is `"fall"`, `"void"`, `"starve"`, or whatever a mod passed to `player.damage(amount, cause)`. +`cause` is `"fall"`, `"void"`, `"starve"`, `"mob_attack"`, or whatever a mod passed to `damage(amount, cause)`. + +`entity_damage` fires whenever a player or a mob is hurt, like NeoForge's `LivingIncomingDamageEvent`. `entity` is a +[`LivingRef`](../entities/effects.md#effect-components), and `player` is set when it's a player. Before handlers can +change `amount` or cancel it. They run before the hurt cooldown, so what they leave is what's compared with the last +hit. `bypasses_invulnerability` is set for damage that nothing should stop, like falling out of the world. After fires +only when the entity was hurt, with the amount the before handlers left. ### Order diff --git a/docs/modding/entities/effects.md b/docs/modding/entities/effects.md index bf816d4..fd8bd26 100644 --- a/docs/modding/entities/effects.md +++ b/docs/modding/entities/effects.md @@ -4,8 +4,9 @@ Status effects change a player or a mob for a while, like speed or poison. They effect is defined once, and adding it to someone gives them an instance of it with a duration and a level. Like blocks and items, an effect is data with components. Its JSON in the mod's `effects/` folder says what it is and -which attributes it changes. Components, registered by the server script, say what it does over time. Even the base -game's effects are defined this way, in `mods/bworld/effects`. +which attributes it changes. Components, registered by the server script, say what it does over time. An effect can also +change things where they happen, through an [event](../concepts/events.md). Even the base game's effects are defined +this way, in `mods/bworld/effects`. ## Defining an Effect @@ -73,13 +74,46 @@ interface LivingRef { readonly id: string; readonly health: number; readonly max_health: number; + // ticks of air left under water, max_air when full. it drowns 20 ticks after reaching 0. setting it over max_air + // sets max_air + air: number; + readonly max_air: number; + // the one it has of that type, like player.effect + effect(id: Id): { readonly amplifier: number; readonly duration: number } | undefined; damage(amount: number, cause?: string): void; // cause is for events and the death message heal(amount: number): void; } ``` +Effects tick after the entity loses air under water, so setting `air` from `on_tick` keeps it from running out. That's +all `bworld:water_breathing` does: + +```ts +ctx.components.register_effect("bworld:refill_air", { + on_tick(entity) { + entity.air = entity.max_air; + }, +}); +``` + Like block components, an effect that lists a component nobody registered stops the server from starting. +## Effects Through Events + +Some effects change something as it happens, like damage coming in, rather than over time. Those need no component: a +handler checks whether the entity has the effect. `bworld:resistance` is one, subscribing to `entity_damage` in its +server script: + +```ts +ctx.events.before.entity_damage.subscribe((event) => { + const resistance = event.entity.effect("bworld:resistance"); + if (!resistance || event.bypasses_invulnerability) return; + event.amount *= Math.max(0, 1 - 0.2 * (resistance.amplifier + 1)); +}); +``` + +Before handlers run in mod load order, so mods loaded later see the lowered amount. + ## Using Effects `/effect [seconds]` gives you one while testing, for 30 seconds unless you say. @@ -102,5 +136,6 @@ player.add_effect("copper_tools:swiftness", 200, { amplifier: 1 }); | `bworld:resistance` | Takes 20% less damage a level. | | `bworld:water_breathing` | Doesn't run out of air under water. | -Resistance and water breathing have no components: like in Minecraft, the engine checks for them where damage and air -are worked out. +Regeneration, poison and instant health use components that tick. Water breathing's component fills the air back up each +tick, so it never runs out. Resistance has no component, it lowers damage in a `before.entity_damage` handler, see +[Effects Through Events](#effects-through-events). diff --git a/docs/modding/entities/players.md b/docs/modding/entities/players.md index f57564a..99e102d 100644 --- a/docs/modding/entities/players.md +++ b/docs/modding/entities/players.md @@ -99,7 +99,7 @@ half a second, unless the new hit is harder, and then only by the difference. A player's client moves them, except while they're knocked back: then the server moves them until they land, so it works 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` +`damage(amount, cause)` hurts them like anything else would. `cause` shows in the `entity_damage` and `player_death` [events](../concepts/events.md) and in the death message. Before events can change the amount or cancel it. ## Attributes diff --git a/mods/bworld/effects/water_breathing.json b/mods/bworld/effects/water_breathing.json index 0208f33..17233ee 100644 --- a/mods/bworld/effects/water_breathing.json +++ b/mods/bworld/effects/water_breathing.json @@ -3,6 +3,9 @@ "effect": { "id": "bworld:water_breathing", "category": "beneficial", - "icon": "bworld:water_breathing" + "icon": "bworld:water_breathing", + "components": { + "bworld:refill_air": {} + } } } diff --git a/mods/bworld/scripts/curios.ts b/mods/bworld/scripts/curios.ts index a29cdda..3626e9c 100644 --- a/mods/bworld/scripts/curios.ts +++ b/mods/bworld/scripts/curios.ts @@ -103,7 +103,9 @@ export function register_curios(ctx: ServerContext) { }); ctx.events.after.player_join.subscribe(({ player }) => last_hurt.set(player.id, ctx.system.current_tick)); - ctx.events.after.player_damage.subscribe(({ player }) => last_hurt.set(player.id, ctx.system.current_tick)); + ctx.events.after.entity_damage.subscribe(({ player }) => { + if (player) last_hurt.set(player.id, ctx.system.current_tick); + }); ctx.events.after.tick.subscribe(() => { for (const [id, effects] of unhurt_effects) { const player = ctx.players.get(id); diff --git a/mods/bworld/scripts/effects.ts b/mods/bworld/scripts/effects.ts index 0ca43dc..bf0ff56 100644 --- a/mods/bworld/scripts/effects.ts +++ b/mods/bworld/scripts/effects.ts @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// what the base game's effects do over time, see mods/bworld/effects. speed and slowness are only attribute -// modifiers, and resistance and water breathing work where damage and air happen, like minecraft's +// what the base game's effects do, see mods/bworld/effects. speed and slowness are only attribute modifiers, and +// resistance has no component, it lowers damage as it comes in import type { ServerContext } from "cubi/server"; // every n ticks, n halving with each level: minecraft's regeneration and poison @@ -25,6 +25,18 @@ export function register_effects(ctx: ServerContext) { if (entity.health > 1) entity.damage(1, "magic"); }, }); + // effects tick after the entity loses air under water, so it never runs out + ctx.components.register_effect("bworld:refill_air", { + on_tick(entity) { + entity.air = entity.max_air; + }, + }); + // 20% less damage for each level, unless nothing could stop it, like falling out of the world + ctx.events.before.entity_damage.subscribe((event) => { + const resistance = event.entity.effect("bworld:resistance"); + if (!resistance || event.bypasses_invulnerability) return; + event.amount *= Math.max(0, 1 - 0.2 * (resistance.amplifier + 1)); + }); // instant: amount for level 1, doubling with each level ctx.components.register_effect<{ amount: number }>("bworld:heal", { on_tick(entity, amplifier, params) { diff --git a/move_to_mods.md b/move_to_mods.md new file mode 100644 index 0000000..18dcbfc --- /dev/null +++ b/move_to_mods.md @@ -0,0 +1,244 @@ +# Moving base game rules out of the engine + +Three places where `cubi` still names `bworld` content, and what the modding API needs so `mods/bworld` can do them +itself. Each part is independent. The suggested order is effects, then tooltips, then dimensions, from smallest to +largest. + +## 1. Effects: resistance and water breathing + +### Today + +- [server/game/entity/living_entity.ts](server/game/entity/living_entity.ts) hardcodes `bworld:resistance` and + `bworld:water_breathing`. +- `actually_hurt` cuts damage by 20% per resistance level, unless the source is `absolute` or bypasses invulnerability. + It does this before shielding. +- `base_tick` skips losing air when the entity has water breathing. +- Both effect JSONs in `mods/bworld/effects/` have no components. The docs say "the engine checks for them". + +### How VoxeLibre does it + +`ports/voxelibre/mods/ITEMS/mcl_potions/functions.lua` has no hook made for either effect: + +- **Water breathing** is a plain `on_step` that sets the entity's breath back to full while the effect is on. +- **Resistance** is a `modifier_func` run by `mcl_damage.register_modifier` + (`ports/voxelibre/mods/CORE/mcl_damage/init.lua`). That's a general list of damage modifiers every hit goes through, + and it isn't specific to effects. The effect's modifier only checks whether the entity has the effect, and skips + damage flagged `bypasses_magic`. + +So effects need nothing new. What's missing is general API: scripts can't see or change an entity's air, mobs' damage +goes through no event, and `LivingRef` can't tell which effects an entity has. + +### Plan + +The API additions are general, and each is useful without effects: + +```ts +// common/mod_api/server.ts +export interface LivingRef { + readonly id: string; + readonly health: number; + readonly max_health: number; + // ticks of air left under water, max_air when full. it drowns 20 ticks after reaching 0 + air: number; + readonly max_air: number; + // the one it has of that type, like Player.effect + effect(id: Id): { readonly amplifier: number; readonly duration: number } | undefined; + damage(amount: number, cause?: string): void; + heal(amount: number): void; +} + +// replaces PlayerDamageEvent: fires for every living entity, players included +export interface EntityDamageEvent { + readonly entity: LivingRef; + // set when a player is hurt + readonly player: Player | undefined; + // before events can change it + amount: number; + readonly cause: string; + // like falling out of the world. even invulnerable entities are hurt + readonly bypasses_invulnerability: boolean; +} +``` + +Engine: + +- `ctx.events.before.entity_damage` and `ctx.events.after.entity_damage` replace `player_damage`. The game is pre-alpha, + so there's no need to keep both. +- The before event moves from `GameServer.hurt_player` into `LivingEntity.hurt`, so mobs go through it too. It fires + before the hurt cooldown math, which is where `player_damage` fires for players now. +- `living_ref` gets `air` (the setter clamps to `max_air` or less) and `effect(id)`. `Player` already has `effect`. +- `LivingEntity` drops the `RESISTANCE` and `WATER_BREATHING` constants and their checks. `base_tick` always loses air + under water unless `can_breathe_underwater` is true. + +bworld: + +- Water breathing gets a `bworld:refill_air` component whose `on_tick` sets `entity.air = entity.max_air`. Effects tick + after `base_tick`, so the air never gets to 0. This is VoxeLibre's `on_step`. +- Resistance subscribes to `before.entity_damage` in [mods/bworld/scripts/effects.ts](mods/bworld/scripts/effects.ts). + When `entity.effect("bworld:resistance")` is there and the damage doesn't bypass invulnerability, it multiplies + `amount` by `1 - 0.2 * (amplifier + 1)`, clamped to 0 or more. This is VoxeLibre's damage modifier. Resistance's JSON + keeps no components. +- `curios.ts` moves from `after.player_damage` to `after.entity_damage` and checks `player`. + +Behavior changes to accept: + +- Resistance now applies in the before event, in load order with other mods' handlers. Today it applies after all of + them. bworld loads first, so later mods see the reduced amount. VoxeLibre orders its modifiers with a priority. Leave + that out until a mod needs it. +- With water breathing on, the air bar stays full under water instead of not changing. That's what VoxeLibre does. + +NeoForge reference: `LivingIncomingDamageEvent`, the general version of `entity_damage` +(`ports/neoforge/src/main/java/net/neoforged/neoforge/event/entity/living/`). Air is `getAirSupply` and `setAirSupply`. + +Docs and tests: + +- In [docs/modding/concepts/events.md](docs/modding/concepts/events.md), replace `player_damage` with `entity_damage` in + the table, and update [docs/modding/entities/players.md](docs/modding/entities/players.md), which mentions it. +- In [docs/modding/entities/effects.md](docs/modding/entities/effects.md), rewrite "The Base Game's Effects", and add an + example of an effect that works through an event, like resistance. +- The water breathing test in `tests/entity_test.ts` should keep passing unchanged. +- Add a test that `before.entity_damage` fires for a mob and can change the amount. +- Add a test that a script setting `air` is clamped and keeps a mob from drowning. + +## 2. Tooltip API: the sell value line + +### Today + +- `item_tooltip` in [client/gui/tooltip.ts](client/gui/tooltip.ts) always adds a sell value line, using the + `bworld:copper_coin` icon (`VALUE_ICON`). +- `sell_value` and `base_sell_value` are engine features used by the server API. They stay. Only the line and its icon + move. +- Client scripts can't add lines to item tooltips. `g.item_tooltip(id, x, y, extra)` only adds lines to one drawn + tooltip. +- The client's `ctx.items.sell_value(id)` takes no item data, so it can't price a full juice bottle the way the engine's + tooltip does. + +### Plan + +```ts +// common/mod_api/client.ts +export interface TooltipLine { + text: string; + color?: Color; + // a texture drawn before the text, as tall as the line + icon?: Id; + // lower comes first, TOOLTIP_PRIORITY.default when not set. lines with the same priority keep the order they were + // added in: the game's first, then mods' in load order + priority?: number; +} + +// where the game's own lines go, so a mod's can go between them +export const TOOLTIP_PRIORITY = { + name: 0, + fluid: 100, + food: 200, + default: 500, + lore: 1000, + // g.item_tooltip's extra lines + extra: 2000, +} as const; + +export interface ClientUi { + // ... + // adds to every item's tooltip, like neoforge's ItemTooltipEvent. lines has the game's lines and earlier mods'. + // push to it, and the lines are sorted by priority once every function has run + add_item_tooltip(fn: (item: ItemStack, lines: TooltipLine[]) => void): void; +} +``` + +Engine: + +- `item_tooltip` stops adding the value line. It gives its own lines their `TOOLTIP_PRIORITY`, runs the registered + functions in load order, each with `run_mod`, then does a stable sort by priority. Hovered slots and `g.item_tooltip` + both go through `item_tooltip`, so both get the new lines. +- `g.item_tooltip`'s `extra` lines get `TOOLTIP_PRIORITY.extra` unless they set their own priority, so they stay under + everything like now. Lore from the server's `get_lore` is part of the stack's lore, so it gets `lore`. +- `g.tooltip` and `g.item_tooltip` take the same `TooltipLine`, so mods can draw icons there too. +- Give the shared `ctx.items.sell_value` an optional `data`, like the server's `sell_value(id, data)`. Both should call + `sell_value` in `common/inventory.ts` with the side's fluid rules. +- Remove `VALUE_ICON` and `VALUE_COLOR`. + +bworld: + +- [mods/bworld/scripts/client.ts](mods/bworld/scripts/client.ts) calls `ctx.ui.add_item_tooltip` and pushes + `{ icon: "bworld:copper_coin", text: String(value), color, priority: TOOLTIP_PRIORITY.food + 1 }` whenever + `ctx.items.sell_value(item.id, item.data)` is defined. That puts it between the food and the lore, where it is now. + +NeoForge reference: `ItemTooltipEvent` +(`ports/neoforge/src/main/java/net/neoforged/neoforge/event/entity/player/ItemTooltipEvent.java`). + +Docs and tests: + +- In [docs/modding/gui/index.md](docs/modding/gui/index.md), document `add_item_tooltip`, the `TooltipLine` icon and + priority, and the `TOOLTIP_PRIORITY` table. +- In [docs/modding/items/index.md](docs/modding/items/index.md), give `sell_value` its `data` argument. +- Add a test where a test mod's client script adds a line, and it shows up in `item_tooltip`. +- Add a test that two lines with a priority between the name and the lore end up there, and that two lines with the same + priority keep the order they were added in. + +The food line ("Restores N hunger") is the same kind of thing and could move the same way later, if hunger is base game +content. + +## 3. Dimensions: the overworld generator and the spawn search + +### Today + +- The generator is hardcoded as `GENERATOR = "bworld:overworld"` in + [server/game/load_mods.ts](server/game/load_mods.ts). It's passed to `load_worldgen` and to `worldgen_bundle` for the + workers. +- `World.#find_spawn` in [server/game/world.ts](server/game/world.ts) checks rings of chunks around 0, 0. It takes the + top non-air block of each chunk's middle column, unless that block is `bworld:water`. +- `tools/worldgen_preview.ts` also names `bworld:overworld`, but it's a tool for bworld, so that's fine. + +### Plan + +A dimension is data, like NeoForge's `dimension/` files (a level stem). It points at the noise settings that generate +it: + +```json +// mods/bworld/worldgen/dimension/overworld.json +{ + "format_version": 1, + "dimension": { + "id": "bworld:overworld", + "generator": "bworld:overworld", + "default": true + } +} +``` + +- The world plays the dimension with `"default": true`. If no loaded mod has one, or more than one does, the server + doesn't start, and the error names the mods. +- `start_game` reads the generator from the dimension instead of `GENERATOR`, and passes it to `load_worldgen` and + `worldgen_bundle`. +- Mods add worldgen data in four places: `mod_data.ts`, `mod_check.ts` (the generator has to exist), `check_mods.ts`, + and the `.cubi` reader. Dimension files need the same handling. +- There's one dimension per world for now. The file is where more dimensions would go later, but this plan doesn't add + travel between them. + +Spawn search, recommended: keep a generic search in the engine, since every game needs a spawn point, but drop the block +id. A column counts when its top non-air block has collision. Water has `"collision": false`, so bworld gets the same +spawn without the engine naming anything. Columns topped by a plant without collision get skipped too, which is fine. + +If mods need more control later: + +- A `"spawn"` field on the dimension, such as a block tag the spawn has to be on. +- A server script hook that picks the spawn, like NeoForge's `LevelEvent.CreateSpawnPosition`. + +Neither is needed to move this out, so neither is in the plan. + +Docs and tests: + +- Add a "Dimensions" section to [docs/modding/worldgen/index.md](docs/modding/worldgen/index.md) or + [terrain.md](docs/modding/worldgen/terrain.md), and update the terrain docs that say the base game's overworld is the + generator. +- Add a test where a test mod with its own noise settings and a default dimension is what the world generates. +- Add tests that zero or two default dimensions are a load error. +- Add a test that the spawn never lands on a block without collision. +- The worldgen golden tests shouldn't change, since the generator and the terrain are the same. + +## Open questions + +1. Spawn: is the collision rule enough, or do you want the spawn search fully in bworld (a script hook) right away? +2. Dimensions: should the save remember which dimension a world was made with, so changing mods can't swap the generator + under an existing world? It isn't needed for pre-alpha. diff --git a/server/game/entity/entity.ts b/server/game/entity/entity.ts index fa3f7a3..7e72cc0 100644 --- a/server/game/entity/entity.ts +++ b/server/game/entity/entity.ts @@ -15,6 +15,7 @@ import type { Season } from "@/common/worldgen/biomes.ts"; import { type Collisions, type FluidInCell, physics } from "@/common/physics.ts"; import type { EntityData, EntityEvent, EntityInfo } from "@/common/protocol.ts"; import type { ServerPlayer } from "../player.ts"; +import type { LivingEntity } from "./living_entity.ts"; // below this, entities have fallen out of the world export const VOID_Y = -64; @@ -85,8 +86,11 @@ export interface EntityLevel { // entities whose feet are within the box around x, y, z entities_near(x: number, y: number, z: number, radius: number): Entity[]; nearest_player(x: number, y: number, z: number, max_distance: number): ServerPlayer | undefined; - // what ServerPlayer.hurt does: mods get a say, then they're hurt. returns whether they were - hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean; + // mods' before.entity_damage, see LivingEntity.hurt: what's left of amount once they had their say, 0 when one + // canceled it + before_hurt(entity: LivingEntity, amount: number, source: DamageSource): number; + // mods' after.entity_damage, it was hurt by amount + after_hurt(entity: LivingEntity, amount: number, source: DamageSource): void; spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay?: number): Entity; // an item on the ground was picked up whole by who, clients see it fly to them. it's gone after take_item(item: Entity, by: string): void; diff --git a/server/game/entity/entity_manager.ts b/server/game/entity/entity_manager.ts index dbe627d..bde83fc 100644 --- a/server/game/entity/entity_manager.ts +++ b/server/game/entity/entity_manager.ts @@ -15,6 +15,7 @@ import type { ServerWorld } from "../world.ts"; import type { DamageSource, Entity, EntityLevel, SavedEntity } from "./entity.ts"; import { load_entity } from "./entity_types.ts"; import { ItemEntity } from "./item_entity.ts"; +import type { LivingEntity } from "./living_entity.ts"; // everything the entities need from the game server export interface EntityHost { @@ -22,7 +23,8 @@ export interface EntityHost { readonly current_tick: number; players(): ServerPlayer[]; send(player: ServerPlayer, message: ServerMessage): void; - hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean; + before_hurt(entity: LivingEntity, amount: number, source: DamageSource): number; + after_hurt(entity: LivingEntity, amount: number, source: DamageSource): void; on_entity_death?(entity: Entity, source: DamageSource): void; // what it drops when it dies, from its loot table entity_loot?(entity: Entity, source: DamageSource): ItemStack[]; @@ -136,8 +138,12 @@ export class EntityManager implements EntityLevel { return nearest; } - hurt_player(player: ServerPlayer, amount: number, source: DamageSource) { - return this.#host.hurt_player(player, amount, source); + before_hurt(entity: LivingEntity, amount: number, source: DamageSource) { + return this.#host.before_hurt(entity, amount, source); + } + + after_hurt(entity: LivingEntity, amount: number, source: DamageSource) { + this.#host.after_hurt(entity, amount, source); } spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): ItemEntity { diff --git a/server/game/entity/living_entity.ts b/server/game/entity/living_entity.ts index e9475ea..c471e71 100644 --- a/server/game/entity/living_entity.ts +++ b/server/game/entity/living_entity.ts @@ -31,9 +31,6 @@ const SWIM_UP = 0.04; // a jump can't start more often than this while jump is held const JUMP_DELAY = 10; const KNOCKBACK = 0.4; -// the base game's effects that work where what they change happens, like minecraft's: in damage and air -const RESISTANCE = "bworld:resistance"; -const WATER_BREATHING = "bworld:water_breathing"; export interface SavedLivingEntity extends SavedEntity { health?: number; @@ -141,7 +138,7 @@ export abstract class LivingEntity extends Entity { override base_tick() { super.base_tick(); if (this.alive) { - if (this.eyes_in_water && !this.can_breathe_underwater && !this.has_effect(WATER_BREATHING)) { + if (this.eyes_in_water && !this.can_breathe_underwater) { this.air -= 1; if (this.air <= -20) { this.air = 0; @@ -270,11 +267,14 @@ export abstract class LivingEntity extends Entity { // health - // like minecraft's LivingEntity.hurt. returns whether it was hurt + // like minecraft's LivingEntity.hurt. mods can change or cancel it first. returns whether it was hurt override hurt(amount: number, source: DamageSource): boolean { if (this.is_invulnerable_to(source) || this.dead || !(amount > 0)) { return false; } + amount = this.level.before_hurt(this, amount, source); + if (!(amount > 0)) return false; + const taken = amount; let fresh = true; if (this.#hurt_cooldown > HURT_COOLDOWN / 2) { if (amount <= this.#last_hurt_amount) return false; @@ -306,24 +306,20 @@ export abstract class LivingEntity extends Entity { } } this.on_hurt(source); + this.level.after_hurt(this, taken, source); if (this.dead) { this.die(source); } return true; } - // after resistance + // after mods and the hurt cooldown actually_hurt(amount: number, source: DamageSource) { // absolute damage, take it and theres no counterplay if (source.type === "absolute") { this.health -= amount; return; } - - const resistance = this.get_effect(RESISTANCE); - if (resistance && !source.bypasses_invulnerability) { - amount = Math.max(0, amount * (25 - (resistance.amplifier + 1) * 5) / 25); - } const shielding = this.attribute( source.type === "physical" ? ATTRIBUTES.physical_shielding : ATTRIBUTES.arcane_shielding, ); diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 7241014..ca78cbe 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -242,7 +242,10 @@ export class GameServer { }, players: () => this.players(), send: (player, message) => this.#send(player, message), - hurt_player: (player, amount, source) => this.hurt_player(player, amount, source), + before_hurt: (entity, amount, source) => + this.mods.before_damage(entity, entity instanceof ServerPlayer ? entity : undefined, amount, source), + after_hurt: (entity, amount, source) => + this.mods.after_damage(entity, entity instanceof ServerPlayer ? entity : undefined, amount, source), on_entity_death: (entity, source) => { if (entity instanceof ServerPlayer) this.#kill(entity, source); }, @@ -1959,22 +1962,6 @@ export class GameServer { player.hurt(amount, damage_source(cause)); } - // everything that hurts a player ends up here, see ServerPlayer.hurt. mods can change or cancel it first - hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean { - if (player.is_invulnerable_to(source) || !player.alive || !(amount > 0)) { - return false; - } - const before = { player: this.mods.player(player), amount, cause: source.cause, cancel: false }; - this.mods.before.player_damage.emit(before); - const final = Number(before.amount); - if (before.cancel || !(final > 0)) { - return false; - } - if (!player.apply_hurt(final, source)) return false; - this.mods.after.player_damage.emit({ player: before.player, amount: final, cause: source.cause }); - return true; - } - heal_player(player: ServerPlayer, amount: number) { player.heal(amount); } diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index 2e3248b..2438134 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -80,7 +80,7 @@ import type { GameServer } from "./game_server.ts"; import { MAX_PRIORITY, MIN_PRIORITY } from "./scheduled_ticks.ts"; import type { ServerPlayer } from "./player.ts"; import { Menu, type MenuFluidSlot, type MenuSlot } from "./menu.ts"; -import { damage_source, type Entity } from "./entity/entity.ts"; +import { damage_source, type DamageSource, type Entity } from "./entity/entity.ts"; import type { LivingEntity } from "./entity/living_entity.ts"; import type { EffectJson } from "@/common/mod_data.ts"; import { create_entity } from "./entity/entity_types.ts"; @@ -184,7 +184,7 @@ export class ModRuntime { block_place: new Signal(), block_interact: new Signal(), chat_send: new Signal(), - player_damage: new Signal(), + entity_damage: new Signal(), }; after: After = { block_break: new Signal(), @@ -193,7 +193,7 @@ export class ModRuntime { chat_send: new Signal(), player_join: new Signal(), player_leave: new Signal(), - player_damage: new Signal(), + entity_damage: new Signal(), player_death: new Signal(), server_start: new Signal(), tick: new Signal(), @@ -624,6 +624,32 @@ export class ModRuntime { } } + // everything that hurts a player or a mob, see LivingEntity.hurt. what's left of amount once mods had their say, 0 + // when one canceled it + before_damage(entity: LivingEntity, player: ServerPlayer | undefined, amount: number, source: DamageSource) { + if (this.before.entity_damage.empty) return amount; + const event = { ...this.#damage_event(entity, player, amount, source), cancel: false }; + this.before.entity_damage.emit(event); + const final = Number(event.amount); + return event.cancel || !(final > 0) ? 0 : final; + } + + after_damage(entity: LivingEntity, player: ServerPlayer | undefined, amount: number, source: DamageSource) { + if (!this.after.entity_damage.empty) { + this.after.entity_damage.emit(this.#damage_event(entity, player, amount, source)); + } + } + + #damage_event(entity: LivingEntity, player: ServerPlayer | undefined, amount: number, source: DamageSource) { + return { + entity: living_ref(entity), + player: player && this.player(player), + amount, + cause: source.cause, + bypasses_invulnerability: source.bypasses_invulnerability === true, + }; + } + player(player: ServerPlayer): Player { let api = this.#players.get(player); if (!api) { @@ -1575,10 +1601,7 @@ function player_api(game: GameServer, player: ServerPlayer): Player { } player.add_effect(new EffectInstance(type, duration, { ...options, amplifier })); }, - effect(id) { - const effect = player.get_effect(known_effect(id).id); - return effect && { amplifier: effect.amplifier, duration: effect.duration }; - }, + effect: (id) => effect_of(player, id), remove_effect: (id) => player.remove_effect(known_effect(id).id), is_swimming: () => player.swimming, is_sneaking: () => player.sneaking, @@ -1611,7 +1634,12 @@ function known_attribute(id: string): AttributeType { return type; } -function living_ref(entity: LivingEntity): LivingRef { +function effect_of(entity: LivingEntity, id: string) { + const effect = entity.get_effect(known_effect(id).id); + return effect && { amplifier: effect.amplifier, duration: effect.duration }; +} + +export function living_ref(entity: LivingEntity): LivingRef { return { id: entity.id, get health() { @@ -1620,6 +1648,17 @@ function living_ref(entity: LivingEntity): LivingRef { get max_health() { return entity.max_health; }, + get air() { + return entity.air; + }, + set air(value) { + if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`air must be a number`); + entity.air = Math.min(value, entity.max_air); + }, + get max_air() { + return entity.max_air; + }, + effect: (id) => effect_of(entity, id), damage(amount, cause = "script") { if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`damage must be a number`); entity.hurt(amount, damage_source(String(cause))); diff --git a/server/game/player.ts b/server/game/player.ts index 08e00b2..947cac6 100644 --- a/server/game/player.ts +++ b/server/game/player.ts @@ -178,16 +178,6 @@ export class ServerPlayer extends LivingEntity { this.vx = this.vy = this.vz = 0; } - // everything that hurts a player goes through the game server first, which lets mods change or cancel it - override hurt(amount: number, source: DamageSource): boolean { - return this.level.hurt_player(this, amount, source); - } - - // hurts them for real, once mods have had their say - apply_hurt(amount: number, source: DamageSource): boolean { - return super.hurt(amount, source); - } - override on_hurt(_source: DamageSource) { this.vitals.add_exhaustion(EXHAUSTION.damage); } diff --git a/tests/base_game_test.ts b/tests/base_game_test.ts index cc99012..4662a5b 100644 --- a/tests/base_game_test.ts +++ b/tests/base_game_test.ts @@ -398,6 +398,18 @@ Deno.test("a stonecutter cuts its input into the recipe picked with a button, on ); }); +Deno.test("resistance takes 20% off damage for each level, but not off what nothing could stop", async () => { + const t = await setup(); + const alice = t.game.players()[0]; + const amounts: number[] = []; + // loaded after bworld, so it sees what resistance left + t.game.mods.before.entity_damage.for_mod("test").subscribe((event) => amounts.push(event.amount)); + t.game.mods.player(alice).add_effect("bworld:resistance", 100, { amplifier: 1 }); + t.game.damage_player(alice, 10, "fall"); + t.game.damage_player(alice, 10, "void"); + assertEquals(amounts, [6, 10]); +}); + Deno.test("a bucket picks up a water source but not flowing water, and a water bucket puts a source back", async () => { const t = await setup([["bworld:bucket", 1]]); const held = () => t.game.players()[0].held_item?.type_id; diff --git a/tests/entity_test.ts b/tests/entity_test.ts index 0d83d57..b8ad0c0 100644 --- a/tests/entity_test.ts +++ b/tests/entity_test.ts @@ -9,6 +9,7 @@ import { DAMAGE } from "@/server/game/entity/entity.ts"; import { register_entity_type } from "@/server/game/entity/entity_types.ts"; import { Goal, GoalSelector, RandomStrollGoal } from "@/server/game/entity/goals.ts"; import { Mob } from "@/server/game/entity/mob.ts"; +import { living_ref } from "@/server/game/mod_runtime.ts"; import { test_game } from "./helpers.ts"; // a mob for testing, walking like a pig @@ -256,7 +257,7 @@ Deno.test("mobs hurt players like anything else, and mods still get a say", asyn const { game, spawn, ticks } = await floor_game(); const alice = game.players()[0]; const causes: string[] = []; - game.mods.before.player_damage.for_mod("test").subscribe((event) => causes.push(event.cause)); + game.mods.before.entity_damage.for_mod("test").subscribe((event) => causes.push(event.cause)); const mob = spawn(0.5, 100, 1.5); ticks(1); @@ -329,6 +330,40 @@ Deno.test("mobs drown after their air runs out, unless they breathe water", asyn assertEquals(breather.health, 10); }); +Deno.test("mods get a say in damage to mobs too", async () => { + const { game, spawn, ticks } = await floor_game(); + const mob = spawn(0.5, 100, 2.5); + ticks(1); + const seen: { entity: string; player: unknown; cause: string; amount: number }[] = []; + game.mods.before.entity_damage.for_mod("test").subscribe((event) => { + if (event.entity.id === mob.id) event.amount /= 2; + }); + game.mods.after.entity_damage.for_mod("test").subscribe(({ entity, player, cause, amount }) => + seen.push({ entity: entity.id, player, cause, amount }) + ); + assert(mob.hurt(4, DAMAGE.generic)); + assertEquals(mob.health, 10 - 2); + assertEquals(seen, [{ entity: mob.id, player: undefined, cause: "generic", amount: 2 }]); +}); + +Deno.test("scripts can set a mob's air, up to its most", async () => { + const { game, spawn, ticks } = await floor_game(); + for (let y = 100; y <= 102; y++) game.set_block(3, y, 3, "bworld:water"); + for (const [x, z] of [[2, 3], [4, 3], [3, 2], [3, 4]]) { + for (let y = 100; y <= 102; y++) game.set_block(x, y, z, "bworld:stone"); + } + const mob = spawn(3.5, 100, 3.5); + mob.no_ai = true; + const ref = living_ref(mob); + ref.air = ref.max_air * 10; + assertEquals(mob.air, mob.max_air); + + game.mods.after.tick.for_mod("test").subscribe(() => ref.air = ref.max_air); + ticks(400); + assert(mob.eyes_in_water); + assertEquals(mob.health, 10); +}); + Deno.test("the move control walks a mob to where it's told at minecraft's speed", async () => { const { spawn, ticks } = await floor_game(); const mob = spawn(0.5, 100, -5.5); diff --git a/tests/vitals_test.ts b/tests/vitals_test.ts index ef7e715..ca9d33e 100644 --- a/tests/vitals_test.ts +++ b/tests/vitals_test.ts @@ -186,7 +186,7 @@ Deno.test("dying takes 1 durability off every tool carried, and ones that run ou Deno.test("mods can stop or change damage, and hurt, heal and feed players", async () => { const t = await setup(); - t.game.mods.before.player_damage.for_mod("test").subscribe((event) => { + t.game.mods.before.entity_damage.for_mod("test").subscribe((event) => { if (event.cause === "fall") event.cancel = true; if (event.cause === "poison") event.amount = 1; });