Player api
This commit is contained in:
@@ -324,8 +324,15 @@ and turned as a whole: assembled from the world and put back, saved, and synced.
|
||||
into it as it moves (Create's `ContraptionCollider`, about 1000 lines, is the hardest part), and they can point at and
|
||||
use its blocks. Generic: boats with decks, falling structures and elevators would all use it.
|
||||
|
||||
**S7. Player API additions** (P1). `sneaking` on players, placements and interactions. Reach from an attribute, for the
|
||||
extendo grip. Item use events (use, release, using for some time) for the potato cannon and wands.
|
||||
**S7. Player API additions** (P1, built). `player.is_sneaking()` on the server and in client scripts, and `sneaking` in
|
||||
placement and interaction rules, for blocks like `DirectionalKineticBlock` that sneaking places the other way round.
|
||||
Like Minecraft's secondary use, sneaking with an item in hand skips the clicked block's interactions and uses or places
|
||||
the item, and an item's `on_use` gets the block it was used on, for the wrench's pickup. Reach is the
|
||||
`bworld:block_interaction_range` and `bworld:entity_interaction_range` attributes, which clients aim with, so the
|
||||
extendo grip is a modifier while it's held. `player.start_using(ticks)` uses an item over time, with `on_use_tick`,
|
||||
`on_release_using` and `on_finish_using`, for the sand paper, builder's tea and packages. The potato cannon and wands
|
||||
are plain uses, but their reload needs item cooldowns (Minecraft's `getCooldowns`, shown on the hotbar), which aren't
|
||||
built.
|
||||
|
||||
**S8. Sound** (P3). Web Audio, positional, with sound events defined in data. bworld has no sound at all yet. Create's
|
||||
whistles, presses, cranks and trains want it, but nothing breaks without it.
|
||||
|
||||
+15
-9
@@ -29,10 +29,6 @@ import { EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import type { EntityJson } from "$/common/mod_data.ts";
|
||||
import { tick_texture_animations } from "./texture_animations.ts";
|
||||
|
||||
// how far from the eyes entities can be hit, like minecraft
|
||||
const ENTITY_REACH = 3;
|
||||
// how far from the eyes blocks can be broken and used
|
||||
const BLOCK_REACH = 6;
|
||||
// holding the use button uses the held item on blocks again this often, like minecraft's 4 ticks
|
||||
const USE_REPEAT_MS = 200;
|
||||
|
||||
@@ -66,6 +62,8 @@ export class Client {
|
||||
#attacking = false;
|
||||
// when holding the use button on a block uses it again, see USE_REPEAT_MS
|
||||
#next_use = 0;
|
||||
// a use was sent and the use button hasn't been let go of since, see #handle_block_interaction
|
||||
#use_held = false;
|
||||
#stopped = false;
|
||||
// the render distance the server was last told, it sends chunks for it
|
||||
#sent_view_distance: number;
|
||||
@@ -293,7 +291,7 @@ export class Client {
|
||||
player.z,
|
||||
player.yaw,
|
||||
player.pitch,
|
||||
ENTITY_REACH,
|
||||
player.entity_interaction_range,
|
||||
(entity) =>
|
||||
entity instanceof RemotePlayer ||
|
||||
(entity instanceof RemoteEntity && !entity.dead && is_hittable(entity)),
|
||||
@@ -305,7 +303,7 @@ export class Client {
|
||||
player.z,
|
||||
player.yaw,
|
||||
player.pitch,
|
||||
picked?.distance ?? BLOCK_REACH,
|
||||
picked?.distance ?? player.block_interaction_range,
|
||||
this.game_mode.held_item()?.targets_liquids,
|
||||
);
|
||||
this.entity_hit = picked && !this.hit_result ? picked.entity : undefined;
|
||||
@@ -320,16 +318,24 @@ export class Client {
|
||||
if (!attacking || !hit) {
|
||||
this.game_mode.stop_destroy_block();
|
||||
}
|
||||
// letting go stops using an item over time, like shooting a bow, even with a screen open by then. the server
|
||||
// may not have said it's using one yet, so it's sent after every use
|
||||
if (this.#use_held && !InputManager.is_mouse_down(2)) {
|
||||
this.#use_held = false;
|
||||
this.connection.send({ type: "release_use" });
|
||||
}
|
||||
if (this.screen) {
|
||||
return;
|
||||
}
|
||||
|
||||
// a click uses right away, holding it on blocks keeps using every USE_REPEAT_MS
|
||||
// a click uses right away, holding it on blocks keeps using every USE_REPEAT_MS. not while it's using an item
|
||||
const now = performance.now();
|
||||
const use_pressed = InputManager.is_mouse_pressed(2);
|
||||
const using = use_pressed || (hit && InputManager.is_mouse_down(2) && now >= this.#next_use);
|
||||
const use_pressed = InputManager.is_mouse_pressed(2) && !this.player.using_item;
|
||||
const using = use_pressed ||
|
||||
(hit && InputManager.is_mouse_down(2) && now >= this.#next_use && !this.player.using_item);
|
||||
if (using) {
|
||||
this.#next_use = now + USE_REPEAT_MS;
|
||||
this.#use_held = true;
|
||||
}
|
||||
|
||||
// the held item swings on every click and use, and keeps swinging while breaking, like minecraft
|
||||
|
||||
@@ -38,6 +38,8 @@ const SPRINT_FOV = (1 + SPRINT_SPEED) / 2;
|
||||
const FOV_EASE = 0.5;
|
||||
// like minecraft: sneaking is 30% of walking speed and lowers the eyes 0.35, which ease there by half each tick
|
||||
const SNEAK_SPEED = 0.3;
|
||||
// using an item over time, like drawing a bow, slows walking to a fifth and stops sprinting, like minecraft
|
||||
const USING_SPEED = 0.2;
|
||||
const SNEAK_EYE_HEIGHT = PLAYER_EYE_HEIGHT - 0.35;
|
||||
const EYE_EASE = 0.5;
|
||||
// sneaking keeps it from walking off anything taller than this
|
||||
@@ -102,6 +104,11 @@ export class LocalPlayer extends Player {
|
||||
// the attack speed attribute the server sent, and when they last attacked or switched slots, for the indicator
|
||||
attack_speed = 4;
|
||||
last_attack = -Infinity;
|
||||
// how far it reaches blocks and entities, the attributes the server sent
|
||||
block_interaction_range = 6;
|
||||
entity_interaction_range = 3;
|
||||
// using its held item over time, as the server says, see ctx's player.start_using
|
||||
using_item = false;
|
||||
|
||||
// blocks per second, peaks about 1.25 blocks up with the entity's gravity and drag
|
||||
jump_force = 9.23;
|
||||
@@ -111,7 +118,10 @@ export class LocalPlayer extends Player {
|
||||
#ticks_since_sent = 0;
|
||||
// counts down every tick, letting go of jump clears it
|
||||
#jump_delay = 0;
|
||||
// the sneaking pose, which flying doesn't have
|
||||
sneaking = false;
|
||||
// holding the sneak key, flying or not, which is what the server is told for placing and using things
|
||||
holding_sneak = false;
|
||||
// stays on after letting go of the key, see #update_sprinting
|
||||
sprinting = false;
|
||||
// what the server says, see /fly
|
||||
@@ -139,6 +149,7 @@ export class LocalPlayer extends Player {
|
||||
// flying ignores water
|
||||
this.#in_water = !this.flying && this.in_water;
|
||||
const was_swimming = this.swimming;
|
||||
const was_holding_sneak = this.holding_sneak;
|
||||
const input = this.client.screen ? NO_INPUT : this.#read_input();
|
||||
this.#apply_input(input);
|
||||
// after sprinting is, so letting go stands it up the same tick
|
||||
@@ -185,7 +196,10 @@ export class LocalPlayer extends Player {
|
||||
if (Math.abs(this.vx) < MIN_SPEED) this.vx = 0;
|
||||
if (Math.abs(this.vz) < MIN_SPEED) this.vz = 0;
|
||||
this.update_swim_animation();
|
||||
this.#send_position((this.on_ground && !was_on_ground) || this.swimming !== was_swimming);
|
||||
this.#send_position(
|
||||
(this.on_ground && !was_on_ground) || this.swimming !== was_swimming ||
|
||||
this.holding_sneak !== was_holding_sneak,
|
||||
);
|
||||
}
|
||||
|
||||
// like voxelibre: sprinting with the eyes under water starts it, and it keeps going while it sprints in water, along
|
||||
@@ -277,12 +291,14 @@ export class LocalPlayer extends Player {
|
||||
let { x: input_x, z: input_z } = input;
|
||||
const size = Math.hypot(input_x, input_z);
|
||||
if (size > 0) {
|
||||
input_x /= size;
|
||||
input_z /= size;
|
||||
const scale = (this.using_item ? USING_SPEED : 1) / size;
|
||||
input_x *= scale;
|
||||
input_z *= scale;
|
||||
}
|
||||
|
||||
// sneaking while flying goes down instead
|
||||
this.sneaking = input.sneak && !this.flying;
|
||||
this.holding_sneak = input.sneak;
|
||||
const sin = Math.sin(this.yaw);
|
||||
const cos = Math.cos(this.yaw);
|
||||
this.#update_sprinting(input, sin, cos);
|
||||
@@ -325,7 +341,8 @@ export class LocalPlayer extends Player {
|
||||
// until it stops moving forward, sneaks, gets hungry or runs into a wall, even after letting go of the key
|
||||
#update_sprinting(input: MoveInput, sin: number, cos: number) {
|
||||
// like minecraft, flying sprints even hungry, and sneaking to go down doesn't stop it
|
||||
const can_sprint = input.z < 0 && (this.flying || (!input.sneak && this.food > SPRINT_MIN_FOOD));
|
||||
const can_sprint = input.z < 0 && !this.using_item &&
|
||||
(this.flying || (!input.sneak && this.food > SPRINT_MIN_FOOD));
|
||||
// how far it's looking into what it hit in the last move, the way it's facing is -sin, -cos
|
||||
const into_wall = sin * this.colliding_x + cos * this.colliding_z;
|
||||
if (!can_sprint || into_wall > SPRINT_WALL_ANGLE) {
|
||||
@@ -357,6 +374,7 @@ export class LocalPlayer extends Player {
|
||||
pitch: this.pitch,
|
||||
teleport: this.teleport_id,
|
||||
...(this.swimming && { swimming: true }),
|
||||
...(this.holding_sneak && { sneaking: true }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+9
-3
@@ -88,8 +88,13 @@ export class MultiPlayerGameMode {
|
||||
const held = this.held_item();
|
||||
const value = level.get_block_value(hit.x, hit.y, hit.z);
|
||||
const used = (held?.targets_liquids && liquid_block(value, block_info)) || block_info;
|
||||
const interaction = { face: hit.face, hit: hit.hit };
|
||||
if (block_rules.interact(used, hit.x, hit.y, hit.z, interaction, this.client.player.yaw)) return;
|
||||
// sneaking with an item skips the block, like on the server
|
||||
const sneaking = this.client.player.holding_sneak;
|
||||
const skips_block = sneaking && held !== undefined;
|
||||
const interaction = { face: hit.face, hit: hit.hit, sneaking };
|
||||
if (!skips_block && block_rules.interact(used, hit.x, hit.y, hit.z, interaction, this.client.player.yaw)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// guess that it places the held block, unless the block does something when used. the same rules as the server:
|
||||
// into the clicked block when it's replaceable, and only where place_in and place_on allow
|
||||
@@ -109,6 +114,7 @@ export class MultiPlayerGameMode {
|
||||
...target,
|
||||
face: hit.face,
|
||||
hit: hit.hit,
|
||||
sneaking,
|
||||
}),
|
||||
place_block,
|
||||
level.get_block_value(target.x, target.y, target.z),
|
||||
@@ -120,7 +126,7 @@ export class MultiPlayerGameMode {
|
||||
level.get_block_value(target.x, target.y, target.z),
|
||||
below_id,
|
||||
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, place_value!));
|
||||
if (!block_info.interactive && place_id && placeable) {
|
||||
if ((!block_info.interactive || skips_block) && place_id && placeable) {
|
||||
level.add_block({ ...target, id: place_id }, place_value! >>> 16);
|
||||
predict_neighbors(target.x, target.y, target.z);
|
||||
const slot = this.#held_slot();
|
||||
|
||||
@@ -286,6 +286,7 @@ function client_context(listing: ModListing): ClientContext {
|
||||
return rules_world.season_at(x, z);
|
||||
},
|
||||
is_swimming: () => need_client().player.swimming,
|
||||
is_sneaking: () => need_client().player.holding_sneak,
|
||||
},
|
||||
world: {
|
||||
get_block(x, y, z) {
|
||||
|
||||
@@ -84,8 +84,13 @@ export class ClientPacketListener {
|
||||
client.player.saturation = message.saturation;
|
||||
client.player.air = message.air;
|
||||
break;
|
||||
case "attack_speed":
|
||||
client.player.attack_speed = message.value;
|
||||
case "attributes":
|
||||
client.player.attack_speed = message.attack_speed;
|
||||
client.player.block_interaction_range = message.block_interaction_range;
|
||||
client.player.entity_interaction_range = message.entity_interaction_range;
|
||||
break;
|
||||
case "using_item":
|
||||
client.player.using_item = message.using;
|
||||
break;
|
||||
case "flying":
|
||||
client.player.flying = message.flying;
|
||||
|
||||
@@ -16,14 +16,15 @@ export interface ClientContext {
|
||||
// the way jei's recipes screen checks options.keyInventory
|
||||
options: KeyMappings;
|
||||
net: ClientNet;
|
||||
// is_swimming: lying flat in water in the 0.8 tall box, like minecraft's isSwimming. biome and season are where
|
||||
// their feet are, undefined until that chunk loads
|
||||
// is_swimming: lying flat in water in the 0.8 tall box, like minecraft's isSwimming. is_sneaking: holding the sneak
|
||||
// key, like isShiftKeyDown. biome and season are where their feet are, undefined until that chunk loads
|
||||
player: {
|
||||
readonly name: string;
|
||||
readonly position: Readonly<Position>;
|
||||
readonly biome: Id | undefined;
|
||||
readonly season: Season | undefined;
|
||||
is_swimming(): boolean;
|
||||
is_sneaking(): boolean;
|
||||
};
|
||||
// read only, what this client sees
|
||||
world: {
|
||||
|
||||
@@ -68,7 +68,21 @@ export interface BlockComponent<P = any> {
|
||||
export interface ItemComponent<P = any> {
|
||||
on_create?(item: ItemStack, params: P): void;
|
||||
get_lore?(item: ItemStack, params: P): string;
|
||||
on_use?(item: ItemStack, params: P, player: Player): void;
|
||||
// right clicked while holding it, at nothing or at the block in target, like minecraft's use and useOn
|
||||
on_use?(item: ItemStack, params: P, player: Player, target: UseTarget | undefined): void;
|
||||
// using it over time, see Player.start_using. every tick while they do, ticks counting from 1, like onUseTick
|
||||
on_use_tick?(item: ItemStack, params: P, player: Player, ticks: number): void;
|
||||
// they let go of use before it finished, like a bow being shot, after using it for ticks. like releaseUsing
|
||||
on_release_using?(item: ItemStack, params: P, player: Player, ticks: number): void;
|
||||
// they used it for as long as start_using said, like food being eaten. like finishUsingItem
|
||||
on_finish_using?(item: ItemStack, params: P, player: Player): void;
|
||||
}
|
||||
|
||||
// the block an item was used on, the face that was clicked, and where on the block (0 to 1 on each axis)
|
||||
export interface UseTarget {
|
||||
readonly block: BlockRef;
|
||||
readonly face: Face;
|
||||
readonly hit: readonly [number, number, number];
|
||||
}
|
||||
|
||||
// P is the component's params from the effect json. see docs/modding/entities/effects.md
|
||||
@@ -328,6 +342,15 @@ export interface Player {
|
||||
remove_effect(id: Id): boolean;
|
||||
// lying flat in water in the 0.8 tall box, like minecraft's isSwimming. their client says when
|
||||
is_swimming(): boolean;
|
||||
// holding the sneak key, flying or not, like minecraft's isShiftKeyDown. their client says when
|
||||
is_sneaking(): boolean;
|
||||
// keeps using the held item while they hold use, like minecraft's startUsingItem: its components' on_use_tick runs
|
||||
// every tick, then on_finish_using after ticks, or on_release_using if they let go first. -1 uses it until they let
|
||||
// go, like a bow. it slows them down like sneaking. for an on_use to call. switching away from it stops it
|
||||
start_using(ticks: number): void;
|
||||
// stops using it without on_release_using or on_finish_using, like stopUsingItem
|
||||
stop_using(): void;
|
||||
is_using(): boolean;
|
||||
}
|
||||
|
||||
export interface EffectOptions {
|
||||
|
||||
@@ -93,19 +93,23 @@ export interface SharedBlock extends Position {
|
||||
}
|
||||
|
||||
// a player placing a block at x y z by clicking face of the block next to it, at hit (0 to 1 on each axis of that
|
||||
// block), like minecraft's BlockPlaceContext. facing is the way the player looks, along the ground
|
||||
// block), like minecraft's BlockPlaceContext. facing is the way the player looks, along the ground, and sneaking
|
||||
// whether they hold the sneak key, for blocks placed another way round when they do
|
||||
export interface BlockPlacement extends Position {
|
||||
readonly face: Face;
|
||||
readonly hit: readonly [number, number, number];
|
||||
readonly facing: "north" | "east" | "south" | "west";
|
||||
readonly sneaking: boolean;
|
||||
}
|
||||
|
||||
// a player right clicking face of a block, at hit (0 to 1 on each axis of the block), like minecraft's BlockHitResult.
|
||||
// facing is the way the player looks, along the ground
|
||||
// facing is the way the player looks, along the ground, and sneaking whether they hold the sneak key. sneaking with
|
||||
// an item in hand doesn't interact at all, the item is used or placed instead
|
||||
export interface BlockInteraction {
|
||||
readonly face: Face;
|
||||
readonly hit: readonly [number, number, number];
|
||||
readonly facing: "north" | "east" | "south" | "west";
|
||||
readonly sneaking: boolean;
|
||||
}
|
||||
|
||||
// P is the component's params from the block json
|
||||
|
||||
+11
-4
@@ -10,7 +10,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 = 20;
|
||||
export const PROTOCOL_VERSION = 21;
|
||||
|
||||
export interface PlayerInfo {
|
||||
id: string;
|
||||
@@ -95,7 +95,8 @@ export type ClientMessage =
|
||||
// answers chunk_batch_finished once the batch is loaded, with how many chunks a tick the client can take
|
||||
| { type: "chunk_batch_received"; chunks_per_tick: number }
|
||||
// teleport is the id of the last teleport the client heard of. moves from before the latest one are ignored.
|
||||
// swimming is whether they're swimming, sent right away when it changes
|
||||
// swimming is whether they're swimming and sneaking whether they hold the sneak key, both sent right away when they
|
||||
// change
|
||||
| {
|
||||
type: "move";
|
||||
x: number;
|
||||
@@ -105,6 +106,7 @@ export type ClientMessage =
|
||||
pitch: number;
|
||||
teleport?: number;
|
||||
swimming?: boolean;
|
||||
sneaking?: boolean;
|
||||
}
|
||||
// seq numbers what this client guessed for it, the server answers with block_ack. see client/level/block_predictions.ts
|
||||
| { type: "break_block"; x: number; y: number; z: number; seq?: number }
|
||||
@@ -116,6 +118,8 @@ export type ClientMessage =
|
||||
| { type: "swing" }
|
||||
// right click without looking at a block, for items' on_use
|
||||
| { type: "use_item" }
|
||||
// the use button let go of after a use_item or use_block, which stops using an item over time, like shooting a bow
|
||||
| { type: "release_use" }
|
||||
// right click on a block: interact with it, or place the held block against `face`. hit is where on the block it
|
||||
// clicked, 0 to 1 on each axis, like minecraft's click location. seq is like break_block's
|
||||
| { type: "use_block"; x: number; y: number; z: number; face: Faces; hit?: [number, number, number]; seq?: number }
|
||||
@@ -249,8 +253,11 @@ export type ServerMessage =
|
||||
| { type: "suggestions"; id: number; start: number; suggestions: { text: string; tooltip?: string }[] }
|
||||
// the player's own health, max health, hunger, saturation and air (out of 20, 2 a bubble), when they change
|
||||
| { type: "vitals"; health: number; max_health: number; food: number; saturation: number; air: number }
|
||||
// the player's own attack speed attribute, when it changes, for the attack indicator under the crosshair
|
||||
| { type: "attack_speed"; value: number }
|
||||
// the player's own attributes their client needs, when they change: attack speed for the attack indicator under the
|
||||
// crosshair, and how far they reach blocks and entities
|
||||
| { type: "attributes"; attack_speed: number; block_interaction_range: number; entity_interaction_range: number }
|
||||
// whether they're using their held item over time, like drawing a bow, see ctx's player.start_using
|
||||
| { type: "using_item"; using: boolean }
|
||||
// whether the player flies, see /fly, when it changes
|
||||
| { type: "flying"; flying: boolean }
|
||||
// the player's own effects that show an icon, when they change. duration is in ticks, -1 for forever, and the
|
||||
|
||||
@@ -115,11 +115,12 @@ a slab's sides and plants aren't.
|
||||
### Placing
|
||||
|
||||
`state_for_placement` picks the states a block is placed with, like Minecraft's `getStateForPlacement`. `placement` is
|
||||
`{ x, y, z, face, hit, facing }`: where it's going, the face of the block that was clicked, where on that block the
|
||||
click was (from 0 to 1 on each axis), and the way the player looks along the ground. It returns states by name, and the
|
||||
rest keep their defaults, except that a 2 bit `facing` already faces the player. It runs before the server checks that
|
||||
no one is in the way, so that's checked against the shape the block will really have. A trapdoor clicked onto the upper
|
||||
half of a block's side hangs in the top half:
|
||||
`{ x, y, z, face, hit, facing, sneaking }`: where it's going, the face of the block that was clicked, where on that
|
||||
block the click was (from 0 to 1 on each axis), the way the player looks along the ground, and whether they're
|
||||
[sneaking](../entities/players.md#sneaking), for blocks that sneaking places the other way round. It returns states by
|
||||
name, and the rest keep their defaults, except that a 2 bit `facing` already faces the player. It runs before the server
|
||||
checks that no one is in the way, so that's checked against the shape the block will really have. A trapdoor clicked
|
||||
onto the upper half of a block's side hangs in the top half:
|
||||
|
||||
```ts
|
||||
state_for_placement(placement): Record<string, number> {
|
||||
@@ -142,8 +143,10 @@ the block had no components.
|
||||
A rule's `on_interact` also runs on the clicking player's client, so they see what it does right away instead of waiting
|
||||
for the server, like a trapdoor opening. It's for clicks that only change states with `ctx.world.set_state`, like
|
||||
Minecraft's `useWithoutItem`: anything that needs the server, like opening a screen, giving items or tile data, goes in
|
||||
the handler. `interaction` is `{ face, hit, facing }`: the face that was clicked, where on it (from 0 to 1 on each
|
||||
axis), and the way the player looks along the ground. The trapdoor's is in `mods/bworld/scripts/shared.ts`:
|
||||
the handler. `interaction` is `{ face, hit, facing, sneaking }`: the face that was clicked, where on it (from 0 to 1 on
|
||||
each axis), the way the player looks along the ground, and whether they're sneaking. A player sneaking with an item in
|
||||
hand doesn't interact at all: no `on_interact` runs, and the item is used or placed against the block instead. The
|
||||
trapdoor's is in `mods/bworld/scripts/shared.ts`:
|
||||
|
||||
```ts
|
||||
on_interact(block) {
|
||||
|
||||
@@ -61,9 +61,10 @@ showed. These events fire for **every** player's actions, since they all go thro
|
||||
### Order
|
||||
|
||||
Handlers run in the order they subscribed, and mods' `setup` functions run in [load order](registries.md#loading). For
|
||||
`block_interact`, the before event runs first, then the block's own components' `on_interact`, rules before handlers. If
|
||||
no component handled the click and the held item has no `on_use`, the held block is placed, which fires `block_place`.
|
||||
Cancelling it undoes what the clicking player's client guessed, like a trapdoor it showed opening.
|
||||
`block_interact`, the before event runs first, then the block's own components' `on_interact`, rules before handlers,
|
||||
unless the player is [sneaking](../entities/players.md#sneaking) with an item in hand. If no component handled the click
|
||||
and the held item has no `on_use`, the held block is placed, which fires `block_place`. Cancelling it undoes what the
|
||||
clicking player's client guessed, like a trapdoor it showed opening.
|
||||
|
||||
## Errors
|
||||
|
||||
|
||||
@@ -52,6 +52,11 @@ interface Player {
|
||||
remove_effect(id: string): boolean;
|
||||
|
||||
is_swimming(): boolean; // see Swimming
|
||||
is_sneaking(): boolean; // see Sneaking
|
||||
|
||||
start_using(ticks: number): void; // see Using Items Over Time
|
||||
stop_using(): void;
|
||||
is_using(): boolean;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -64,7 +69,7 @@ what a player is looking at, like Minecraft's `getPlayerPOVHitResult`:
|
||||
```ts
|
||||
const eye = player.eye_position;
|
||||
const look = player.look_direction;
|
||||
const reach = 5;
|
||||
const reach = player.attribute("bworld:block_interaction_range");
|
||||
const to = { x: eye.x + look.x * reach, y: eye.y + look.y * reach, z: eye.z + look.z * reach };
|
||||
const hit = ctx.world.raycast(eye, to, { liquids: "source_only" });
|
||||
```
|
||||
@@ -96,10 +101,12 @@ even when their game isn't running, like in a background tab.
|
||||
|
||||
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. |
|
||||
| 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. |
|
||||
| `bworld:block_interaction_range` | 6 | How far from their eyes they break and use blocks, in blocks. |
|
||||
| `bworld:entity_interaction_range` | 3 | How far from their eyes they hit entities, in blocks. |
|
||||
|
||||
```ts
|
||||
player.add_modifier("bworld:attack_damage", { id: "my_mod:rage", amount: 2, operation: "add_value" });
|
||||
@@ -116,6 +123,26 @@ Like Minecraft, an attack right after the last one, or right after changing the
|
||||
damage, rising to full after `20 / attack_speed` ticks. A bar under the crosshair shows it filling up, and the server
|
||||
sends players their `attack_speed` whenever it changes so the bar matches.
|
||||
|
||||
The two ranges are how far a player reaches, like NeoForge's `BLOCK_INTERACTION_RANGE` and `ENTITY_INTERACTION_RANGE`.
|
||||
Their client aims that far, and the server allows a little more, for where they moved since they aimed. A tool that
|
||||
reaches further gives a modifier while it's held, like Create's extendo grip:
|
||||
|
||||
```ts
|
||||
ctx.events.after.tick.subscribe(() => {
|
||||
for (const player of ctx.players.all()) {
|
||||
if (player.held_item?.id === "copper_tools:grabber") {
|
||||
player.add_modifier("bworld:block_interaction_range", {
|
||||
id: "copper_tools:grabber",
|
||||
amount: 3,
|
||||
operation: "add_value",
|
||||
});
|
||||
} else {
|
||||
player.remove_modifier("bworld:block_interaction_range", "copper_tools:grabber");
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Status Effects
|
||||
|
||||
Players can have any mod's [status effects](effects.md), like the base game's `bworld:speed`, `bworld:regeneration` or
|
||||
@@ -155,6 +182,24 @@ client scripts, where `ctx.player.is_swimming()` is about the player on this cli
|
||||
if (player.is_swimming()) player.add_effect("bworld:speed", 20);
|
||||
```
|
||||
|
||||
## Sneaking
|
||||
|
||||
`player.is_sneaking()` says whether a player holds the sneak key, like NeoForge's `isShiftKeyDown()`. It's the key, not
|
||||
the pose: a player flying down holds it too. Their client tells the server as soon as it changes. In client scripts,
|
||||
`ctx.player.is_sneaking()` is about the player on this client.
|
||||
|
||||
Sneaking changes what right clicking a block does, like Minecraft: with an item in hand, the block isn't used at all,
|
||||
and the item is used or placed against it instead. That's how a block is placed against a chest without opening it. With
|
||||
an empty hand, the block is used as usual, and its handlers can read `player.is_sneaking()`. Blocks' placement and
|
||||
interaction rules get `sneaking` too, see [Placing](../blocks/components.md#placing).
|
||||
|
||||
## Using Items Over Time
|
||||
|
||||
Some items are used for as long as the use button is held, like drawing a bow or eating in Minecraft. An item's `on_use`
|
||||
starts it with `player.start_using(ticks)`, and the item's components hear how it goes, see
|
||||
[Using Over Time](../items/index.md#using-over-time). `stop_using()` ends it without either ending, and `is_using()`
|
||||
says whether they're using one. While they are, they walk at a fifth of their speed and can't sprint.
|
||||
|
||||
## Death
|
||||
|
||||
When a player dies, everything they carried falls out where they died, and their tools lose durability (see
|
||||
|
||||
@@ -136,8 +136,8 @@ ctx.components.register_item<{ max_water: number }>("bworld:watering_can", {
|
||||
get_lore(item, params) {
|
||||
return `Water: ${(item.data as { water: number }).water}/${params.max_water}`;
|
||||
},
|
||||
on_use(item, params, player) {
|
||||
// right clicked while holding it
|
||||
on_use(item, params, player, target) {
|
||||
// right clicked while holding it, at target's block or at nothing
|
||||
},
|
||||
});
|
||||
```
|
||||
@@ -148,11 +148,14 @@ and items list them with their parameters:
|
||||
"components": { "bworld:watering_can": { "max_water": 32 } }
|
||||
```
|
||||
|
||||
| Handler | Called when |
|
||||
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `on_create(item, params)` | A stack of it is made: crafted, given, dropped by a block, and so on. |
|
||||
| `get_lore(item, params)` | The server sends the stack to a player. Returns extra tooltip text for that stack, shown under the item's own `lore`. It isn't saved. |
|
||||
| `on_use(item, params, player)` | A player right clicks while holding it, at nothing or at a block. |
|
||||
| Handler | Called when |
|
||||
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `on_create(item, params)` | A stack of it is made: crafted, given, dropped by a block, and so on. |
|
||||
| `get_lore(item, params)` | The server sends the stack to a player. Returns extra tooltip text for that stack, shown under the item's own `lore`. It isn't saved. |
|
||||
| `on_use(item, params, player, target)` | A player right clicks while holding it, at nothing or at a block. |
|
||||
| `on_use_tick(item, params, player, ticks)` | Every tick while it's [used over time](#using-over-time), `ticks` counting from 1. |
|
||||
| `on_release_using(item, params, player, ticks)` | They let go of use before it finished, after using it for `ticks`. |
|
||||
| `on_finish_using(item, params, player)` | They used it for as long as `start_using` said. |
|
||||
|
||||
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.
|
||||
@@ -160,8 +163,41 @@ 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 the base game's curios slots do for `bworld:curio_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).
|
||||
At a block, `target` is `{ block, face, hit }`: the block, with its tile data like a block component's, the face that
|
||||
was clicked, and where on the block (0 to 1 on each axis), like Minecraft's `useOn`. At nothing it's `undefined`. A
|
||||
player [sneaking](../entities/players.md#sneaking) with the item skips the block's own interaction, so a wrench can pick
|
||||
up a block instead of using it:
|
||||
|
||||
```ts
|
||||
on_use(item, params, player, target) {
|
||||
if (target && player.is_sneaking()) ctx.world.break_block(target.block.x, target.block.y, target.block.z);
|
||||
},
|
||||
```
|
||||
|
||||
### Using Over Time
|
||||
|
||||
An item can be used for as long as the use button is held, like a bow or Minecraft's food. Its `on_use` calls
|
||||
`player.start_using(ticks)`, then:
|
||||
|
||||
- `on_use_tick` runs every tick while they hold use, with how many ticks they've used it.
|
||||
- `on_finish_using` runs once they've held it for `ticks`, and it stops.
|
||||
- `on_release_using` runs instead if they let go first, with how long they held it, like a bow shooting.
|
||||
|
||||
`-1` keeps it going until they let go. Switching to another slot, or the item being used up or moved, stops it without
|
||||
either ending. While using an item, a player walks at a fifth of their speed and can't sprint, and clicking again does
|
||||
nothing.
|
||||
|
||||
```ts
|
||||
ctx.components.register_item("copper_tools:sling", {
|
||||
on_use(item, params, player) {
|
||||
player.start_using(-1);
|
||||
},
|
||||
on_release_using(item, params, player, ticks) {
|
||||
const power = Math.min(ticks / 20, 1); // full power after a second
|
||||
// throw something with it
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Server Script Helpers
|
||||
|
||||
|
||||
@@ -46,6 +46,9 @@ export const ATTRIBUTES = {
|
||||
// blocks a fall can be without hurting
|
||||
safe_fall_distance: attribute("safe_fall_distance", 3, -1024, 1024),
|
||||
fall_damage_multiplier: attribute("fall_damage_multiplier", 1, 0, 100),
|
||||
// how far a player reaches, in blocks from their eyes: blocks they break and use, and entities they hit
|
||||
block_interaction_range: attribute("block_interaction_range", 6, 0, 64),
|
||||
entity_interaction_range: attribute("entity_interaction_range", 3, 0, 64),
|
||||
} satisfies Record<string, AttributeType>;
|
||||
|
||||
const BY_ID = new Map<string, AttributeType>(Object.values(ATTRIBUTES).map((type) => [type.id, type]));
|
||||
|
||||
+110
-32
@@ -46,7 +46,7 @@ import { collision_shape_at, type Shape } from "$/common/block_shapes.ts";
|
||||
import { physics } from "$/common/physics.ts";
|
||||
import { EXHAUSTION } from "./vitals.ts";
|
||||
import { entity_ref, ModRuntime, new_stack, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
|
||||
import type { LootContext } from "$/common/mod_api/server.ts";
|
||||
import type { LootContext, UseTarget } from "$/common/mod_api/server.ts";
|
||||
import type { EntityJson } from "$/common/mod_data.ts";
|
||||
import {
|
||||
argument,
|
||||
@@ -85,8 +85,9 @@ import { damage_source, type DamageSource, type SavedEntity } from "./entity/ent
|
||||
import { effect_type, effect_type_ids, EffectInstance } from "./entity/effects.ts";
|
||||
import { ATTRIBUTES } from "./entity/attributes.ts";
|
||||
|
||||
// how far from a player's eyes a block can be changed, a bit more than the client's reach
|
||||
const MAX_REACH = 8;
|
||||
// how much further than their reach attributes the server lets a player use blocks and hit entities, for where they
|
||||
// moved since their client aimed
|
||||
const REACH_LEEWAY = 2;
|
||||
// how far past a player's box items get picked up from, sideways and up or down, like minecraft
|
||||
const PICKUP_REACH_XZ = 1;
|
||||
const PICKUP_REACH_Y = 0.5;
|
||||
@@ -372,6 +373,7 @@ export class GameServer {
|
||||
this.#new_days();
|
||||
this.liquids.tick(this.#tick);
|
||||
this.#tick_vitals();
|
||||
for (const player of this.#players.values()) this.#tick_using(player);
|
||||
this.#tick_entities();
|
||||
|
||||
this.mods.tick();
|
||||
@@ -892,6 +894,7 @@ export class GameServer {
|
||||
this.#on_move(player, x, y, z);
|
||||
Object.assign(player, { x, y, z, yaw, pitch });
|
||||
player.set_swimming(message.swimming === true);
|
||||
player.sneaking = message.sneaking === true;
|
||||
this.#broadcast(player_move(player), player);
|
||||
this.#update_view(player);
|
||||
break;
|
||||
@@ -928,16 +931,25 @@ export class GameServer {
|
||||
player.attack_strength_ticker = 0;
|
||||
break;
|
||||
case "use_item":
|
||||
this.#use_item(player);
|
||||
// a client that hadn't heard it's using an item yet, still clicking
|
||||
if (!player.using) this.#use_item(player);
|
||||
break;
|
||||
case "release_use":
|
||||
this.#release_using(player);
|
||||
break;
|
||||
case "use_block":
|
||||
if (is_block_position(message.x, message.y, message.z) && faces.includes(message.face)) {
|
||||
// the middle of the block when a client doesn't say, or says something that isn't on it
|
||||
const hit = Array.isArray(message.hit) && message.hit.length === 3 &&
|
||||
message.hit.every((v) => typeof v === "number" && v >= 0 && v <= 1)
|
||||
? message.hit
|
||||
: [0.5, 0.5, 0.5];
|
||||
this.#use_block(player, message.x, message.y, message.z, message.face, hit);
|
||||
if (player.using) {
|
||||
// a client that hadn't heard it's using an item yet: what it guessed the click did, it didn't
|
||||
this.#correct_use(player, message.x, message.y, message.z, message.face);
|
||||
} else {
|
||||
// the middle of the block when a client doesn't say, or says something that isn't on it
|
||||
const hit = Array.isArray(message.hit) && message.hit.length === 3 &&
|
||||
message.hit.every((v) => typeof v === "number" && v >= 0 && v <= 1)
|
||||
? message.hit
|
||||
: [0.5, 0.5, 0.5];
|
||||
this.#use_block(player, message.x, message.y, message.z, message.face, hit);
|
||||
}
|
||||
}
|
||||
this.#ack(player, message.seq);
|
||||
break;
|
||||
@@ -1042,11 +1054,11 @@ export class GameServer {
|
||||
|
||||
// right click at nothing: eating, or the item's on_use
|
||||
#use_item(player: ServerPlayer): boolean {
|
||||
return this.#eat(player) || this.#use_item_components(player);
|
||||
return this.#eat(player) || this.#use_item_components(player, undefined);
|
||||
}
|
||||
|
||||
// the held item's on_use handlers, returns whether it has any
|
||||
#use_item_components(player: ServerPlayer): boolean {
|
||||
// the held item's on_use handlers, with the block it was used on if it was, returns whether it has any
|
||||
#use_item_components(player: ServerPlayer, target: UseTarget | undefined): boolean {
|
||||
const held = player.held_item;
|
||||
if (!held) {
|
||||
return false;
|
||||
@@ -1058,19 +1070,71 @@ export class GameServer {
|
||||
const player_api = this.mods.player(player);
|
||||
const item = player_api.held_item!;
|
||||
for (const { mod, id, component, params } of components) {
|
||||
run_guarded(mod, `${id} on_use`, () => component.on_use!(item, params, player_api));
|
||||
run_guarded(mod, `${id} on_use`, () => component.on_use!(item, params, player_api, target));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// a script's start_using: the held item is used over time from now, while they hold use
|
||||
start_using(player: ServerPlayer, duration: number) {
|
||||
const held = player.held_item;
|
||||
if (!held) throw new Error("start_using needs an item in their hand");
|
||||
player.using = { slot: player.selected_slot, type_id: held.type_id, ticks: 0, duration };
|
||||
}
|
||||
|
||||
// the held item's on_use_tick handlers every tick it's used, and on_finish_using once it's used for its duration.
|
||||
// switching away from it, or it being used up, dropped or swapped, stops it without either, like minecraft
|
||||
#tick_using(player: ServerPlayer) {
|
||||
const using = player.using;
|
||||
if (!using) return;
|
||||
if (!player.alive || player.selected_slot !== using.slot || player.held_item?.type_id !== using.type_id) {
|
||||
player.using = undefined;
|
||||
return;
|
||||
}
|
||||
using.ticks += 1;
|
||||
this.#run_using(player, "on_use_tick", using.ticks);
|
||||
// a handler can stop it, or start it over
|
||||
if (player.using === using && using.duration !== -1 && using.ticks >= using.duration) {
|
||||
player.using = undefined;
|
||||
this.#run_using(player, "on_finish_using");
|
||||
}
|
||||
}
|
||||
|
||||
// they let go of use: on_release_using with how long they used it, when they were using something
|
||||
#release_using(player: ServerPlayer) {
|
||||
const using = player.using;
|
||||
if (!using) return;
|
||||
player.using = undefined;
|
||||
if (player.selected_slot === using.slot && player.held_item?.type_id === using.type_id) {
|
||||
this.#run_using(player, "on_release_using", using.ticks);
|
||||
}
|
||||
}
|
||||
|
||||
#run_using(player: ServerPlayer, handler: "on_use_tick" | "on_release_using" | "on_finish_using", ticks = 0) {
|
||||
const player_api = this.mods.player(player);
|
||||
const item = player_api.held_item;
|
||||
if (!item) return;
|
||||
for (const { mod, id, component, params } of this.mods.item_components_of(item.id)) {
|
||||
const run = component[handler];
|
||||
if (run) run_guarded(mod, `${id} ${handler}`, () => run(item, params, player_api, ticks));
|
||||
}
|
||||
}
|
||||
|
||||
// what a client may have guessed clicking face of the block at x y z did, to the block and to where a block would
|
||||
// be placed, put back to what's really there
|
||||
#correct_use(player: ServerPlayer, x: number, y: number, z: number, face: Faces) {
|
||||
const target = placement_target(x, y, z, FACE_OFFSETS[face], this.world.get_block_info(x, y, z));
|
||||
this.#correct(player, x, y, z);
|
||||
this.#correct(player, target.x, target.y, target.z);
|
||||
}
|
||||
|
||||
#use_block(player: ServerPlayer, x: number, y: number, z: number, face: Faces, hit: number[]) {
|
||||
const info = this.world.get_block_info(x, y, z);
|
||||
const target = placement_target(x, y, z, FACE_OFFSETS[face], info);
|
||||
const [tx, ty, tz] = [target.x, target.y, target.z];
|
||||
|
||||
if (!info || !this.#in_reach(player, x, y, z)) {
|
||||
this.#correct(player, x, y, z);
|
||||
this.#correct(player, tx, ty, tz);
|
||||
this.#correct_use(player, x, y, z, face);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1086,31 +1150,35 @@ export class GameServer {
|
||||
this.mods.before.block_interact.emit(before_interact);
|
||||
if (before_interact.cancel) {
|
||||
// the client may have guessed the shared rules' on_interact, or a placement
|
||||
this.#correct(player, x, y, z);
|
||||
this.#correct(player, tx, ty, tz);
|
||||
this.#correct_use(player, x, y, z, face);
|
||||
return;
|
||||
}
|
||||
|
||||
// the shared rules first, the ones the client guessed, then the server script's
|
||||
let handled = this.mods.rules.interact(used, x, y, z, { face, hit: [hit[0], hit[1], hit[2]] }, player.yaw);
|
||||
for (const { mod, id: component_id, component, params } of this.mods.components_of(used.id)) {
|
||||
if (component.on_interact) {
|
||||
handled = run_guarded(mod, `${component_id} on_interact`, () =>
|
||||
component.on_interact!(block, params, player_api)) ===
|
||||
true || handled;
|
||||
// the shared rules first, the ones the client guessed, then the server script's. sneaking with an item skips the
|
||||
// block, like minecraft's secondary use, so a block can be placed against a chest
|
||||
const sneaking = player.sneaking;
|
||||
let handled = false;
|
||||
if (!(sneaking && held_slot.has_item())) {
|
||||
const interaction = { face, hit: [hit[0], hit[1], hit[2]] as [number, number, number], sneaking };
|
||||
handled = this.mods.rules.interact(used, x, y, z, interaction, player.yaw);
|
||||
for (const { mod, id: component_id, component, params } of this.mods.components_of(used.id)) {
|
||||
if (component.on_interact) {
|
||||
handled = run_guarded(mod, `${component_id} on_interact`, () =>
|
||||
component.on_interact!(block, params, player_api)) ===
|
||||
true || handled;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (handled) {
|
||||
this.mods.after.block_interact.emit(interact);
|
||||
// the client guessed the shared rules' on_interact from what it sees, which might not be what's here. it didn't
|
||||
// guess a placement for interactive blocks, but it might have for others
|
||||
this.#correct(player, x, y, z);
|
||||
this.#correct(player, tx, ty, tz);
|
||||
this.#correct_use(player, x, y, z, face);
|
||||
return;
|
||||
}
|
||||
|
||||
// an item that does something when used does that instead of being placed
|
||||
if (this.#use_item_components(player)) {
|
||||
if (this.#use_item_components(player, { block, face, hit: [hit[0], hit[1], hit[2]] })) {
|
||||
this.#correct(player, tx, ty, tz);
|
||||
return;
|
||||
}
|
||||
@@ -1145,6 +1213,7 @@ export class GameServer {
|
||||
z: tz,
|
||||
face,
|
||||
hit: [hit[0], hit[1], hit[2]],
|
||||
sneaking: player.sneaking,
|
||||
}),
|
||||
placing,
|
||||
this.world.get_block_value(tx, ty, tz),
|
||||
@@ -1894,8 +1963,14 @@ export class GameServer {
|
||||
[health, max_health, food, saturation, air],
|
||||
() => ({ type: "vitals", health, max_health, food, saturation, air }),
|
||||
);
|
||||
const attack_speed = player.attribute(ATTRIBUTES.attack_speed);
|
||||
sync("attack_speed", attack_speed, () => ({ type: "attack_speed", value: attack_speed }));
|
||||
const attributes = {
|
||||
attack_speed: player.attribute(ATTRIBUTES.attack_speed),
|
||||
block_interaction_range: player.attribute(ATTRIBUTES.block_interaction_range),
|
||||
entity_interaction_range: player.attribute(ATTRIBUTES.entity_interaction_range),
|
||||
};
|
||||
sync("attributes", attributes, () => ({ type: "attributes", ...attributes }));
|
||||
const using = player.using !== undefined;
|
||||
sync("using_item", using, () => ({ type: "using_item", using }));
|
||||
const flying = player.flying;
|
||||
sync("flying", flying, () => ({ type: "flying", flying }));
|
||||
const effects = [...player.effects.values()]
|
||||
@@ -2042,11 +2117,13 @@ export class GameServer {
|
||||
this.#next_chunk_player = first + 1;
|
||||
}
|
||||
|
||||
// from the eyes to the block's middle
|
||||
#in_reach(player: ServerPlayer, x: number, y: number, z: number) {
|
||||
const dx = x + 0.5 - player.x;
|
||||
const dy = y + 0.5 - (player.y + player.eye_height);
|
||||
const dz = z + 0.5 - player.z;
|
||||
return dx * dx + dy * dy + dz * dz <= MAX_REACH * MAX_REACH;
|
||||
const reach = player.attribute(ATTRIBUTES.block_interaction_range) + REACH_LEEWAY;
|
||||
return dx * dx + dy * dy + dz * dz <= reach * reach;
|
||||
}
|
||||
|
||||
// from the eyes to the closest point of its box
|
||||
@@ -2056,7 +2133,8 @@ export class GameServer {
|
||||
const dx = Math.max(entity.x - half - player.x, 0, player.x - entity.x - half);
|
||||
const dy = Math.max(entity.y - eye_y, 0, eye_y - entity.y - entity.height);
|
||||
const dz = Math.max(entity.z - half - player.z, 0, player.z - entity.z - half);
|
||||
return dx * dx + dy * dy + dz * dz <= MAX_REACH * MAX_REACH;
|
||||
const reach = player.attribute(ATTRIBUTES.entity_interaction_range) + REACH_LEEWAY;
|
||||
return dx * dx + dy * dy + dz * dz <= reach * reach;
|
||||
}
|
||||
|
||||
// the blocks within SIMULATION_DISTANCE of a player that have on_new_day and no data, in chunks that are built
|
||||
|
||||
@@ -1340,6 +1340,17 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
|
||||
},
|
||||
remove_effect: (id) => player.remove_effect(known_effect(id).id),
|
||||
is_swimming: () => player.swimming,
|
||||
is_sneaking: () => player.sneaking,
|
||||
start_using(ticks) {
|
||||
if (!Number.isInteger(ticks) || (ticks < 1 && ticks !== -1)) {
|
||||
throw new Error("start_using takes a whole number of ticks, or -1 until they let go");
|
||||
}
|
||||
game.start_using(player, ticks);
|
||||
},
|
||||
stop_using() {
|
||||
player.using = undefined;
|
||||
},
|
||||
is_using: () => player.using !== undefined,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,11 @@ export class ServerPlayer extends LivingEntity {
|
||||
override eye_height = PLAYER_EYE_HEIGHT;
|
||||
// lying flat in the short box, as their client says. their client decides, like where they are
|
||||
swimming = false;
|
||||
// holding the sneak key, as their client says
|
||||
sneaking = false;
|
||||
// the held item they're using over time, like drawing a bow: which slot and item it was, how many ticks they've
|
||||
// used it, and for how long they can (-1 until they let go). see GameServer.start_using
|
||||
using: { slot: number; type_id: string; ticks: number; duration: number } | undefined;
|
||||
// flying, from /fly. their client moves them without gravity, and they don't fall or get hungry from moving
|
||||
flying = false;
|
||||
|
||||
@@ -127,6 +132,8 @@ export class ServerPlayer extends LivingEntity {
|
||||
[ATTRIBUTES.attack_speed],
|
||||
[ATTRIBUTES.physical_shielding],
|
||||
[ATTRIBUTES.arcane_shielding],
|
||||
[ATTRIBUTES.block_interaction_range],
|
||||
[ATTRIBUTES.entity_interaction_range],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -192,7 +192,7 @@ Deno.test("players hear their attack speed for the indicator, and any swing, eve
|
||||
operation: "add_multiplied_base",
|
||||
});
|
||||
ticks(1);
|
||||
assertEquals(take(1).filter((m) => m.type === "attack_speed").map((m) => m.value), [4 * 1.3]);
|
||||
assertEquals(take(1).filter((m) => m.type === "attributes").map((m) => m.attack_speed), [4 * 1.3]);
|
||||
|
||||
// too far to hit, but the swing still counts, like the client's indicator shows
|
||||
const far = spawn(0.5, 100, 20.5);
|
||||
|
||||
@@ -12,7 +12,7 @@ type Blocks = (x: number, y: number, z: number) => boolean;
|
||||
// a player on flat ground at y 0, maybe with a ceiling, and the positions it sends. or in a world of its own: what's
|
||||
// solid and what's water
|
||||
function setup(ceiling = Infinity, world?: { solid: Blocks; water: Blocks }) {
|
||||
const sent: { y: number; swimming?: boolean }[] = [];
|
||||
const sent: { y: number; swimming?: boolean; sneaking?: boolean }[] = [];
|
||||
const client = {
|
||||
level: {
|
||||
collision_shape: world?.solid ?? ((_x: number, y: number) => y < 0 || y >= ceiling),
|
||||
@@ -123,6 +123,36 @@ Deno.test("walking speeds up until friction evens it out, at minecraft's speeds"
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("using an item over time walks at a fifth of the speed, and doesn't sprint", () => {
|
||||
for (const keys of [["KeyW"], ["KeyW", "ControlLeft"]]) {
|
||||
const { player } = setup();
|
||||
run(player, 1, () => false);
|
||||
player.using_item = true;
|
||||
for (const key of keys) InputManager.keys_down.add(key);
|
||||
for (let tick = 0; tick < 40; tick++) player.tick();
|
||||
const z = player.z;
|
||||
player.tick();
|
||||
InputManager.keys_down.clear();
|
||||
assertAlmostEquals((z - player.z) * 20, 4.317 / 5, 0.01);
|
||||
assertFalse(player.sprinting);
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("holding sneak tells the server right away, flying too", () => {
|
||||
const { player, sent } = setup();
|
||||
run(player, 1, () => false);
|
||||
InputManager.keys_down.add("ShiftLeft");
|
||||
player.tick();
|
||||
assertEquals(sent.at(-1)?.sneaking, true);
|
||||
player.flying = true;
|
||||
player.tick();
|
||||
assertFalse(player.sneaking);
|
||||
assert(player.holding_sneak);
|
||||
InputManager.keys_down.clear();
|
||||
player.tick();
|
||||
assertEquals(sent.at(-1)?.sneaking, undefined);
|
||||
});
|
||||
|
||||
Deno.test("jumping while sprinting is faster, and turning while sprinting is slower", () => {
|
||||
// average speed over 200 ticks holding w and ctrl, and maybe space, turning this much each tick
|
||||
const average = (jump: boolean, turn: number) => {
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what players do with their hands: sneaking while placing and using, how far they reach, and using an item over time
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { ATTRIBUTES } from "$/server/game/entity/attributes.ts";
|
||||
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
|
||||
|
||||
const SERVER_SCRIPT = `
|
||||
import type { ServerContext } from "bworld/server";
|
||||
export function setup(ctx: ServerContext) {
|
||||
const log = (key: string, value: unknown = 1) => {
|
||||
const all = ctx.storage.get<Record<string, unknown[]>>("log") ?? {};
|
||||
(all[key] ??= []).push(value);
|
||||
ctx.storage.set("log", all);
|
||||
};
|
||||
ctx.components.register_block("testmod:box", {
|
||||
on_interact(_block, _params, player) {
|
||||
log("interact", player.is_sneaking());
|
||||
return true;
|
||||
},
|
||||
});
|
||||
ctx.components.register_item("testmod:wrench", {
|
||||
on_use(_item, _params, player, target) {
|
||||
const { block, face } = target ?? {};
|
||||
log("wrench", block ? [block.id, block.x, block.y, block.z, face, player.is_sneaking()] : null);
|
||||
},
|
||||
});
|
||||
ctx.components.register_item("testmod:bow", {
|
||||
on_use(_item, params: { ticks: number }, player) {
|
||||
player.start_using(params.ticks);
|
||||
log("start");
|
||||
},
|
||||
on_use_tick(_item, _params, _player, ticks) { log("tick", ticks); },
|
||||
on_release_using(_item, _params, _player, ticks) { log("release", ticks); },
|
||||
on_finish_using() { log("finish"); },
|
||||
});
|
||||
}
|
||||
`;
|
||||
|
||||
// a pillar placed upside down while sneaking, like a block whose placement reads sneaking
|
||||
const SHARED_SCRIPT = `
|
||||
import type { SharedContext } from "bworld/shared";
|
||||
export function setup(ctx: SharedContext) {
|
||||
ctx.components.register_block("testmod:pillar", {
|
||||
state_for_placement(placement) { return { flipped: placement.sneaking ? 1 : 0 }; },
|
||||
});
|
||||
}
|
||||
`;
|
||||
|
||||
function test_mods() {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_actions_" });
|
||||
copy_dir("mods/bworld", `${dir}/bworld`);
|
||||
const mod = `${dir}/testmod`;
|
||||
for (const folder of ["blocks", "items", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true });
|
||||
const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json));
|
||||
write("manifest.json", {
|
||||
format_version: 1,
|
||||
id: "testmod",
|
||||
name: "Test",
|
||||
version: "1.0.0",
|
||||
dependencies: [{ id: "bworld", version: "*" }],
|
||||
scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" },
|
||||
});
|
||||
const block = (id: string, extra: Record<string, unknown>) => ({
|
||||
format_version: 1,
|
||||
block: { id, textures: "bworld:stone", mining: { toughness: 1 }, ...extra },
|
||||
});
|
||||
write("blocks/box.json", block("testmod:box", { interactive: true, components: { "testmod:box": {} } }));
|
||||
write(
|
||||
"blocks/pillar.json",
|
||||
block("testmod:pillar", {
|
||||
states: [{ name: "flipped", bits: 1, default: 0 }],
|
||||
components: { "testmod:pillar": {} },
|
||||
}),
|
||||
);
|
||||
const item = (id: string, components: Record<string, unknown>) => ({
|
||||
format_version: 1,
|
||||
item: { id, texture: "bworld:stone", components },
|
||||
});
|
||||
write("items/wrench.json", item("testmod:wrench", { "testmod:wrench": {} }));
|
||||
write("items/bow.json", item("testmod:bow", { "testmod:bow": { ticks: 5 } }));
|
||||
Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT);
|
||||
Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT);
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function setup() {
|
||||
const dir = test_mods();
|
||||
const { game, send, take, join } = await test_game(dir);
|
||||
join(1, "alice");
|
||||
stone_floor(game);
|
||||
const move = (sneaking: boolean) =>
|
||||
send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0, ...(sneaking && { sneaking }) });
|
||||
move(false);
|
||||
// gives them one of id and selects its slot, or selects an empty slot without id
|
||||
const hold = (id?: string) => {
|
||||
if (id) send(1, { type: "chat", text: `/give ${id}` });
|
||||
const inventory = take(1).filter((m) => m.container === "inventory").at(-1)?.items ??
|
||||
game.players()[0].inventory.to_synced_data();
|
||||
send(1, {
|
||||
type: "select_slot",
|
||||
slot: inventory.findIndex((i: { id: string } | null) => (i?.id ?? null) === (id ?? null)),
|
||||
});
|
||||
};
|
||||
const log = () => (game.mods.storage.testmod?.log ?? {}) as Record<string, unknown[]>;
|
||||
const cleanup = () => Deno.removeSync(dir, { recursive: true });
|
||||
return { game, send, take, move, hold, log, cleanup };
|
||||
}
|
||||
|
||||
Deno.test("sneaking with an item places it against a block that does something when used, like minecraft", async () => {
|
||||
const { game, send, move, hold, log, cleanup } = await setup();
|
||||
game.set_block(1, 99, 1, "testmod:box");
|
||||
hold("testmod:pillar");
|
||||
send(1, { type: "use_block", x: 1, y: 99, z: 1, face: "top" });
|
||||
assertEquals(log()["interact"], [false]);
|
||||
assertEquals(game.world.get_block_id(1, 100, 1), "bworld:air");
|
||||
|
||||
// the box isn't used, and the pillar's placement knows they were sneaking
|
||||
move(true);
|
||||
assert(game.mods.player(game.players()[0]).is_sneaking());
|
||||
send(1, { type: "use_block", x: 1, y: 99, z: 1, face: "top" });
|
||||
assertEquals(log()["interact"], [false]);
|
||||
assertEquals(game.world.get_block_id(1, 100, 1), "testmod:pillar");
|
||||
assertEquals(game.world.get_block_value(1, 100, 1) >>> 16, 1);
|
||||
|
||||
// with nothing in hand, sneaking still uses it
|
||||
hold();
|
||||
send(1, { type: "use_block", x: 1, y: 99, z: 1, face: "north" });
|
||||
assertEquals(log()["interact"], [false, true]);
|
||||
cleanup();
|
||||
});
|
||||
|
||||
Deno.test("an item's on_use says which block it was used on", async () => {
|
||||
const { send, move, hold, log, cleanup } = await setup();
|
||||
hold("testmod:wrench");
|
||||
move(true);
|
||||
send(1, { type: "use_block", x: 1, y: 99, z: 0, face: "top", hit: [0.5, 1, 0.5] });
|
||||
send(1, { type: "use_item" });
|
||||
assertEquals(log()["wrench"], [["bworld:stone", 1, 99, 0, "top", true], null]);
|
||||
cleanup();
|
||||
});
|
||||
|
||||
Deno.test("an item used over time ticks while use is held, and is let go of or finishes", async () => {
|
||||
const { game, send, take, hold, log, cleanup } = await setup();
|
||||
hold("testmod:bow");
|
||||
const using = () => take(1).filter((m) => m.type === "using_item").map((m) => m.using);
|
||||
|
||||
send(1, { type: "use_item" });
|
||||
game.tick();
|
||||
game.tick();
|
||||
assertEquals(using(), [true]);
|
||||
// clicking again while it's used doesn't use it again
|
||||
send(1, { type: "use_item" });
|
||||
send(1, { type: "release_use" });
|
||||
game.tick();
|
||||
assertEquals(log()["start"], [1]);
|
||||
assertEquals(log()["tick"], [1, 2]);
|
||||
assertEquals(log()["release"], [2]);
|
||||
assertEquals(using(), [false]);
|
||||
|
||||
// held for its whole time, it finishes instead, and letting go after that does nothing
|
||||
send(1, { type: "use_item" });
|
||||
for (let i = 0; i < 8; i++) game.tick();
|
||||
send(1, { type: "release_use" });
|
||||
assertEquals(log()["tick"], [1, 2, 1, 2, 3, 4, 5]);
|
||||
assertEquals(log()["finish"], [1]);
|
||||
assertEquals(log()["release"], [2]);
|
||||
|
||||
// switching to another slot stops it without either
|
||||
send(1, { type: "use_item" });
|
||||
game.tick();
|
||||
hold();
|
||||
game.tick();
|
||||
send(1, { type: "release_use" });
|
||||
assertEquals(log()["tick"]?.length, 8);
|
||||
assertEquals(log()["finish"], [1]);
|
||||
assertEquals(log()["release"], [2]);
|
||||
cleanup();
|
||||
});
|
||||
|
||||
Deno.test("how far players reach is an attribute, which their client is sent", async () => {
|
||||
const { game, send, take, cleanup } = await setup();
|
||||
const [alice] = game.players();
|
||||
game.set_block(0, 99, 9, "bworld:stone");
|
||||
send(1, { type: "break_block", x: 0, y: 99, z: 9 });
|
||||
assertEquals(game.world.get_block_id(0, 99, 9), "bworld:stone");
|
||||
|
||||
alice.attributes.get(ATTRIBUTES.block_interaction_range)!.add_modifier({
|
||||
id: "extendo",
|
||||
amount: 3,
|
||||
operation: "add_value",
|
||||
});
|
||||
game.tick();
|
||||
const sent = take(1).filter((m) => m.type === "attributes").at(-1);
|
||||
assertEquals([sent.block_interaction_range, sent.entity_interaction_range], [9, 3]);
|
||||
send(1, { type: "break_block", x: 0, y: 99, z: 9 });
|
||||
assertEquals(game.world.get_block_id(0, 99, 9), "bworld:air");
|
||||
cleanup();
|
||||
});
|
||||
@@ -84,13 +84,13 @@ function client_of(t: Game) {
|
||||
return {
|
||||
// what game_mode does when this client places held against face of x y z, at hit
|
||||
place(id: string, x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
|
||||
const value = rules.placement_value(info(id)!, yaw, { x, y, z, face, hit });
|
||||
const value = rules.placement_value(info(id)!, yaw, { x, y, z, face, hit, sneaking: false });
|
||||
copy.set(`${x} ${y} ${z}`, [id, value >>> 16]);
|
||||
rules.notify_neighbors(world.get_block, x, y, z);
|
||||
},
|
||||
// what game_mode does when this client right clicks face of x y z, at hit. whether the rules did something
|
||||
interact(x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
|
||||
return rules.interact(info(at(x, y, z)![0])!, x, y, z, { face, hit }, yaw);
|
||||
return rules.interact(info(at(x, y, z)![0])!, x, y, z, { face, hit, sneaking: false }, yaw);
|
||||
},
|
||||
break(x: number, y: number, z: number) {
|
||||
copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]);
|
||||
|
||||
Reference in New Issue
Block a user