Compare commits

..
3 Commits
Author SHA1 Message Date
paula 9ca717d2d0 Swimming 2026-10-02 11:07:09 -03:00
paula d5015edfa1 Basic swimming 2026-10-01 21:12:30 -03:00
paula 6e5703a482 Change giant chestplate to regen 3 2026-10-01 20:55:58 -03:00
28 changed files with 659 additions and 65 deletions
+11 -1
View File
@@ -1,4 +1,4 @@
import { move_body } from "$/common/physics.ts";
import { eyes_in_water, in_water, move_body } from "$/common/physics.ts";
import type { ClientLevel } from "../level/client_level.ts";
// anything that exists in the level and moves, like minecraft's Entity. position is the middle of its feet.
@@ -59,6 +59,16 @@ export abstract class Entity {
return this.colliding_y === 1;
}
// in water, like the server's Entity.in_water
get in_water() {
return in_water(this, (x, y, z) => this.level.is_liquid(x, y, z));
}
// its eyes are in water
get eyes_in_water() {
return eyes_in_water(this, this.eye_height, (x, y, z) => this.level.is_liquid(x, y, z));
}
// after moving each tick. full speed is 5 blocks per second, a bit faster than walking
update_walk_animation() {
const moved = Math.hypot(this.x - this.prev_x, this.z - this.prev_z);
+105 -8
View File
@@ -1,5 +1,5 @@
import { PLAYER_EYE_HEIGHT, TICK_DELTA } from "$/common/constants.ts";
import { back_off_from_edge } from "$/common/physics.ts";
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_SWIM_EYE_HEIGHT, TICK_DELTA } from "$/common/constants.ts";
import { back_off_from_edge, box_is_free } from "$/common/physics.ts";
import type { Client } from "../client.ts";
import { InputManager } from "../input_manager.ts";
import { ClientInventories } from "../inventory.ts";
@@ -40,6 +40,29 @@ const EYE_EASE = 0.5;
// sneaking keeps it from walking off anything taller than this
const SNEAK_MAX_DROP = 0.6;
// in water, like minecraft's LivingEntity.travel and the server's mobs: the keys add 0.02 blocks a tick, gravity is a
// sixteenth of the usual, and it slows to 0.8 of its speed each tick on every axis. walking settles at 2 blocks a
// second, and sinking at 0.45
const WATER_ACCELERATION = 0.02 / TICK_DELTA;
const WATER_GRAVITY = -32 / 16;
const WATER_DRAG = 0.8;
// holding jump in water pushes it up this much each tick, like minecraft's jumpInLiquid, rising 3.55 blocks a second
const SWIM_UP = 0.04 / TICK_DELTA;
// and sneaking pulls it down as much, like minecraft's goDownInWater, sinking 4.45 blocks a second. both cancel out
const SWIM_DOWN = 0.04 / TICK_DELTA;
// swimming into a wall with nothing solid or wet 0.6 above, like the edge of a pool, it hops up like minecraft. a bit
// harder than minecraft's 0.3, whose water is a little lower than a full block, so a ledge a block above the water can
// be climbed onto
const WATER_HOP_HEIGHT = 0.6;
const WATER_HOP = 0.36 / TICK_DELTA;
// swimming, sprinting with the eyes under water: no gravity and less drag sideways, so it goes 4 blocks a second
const SWIM_DRAG = 0.9;
// and it turns up or down toward where it's looking, this much of the way each tick, like minecraft's Player.travel
const SWIM_STEER = 0.06;
// on land, the entity's own
const LAND_GRAVITY = -32;
const LAND_DRAG = 0.98;
// what the keys ask for this tick. x is right, z is back, as -1 to 1
interface MoveInput {
x: number;
@@ -79,6 +102,8 @@ export class LocalPlayer extends Player {
#fov_scale = 1;
#prev_fov_scale = 1;
#prev_eye_height = PLAYER_EYE_HEIGHT;
// whether it was in water at the start of this tick, which decides how it moves for all of it
#in_water = false;
constructor(client: Client, id: string, name: string) {
super(client.level, id, name);
@@ -93,9 +118,22 @@ export class LocalPlayer extends Player {
}
tick() {
this.#apply_input(this.client.screen ? NO_INPUT : this.#read_input());
this.#in_water = this.in_water;
const was_swimming = this.swimming;
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
this.#update_swimming();
// out of the water but still in the short box, under something low, it falls like on land
this.gravity = !this.#in_water ? LAND_GRAVITY : this.swimming ? 0 : WATER_GRAVITY;
this.drag = this.#in_water ? WATER_DRAG : LAND_DRAG;
if (this.swimming && this.#in_water) this.#steer(input);
this.#prev_eye_height = this.eye_height;
const eye_height = this.sneaking ? SNEAK_EYE_HEIGHT : PLAYER_EYE_HEIGHT;
const eye_height = this.swimming
? PLAYER_SWIM_EYE_HEIGHT
: this.sneaking
? SNEAK_EYE_HEIGHT
: PLAYER_EYE_HEIGHT;
this.eye_height += (eye_height - this.eye_height) * EYE_EASE;
this.#prev_fov_scale = this.#fov_scale;
this.#fov_scale += ((this.sprinting ? SPRINT_FOV : 1) - this.#fov_scale) * FOV_EASE;
@@ -114,10 +152,48 @@ export class LocalPlayer extends Player {
this.vx = dx / TICK_DELTA;
this.vz = dz / TICK_DELTA;
}
const from_y = this.y;
this.move();
if (this.#in_water) this.#hop_out_of_water(from_y);
if (Math.abs(this.vx) < MIN_SPEED) this.vx = 0;
if (Math.abs(this.vz) < MIN_SPEED) this.vz = 0;
this.#send_position(this.on_ground && !was_on_ground);
this.update_swim_animation();
this.#send_position((this.on_ground && !was_on_ground) || this.swimming !== was_swimming);
}
// like voxelibre: sprinting with the eyes under water starts it, and it keeps going while it sprints in water, along
// the surface too. it only stands back up where there's room, until then it stays in the short box
#update_swimming() {
if (!this.swimming) {
if (this.sprinting && this.eyes_in_water) this.set_swimming(true);
return;
}
if (this.sprinting && this.#in_water) return;
const standing = {
x: this.x,
y: this.y,
z: this.z,
width: this.width,
height: PLAYER_HEIGHT,
vx: 0,
vy: 0,
vz: 0,
};
if (box_is_free(standing, 0, 0, 0, (x, y, z) => this.level.has_collision(x, y, z))) this.set_swimming(false);
}
// turns up or down toward where it's looking. not up once its head is out, so it swims along the surface instead
// of leaping out of the water, unless it's holding jump
#steer(input: MoveInput) {
const look_y = Math.sin(this.pitch);
const head_in_water = this.level.is_liquid(
Math.floor(this.x),
Math.floor(this.y + this.height),
Math.floor(this.z),
);
if (look_y <= 0 || input.jump || head_in_water) {
this.vy += (look_y / TICK_DELTA - this.vy) * SWIM_STEER;
}
}
// turns with the mouse every frame, not every tick, like minecraft's MouseHandler.turnPlayer
@@ -130,9 +206,20 @@ export class LocalPlayer extends Player {
}
override horizontal_friction() {
if (this.#in_water) return this.swimming ? SWIM_DRAG : WATER_DRAG;
return this.on_ground ? GROUND_FRICTION : AIR_FRICTION;
}
// like minecraft's LivingEntity.travel in water: after running into a wall, if the box one move on and 0.6 higher
// than where it started touches nothing solid or wet, it hops up, out onto the ledge
#hop_out_of_water(from_y: number) {
if (!this.colliding_x && !this.colliding_z) return;
const blocked = (x: number, y: number, z: number) =>
this.level.has_collision(x, y, z) || this.level.is_liquid(x, y, z);
const dy = from_y - this.y + this.vy * TICK_DELTA + WATER_HOP_HEIGHT;
if (box_is_free(this, this.vx * TICK_DELTA, dy, this.vz * TICK_DELTA, blocked)) this.vy = WATER_HOP;
}
// how much wider the view is than the fov option, between the last tick and this one
override render_fov_scale(partial_tick: number) {
return this.#prev_fov_scale + (this.#fov_scale - this.#prev_fov_scale) * partial_tick;
@@ -168,15 +255,23 @@ export class LocalPlayer extends Player {
const sin = Math.sin(this.yaw);
const cos = Math.cos(this.yaw);
this.#update_sprinting(input, sin, cos);
const acceleration = (this.on_ground ? GROUND_ACCELERATION : AIR_ACCELERATION) *
(input.sneak ? SNEAK_SPEED : this.sprinting ? SPRINT_SPEED : 1);
// sprinting is no faster in water, swimming is
const acceleration = this.#in_water
? WATER_ACCELERATION * (input.sneak ? SNEAK_SPEED : 1)
: (this.on_ground ? GROUND_ACCELERATION : AIR_ACCELERATION) *
(input.sneak ? SNEAK_SPEED : this.sprinting ? SPRINT_SPEED : 1);
this.vx += (sin * input_z + cos * input_x) * acceleration;
this.vz += (cos * input_z - sin * input_x) * acceleration;
if (this.#in_water && input.sneak) this.vy -= SWIM_DOWN;
this.#jump_delay = Math.max(0, this.#jump_delay - 1);
if (!input.jump) {
this.#jump_delay = 0;
} else if (this.#in_water) {
// like minecraft, jumping in water swims up instead, even standing on the bottom
this.vy += SWIM_UP;
} else if (this.on_ground && this.#jump_delay === 0) {
this.vy += this.jump_force;
this.#jump_delay = JUMP_DELAY_TICKS;
@@ -196,7 +291,8 @@ export class LocalPlayer extends Player {
const into_wall = sin * this.colliding_x + cos * this.colliding_z;
if (!can_sprint || into_wall > SPRINT_WALL_ANGLE) {
this.sprinting = false;
} else if (input.sprint) {
} else if (input.sprint && (!this.#in_water || this.eyes_in_water)) {
// in water only with the eyes under, to swim, not to sprint along the bottom
this.sprinting = true;
}
}
@@ -221,6 +317,7 @@ export class LocalPlayer extends Player {
yaw: this.yaw,
pitch: this.pitch,
teleport: this.teleport_id,
...(this.swimming && { swimming: true }),
});
}
}
+45 -1
View File
@@ -1,10 +1,17 @@
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_SWIM_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
import { ItemStack } from "$/common/inventory.ts";
import type { ClientLevel } from "../level/client_level.ts";
import type { Texture } from "../renderer/mod.ts";
import { decode_skin } from "../skins.ts";
import { Entity } from "./entity.ts";
// how much of the way it tips over or stands up each tick, so it takes 10 ticks
const SWIM_EASE = 0.1;
// how much of the way the body turns toward which way it's going each tick
const SWIM_PITCH_EASE = 0.3;
// blocks a tick. slower than this the body lies the way they look instead, it's how they moved that's too jittery
const SWIM_MOVING = 0.05;
export abstract class Player extends Entity {
name: string;
// like minecraft's players: slabs yes, full blocks need a jump
@@ -18,6 +25,14 @@ export abstract class Player extends Entity {
slim = false;
// what they wear that shows, items with a worn model, see the server's player_worn
worn: ItemStack[] = [];
// lying flat in the short box, see set_swimming
swimming = false;
// how far over they've tipped, 0 standing to 1 lying flat, see update_swim_animation
swim_amount = 0;
prev_swim_amount = 0;
// which way the body lies while swimming, radians up from flat: the way they're going, or looking when still
swim_pitch = 0;
prev_swim_pitch = 0;
#skin_version = 0;
constructor(level: ClientLevel, id: string, name: string) {
@@ -25,6 +40,35 @@ export abstract class Player extends Entity {
this.name = name;
}
// swimming lies them flat in the short box, and not swimming stands them back up. the local player checks there's
// room first, remote players' clients already did
set_swimming(swimming: boolean) {
this.swimming = swimming;
this.height = swimming ? PLAYER_SWIM_HEIGHT : PLAYER_HEIGHT;
}
// after moving each tick, for tipping over and standing up smoothly, local and remote players alike. the pitch comes
// from how they moved, so remote players get it without anything more from the server
update_swim_animation() {
this.prev_swim_amount = this.swim_amount;
this.prev_swim_pitch = this.swim_pitch;
const amount = this.swimming ? 1 : 0;
this.swim_amount += Math.max(-SWIM_EASE, Math.min(SWIM_EASE, amount - this.swim_amount));
const [dx, dy, dz] = [this.x - this.prev_x, this.y - this.prev_y, this.z - this.prev_z];
const moving = Math.atan2(dy, Math.hypot(dx, dz));
const weight = Math.min(Math.hypot(dx, dy, dz) / SWIM_MOVING, 1);
const pitch = this.pitch + (moving - this.pitch) * weight;
this.swim_pitch += (pitch - this.swim_pitch) * SWIM_PITCH_EASE;
}
// a frame partial_tick of the way to the next tick
render_swim(partial_tick: number) {
return {
amount: this.prev_swim_amount + (this.swim_amount - this.prev_swim_amount) * partial_tick,
pitch: this.prev_swim_pitch + (this.swim_pitch - this.prev_swim_pitch) * partial_tick,
};
}
// a base64 png from the server, or undefined for the default. the old skin stays until the new one is decoded
async set_skin(skin: string | undefined, slim = false) {
const version = ++this.#skin_version;
+2
View File
@@ -29,6 +29,7 @@ export class RemotePlayer extends Player {
this.set_skin(info.skin, info.slim);
}
this.worn = (info.worn ?? []).map(ItemStack.from_data);
this.set_swimming(info.swimming === true);
}
lerp_to(x: number, y: number, z: number, yaw: number, pitch: number) {
@@ -53,5 +54,6 @@ export class RemotePlayer extends Player {
this.y += (this.target_y - this.y) * t;
this.z += (this.target_z - this.z) * t;
this.update_walk_animation();
this.update_swim_animation();
}
}
+7
View File
@@ -7,6 +7,7 @@ import {
block_light_opacity,
BlockRegistry,
EverythingRegistry,
is_liquid_block,
RENDER_LAYERS,
RenderLayer,
} from "$/common/everything_registry.ts";
@@ -302,6 +303,12 @@ export class ClientLevel {
return block === VOID || (block !== AIR && (this.#blocks[block]?.has_collision ?? true));
}
// water, see is_liquid_block. unloaded chunks aren't
is_liquid(x: number, y: number, z: number) {
const block = this.get_block(x, y, z);
return block !== VOID && block !== AIR && is_liquid_block(this.#blocks[block]);
}
// only changes what this client shows, drops and everything else happen on the server
break_block(x: number, y: number, z: number) {
const block_chunk_x = Math.floor(x / CHUNK_SIZE);
+1
View File
@@ -159,6 +159,7 @@ function client_context(listing: ModListing): ClientContext {
const { x, y, z } = need_client().player;
return { x, y, z };
},
is_swimming: () => need_client().player.swimming,
},
world: {
get_block(x, y, z) {
+1
View File
@@ -90,6 +90,7 @@ export class ClientPacketListener {
const player = level.entities.get(message.id);
if (player instanceof RemotePlayer) {
player.lerp_to(message.x, message.y, message.z, message.yaw, message.pitch);
player.set_swimming(message.swimming === true);
}
break;
}
+59 -7
View File
@@ -1,9 +1,9 @@
// minecraft's player model and how it's posed each frame, for drawing players and what they wear. no drawing here, so
// tests can use it
import { PLAYER_HEIGHT } from "$/common/constants.ts";
import { PLAYER_HEIGHT, PLAYER_SWIM_HEIGHT } from "$/common/constants.ts";
import { PLAYER_PARTS, type WornProperties } from "$/common/everything_registry.ts";
import type { EntityBoneJson, EntityModelJson } from "$/common/mod_data.ts";
import { apply, IDENTITY, type Matrix, rotation_around, type Vec3 } from "./model_math.ts";
import { apply, IDENTITY, type Matrix, multiply, rotation_around, type Vec3 } from "./model_math.ts";
export type PartName = typeof PLAYER_PARTS[number];
@@ -117,19 +117,38 @@ export interface PoseInput {
pitch: number;
walk: { position: number; speed: number };
slim: boolean;
// how far over they've tipped and which way the body lies, see Player.update_swim_animation. none is standing
swim?: { amount: number; pitch: number };
// ticks, for the arms drifting while they swim in place
time?: number;
}
// where a player is drawn this frame: each part's matrix, which turns its points (in skin pixels, around the model's
// feet, like a bone's) the way the part is turned, and where the model is
// feet, like a bone's) the way the part is turned, then the root's, which turns the whole model (lying flat to swim),
// and where the model is
export interface PlayerPose {
x: number;
y: number;
z: number;
yaw: number;
slim: boolean;
root: Matrix;
parts: Record<PartName, Matrix>;
}
// the model lies flat around the middle of its length, moved down to the middle of the swimming box
const SWIM_PIVOT: Vec3 = [0, 16, 0];
const SWIM_DROP = PLAYER_SWIM_HEIGHT / 2 / PIXEL - SWIM_PIVOT[1];
// the crawl: arms go around this much per walk step (once a second swimming at full speed), legs flutter this fast and this far
const STROKE_RATE = 0.3;
const FLUTTER_RATE = 1.2;
const FLUTTER = 0.3;
// arms out a little so they go around beside the head, not through it
const STROKE_SPREAD = 0.15;
// swimming in place, the arms and legs drift slowly, about every 2 seconds
const DRIFT_RATE = 0.15;
const DRIFT = 0.25;
export function pose_at(input: PoseInput): PlayerPose {
// limbs swing opposite to each other, like minecraft's HumanoidModel.setupAnim
const swing = Math.cos(input.walk.position * 0.6662) * input.walk.speed;
@@ -141,18 +160,51 @@ export function pose_at(input: PoseInput): PlayerPose {
right_leg: swing * 1.4,
left_leg: -swing * 1.4,
};
const spread: Record<PartName, number> = { head: 0, body: 0, right_arm: 0, left_arm: 0, right_leg: 0, left_leg: 0 };
let root = IDENTITY;
const swim = input.swim?.amount ?? 0;
if (swim > 0) {
// forward onto its front, then further for going down or less for going up
const tilt = swim * (Math.PI / 2 - input.swim!.pitch);
root = multiply([1, 0, 0, 0, 0, 1, 0, swim * SWIM_DROP, 0, 0, 1, 0], rotation_around(SWIM_PIVOT, -tilt, 0, 0));
// the head turns back up as much, so it faces where they look
angles.head = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, input.pitch + tilt));
const speed = input.walk.speed;
const drift = Math.sin((input.time ?? 0) * DRIFT_RATE) * DRIFT;
// arms go around half a turn apart, forward over the head and back under, like walking's -swing
const stroke = -input.walk.position * STROKE_RATE;
const arm = (offset: number) => drift * (1 - speed) + wrap(stroke + offset - drift) * speed;
const flutter = Math.cos(input.walk.position * FLUTTER_RATE) * FLUTTER * speed + drift * (1 - speed);
const swimming: Partial<Record<PartName, number>> = {
right_arm: arm(0),
left_arm: arm(Math.PI),
right_leg: flutter,
left_leg: -flutter,
};
for (const [name, angle] of Object.entries(swimming) as [PartName, number][]) {
angles[name] += (angle - angles[name]) * swim;
}
spread.right_arm = STROKE_SPREAD * swim;
spread.left_arm = -STROKE_SPREAD * swim;
}
const parts = {} as Record<PartName, Matrix>;
for (const part of input.slim ? SLIM_PARTS : PARTS) {
parts[part.name] = rotation_around(part.pivot, angles[part.name], 0, 0);
parts[part.name] = rotation_around(part.pivot, angles[part.name], 0, spread[part.name]);
}
return { x: input.x, y: input.y, z: input.z, yaw: input.yaw, slim: input.slim, parts };
return { x: input.x, y: input.y, z: input.z, yaw: input.yaw, slim: input.slim, root, parts };
}
// from the model's skin pixels to the world: scaled to the player's height, then turned to their yaw
// an angle the same way around, between -pi and pi
function wrap(angle: number): number {
return angle - 2 * Math.PI * Math.round(angle / (2 * Math.PI));
}
// from the model's skin pixels to the world: turned by the root, scaled to the player's height, then turned to their
// yaw
export function pose_to_world(pose: PlayerPose): (x: number, y: number, z: number) => Vec3 {
const [sin, cos] = [Math.sin(pose.yaw), Math.cos(pose.yaw)];
return (px, py, pz) => {
const [mx, my, mz] = [px * PIXEL, py * PIXEL, pz * PIXEL];
const [mx, my, mz] = apply(pose.root, px, py, pz).map((n) => n * PIXEL);
return [pose.x + mx * cos + mz * sin, pose.y + my, pose.z - mx * sin + mz * cos];
};
}
+3 -1
View File
@@ -65,7 +65,9 @@ const FACES: { rect: (w: number, h: number, d: number) => number[]; corners: num
export function player_pose(player: Player, partial_tick: number): PlayerPose {
const { x, y, z } = player.render_position(partial_tick);
const { yaw, pitch, slim } = player;
return pose_at({ x, y, z, yaw, pitch, slim, walk: player.walk_animation(partial_tick) });
const walk = player.walk_animation(partial_tick);
const swim = player.render_swim(partial_tick);
return pose_at({ x, y, z, yaw, pitch, slim, walk, swim, time: player.level.time + partial_tick });
}
// a player with a minecraft skin, like minecraft's PlayerRenderer. the skin has to be the current texture. tint
+3
View File
@@ -36,6 +36,9 @@ export const CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
export const PLAYER_WIDTH = 0.6;
export const PLAYER_HEIGHT = 1.79;
export const PLAYER_EYE_HEIGHT = 1.69;
// while swimming they lie flat in a shorter box, like voxelibre's, so they fit through 1 block gaps
export const PLAYER_SWIM_HEIGHT = 0.8;
export const PLAYER_SWIM_EYE_HEIGHT = 0.6;
// where a block placed against each face of another block goes
export const FACE_OFFSETS: Record<Faces, { x: number; y: number; z: number }> = {
+6
View File
@@ -150,6 +150,12 @@ export interface BlockRegistry {
compiled_states?: CompiledStateDefinition[];
}
// water, and any other block entities pass through and players can place into. what entities swim in, and where
// falling doesn't hurt
export function is_liquid_block(block: BlockRegistry | undefined): boolean {
return block !== undefined && !block.has_collision && block.replaceable === true;
}
// what a tool is made of, like minecraft's ToolMaterial
export interface ToolProperties {
// like "pickaxe", matched against blocks' tool_to_break
+2 -1
View File
@@ -9,7 +9,8 @@ export interface ClientContext {
hud: HudRegistry;
input: { bind(id: Id, default_key: KeyCode, on_press: () => void): void };
net: ClientNet;
player: { readonly name: string; readonly position: Readonly<Position> };
// is_swimming: lying flat in water in the 0.8 tall box, like minecraft's isSwimming
player: { readonly name: string; readonly position: Readonly<Position>; is_swimming(): boolean };
// read only, what this client sees
world: {
get_block(x: number, y: number, z: number): Id | undefined;
+2
View File
@@ -248,6 +248,8 @@ export interface Player {
effect(id: Id): { readonly amplifier: number; readonly duration: number } | undefined;
// whether they had it
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;
}
export interface EffectOptions {
+30
View File
@@ -172,6 +172,20 @@ export function back_off_from_edge(
return [dx, dz];
}
// whether the body's box, moved by dx, dy and dz, would touch nothing blocked, like minecraft's Entity.isFree
export function box_is_free(
body: Body,
dx: number,
dy: number,
dz: number,
is_blocked: (x: number, y: number, z: number) => boolean,
): boolean {
const half = body.width / 2;
const min = [body.x - half + dx, body.y + dy, body.z - half + dz];
const max = [body.x + half + dx, body.y + body.height + dy, body.z + half + dz];
return !overlaps_solid(min, max, is_blocked);
}
function overlaps_solid(min: number[], max: number[], is_solid: (x: number, y: number, z: number) => boolean) {
for (let x = Math.floor(min[0] + EPSILON); x <= Math.floor(max[0] - EPSILON); x++) {
for (let y = Math.floor(min[1] + EPSILON); y <= Math.floor(max[1] - EPSILON); y++) {
@@ -182,3 +196,19 @@ function overlaps_solid(min: number[], max: number[], is_solid: (x: number, y: n
}
return false;
}
// in water like minecraft's wasTouchingWater, close enough: its feet or the middle of its box are in liquid
export function in_water(body: Body, is_liquid: (x: number, y: number, z: number) => boolean): boolean {
const x = Math.floor(body.x);
const z = Math.floor(body.z);
return is_liquid(x, Math.floor(body.y), z) || is_liquid(x, Math.floor(body.y + body.height / 2), z);
}
// its eyes are in liquid, so it can't breathe
export function eyes_in_water(
body: Body,
eye_height: number,
is_liquid: (x: number, y: number, z: number) => boolean,
): boolean {
return is_liquid(Math.floor(body.x), Math.floor(body.y + eye_height), Math.floor(body.z));
}
+25 -4
View File
@@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air";
// bump when a client and server of different versions can't play together.
// the server rejects a different version before the client downloads anything
export const PROTOCOL_VERSION = 17;
export const PROTOCOL_VERSION = 18;
export interface PlayerInfo {
id: string;
@@ -23,6 +23,8 @@ export interface PlayerInfo {
slim?: boolean;
// what they're wearing that shows, see player_worn
worn?: ItemData[];
// lying flat in the short box, see PLAYER_SWIM_HEIGHT
swimming?: boolean;
}
// an entity that isn't a player, as the server first sends it. players have their own messages. items on the
@@ -87,8 +89,18 @@ export type ClientMessage =
| { type: "view_distance"; distance: number }
// 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
| { type: "move"; x: number; y: number; z: number; yaw: number; pitch: number; teleport?: 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
| {
type: "move";
x: number;
y: number;
z: number;
yaw: number;
pitch: number;
teleport?: number;
swimming?: boolean;
}
| { type: "break_block"; x: number; y: number; z: number }
// the player started hitting a block, for on_click
| { type: "hit_block"; x: number; y: number; z: number }
@@ -155,7 +167,16 @@ export type ServerMessage =
| { type: "chunk_batch_finished"; size: number }
| { type: "player_join"; player: PlayerInfo }
| { type: "player_leave"; id: string }
| { type: "player_move"; id: string; x: number; y: number; z: number; yaw: number; pitch: number }
| {
type: "player_move";
id: string;
x: number;
y: number;
z: number;
yaw: number;
pitch: number;
swimming?: boolean;
}
// a player changed their skin, including the one receiving it. without skin it's back to the default
| { type: "player_skin"; id: string; skin?: string; slim?: boolean }
// what a player wears that shows changed, to everyone including them: the items whose json has worn, see
+16
View File
@@ -46,6 +46,8 @@ interface Player {
add_effect(id: string, duration: number, options?: EffectOptions): void;
effect(id: string): { amplifier: number; duration: number } | undefined;
remove_effect(id: string): boolean;
is_swimming(): boolean; // see Swimming
}
```
@@ -124,6 +126,20 @@ has [`worn`](../items/index.md#worn-models) show.
Everyone is told what each player wears, the player too, and players joining later get it with the others. It isn't
saved: set it again when the player joins, the way the curios slots do.
## Swimming
Players swim by sprinting with their eyes under water. They keep swimming while they sprint in water, along the surface
too, and stop when they let go of sprint or leave the water. While swimming they lie flat in a box 0.8 blocks tall, with
their eyes at 0.6, so they fit through 1-block gaps. Under a low ceiling they stay in that box until there's room to
stand up.
`player.is_swimming()` says whether a player is swimming, like NeoForge's `isSwimming()`. It works on the server and in
client scripts, where `ctx.player.is_swimming()` is about the player on this client:
```ts
if (player.is_swimming()) player.add_effect("bworld:speed", 20);
```
## Death
When a player dies, everything they carried falls out where they died, and their tools lose durability (see
+1
View File
@@ -136,6 +136,7 @@ Client scripts can read what the client knows, to show it:
```ts
ctx.player.name;
ctx.player.position; // { x, y, z }
ctx.player.is_swimming(); // see ../entities/players.md#swimming
ctx.world.get_block(x, y, z); // a block id, what this client sees
ctx.world.time; // see Time
ctx.items.ids(); // every item, in load order
+5 -5
View File
@@ -13,7 +13,7 @@ necklaces and belts, for any mod's items. They're in 2 columns left of the playe
Shift clicking a curio in the inventory puts it in the first slot it fits.
A slot type only shows up once some item is in its tag. The base game's one curio is the giant chestplate, a body curio
that gives 20 more max health while worn, and regeneration II after 10 seconds without being hurt, so the body slot is
that gives 20 more max health while worn, and regeneration III after 10 seconds without being hurt, so the body slot is
always there.
### Making an Item a Curio
@@ -56,13 +56,13 @@ The Power Glove from Artifacts:
An item with the `bworld:curio_unhurt_effect` component gives the wearer a
[status effect](../../docs/modding/entities/players.md#status-effects) once they've gone `after` ticks without being
hurt, and keeps it on them until they're hurt again. The giant chestplate's regeneration II after 10 seconds:
hurt, and keeps it on them until they're hurt again. The giant chestplate's regeneration III after 10 seconds:
```json
"components": {
"bworld:curio_unhurt_effect": { "effect": "bworld:regeneration", "amplifier": 1, "after": 200 }
"bworld:curio_unhurt_effect": { "effect": "bworld:regeneration", "amplifier": 2, "after": 200 }
}
```
It's given 2.5 seconds at a time, so it lasts up to that long after they're hurt. A stronger one they already have, like
from a potion, is left alone.
It's given two of regeneration's heals at a time (1.2 seconds for regeneration III), so it lasts up to that long after
they're hurt. A stronger one they already have, like from a potion, is left alone.
+3 -3
View File
@@ -22,8 +22,8 @@ interface UnhurtEffect {
}
// how long each unhurt effect is given for, topped up whenever it runs out, so it outlasts being hurt by at most this.
// a multiple of regeneration I and II's ticks between heals, so topping it up keeps their pace
const UNHURT_EFFECT_TICKS = 50;
// two of regeneration's heals at that level (every 50 ticks, halving each level), so topping it up keeps its pace
const unhurt_effect_ticks = (amplifier: number) => Math.max(1, 50 >> amplifier) * 2;
export function register_curios(ctx: ServerContext) {
const active = active_slots(ctx.tags);
@@ -111,7 +111,7 @@ export function register_curios(ctx: ServerContext) {
// only once what they have runs out, or when it's weaker. a stronger one, like from a potion, is left alone
const current = player.effect(effect);
if (current && current.amplifier >= amplifier) continue;
player.add_effect(effect, UNHURT_EFFECT_TICKS, { amplifier });
player.add_effect(effect, unhurt_effect_ticks(amplifier), { amplifier });
}
}
});
+3 -6
View File
@@ -7,7 +7,7 @@
import { TICKS_PER_SECOND } from "$/common/constants.ts";
import type { BlockRegistry } from "$/common/everything_registry.ts";
import type { ItemStack } from "$/common/inventory.ts";
import { type Collisions, move_body } from "$/common/physics.ts";
import { type Collisions, eyes_in_water, in_water, move_body } from "$/common/physics.ts";
import type { EntityData, EntityEvent, EntityInfo } from "$/common/protocol.ts";
import type { ServerPlayer } from "../player.ts";
@@ -239,15 +239,12 @@ export abstract class Entity {
}
update_in_water() {
const x = Math.floor(this.x);
const z = Math.floor(this.z);
this.in_water = this.level.is_liquid(x, Math.floor(this.y), z) ||
this.level.is_liquid(x, Math.floor(this.y + this.height / 2), z);
this.in_water = in_water(this, (x, y, z) => this.level.is_liquid(x, y, z));
}
// its eyes are in water, so it can't breathe
get eyes_in_water() {
return this.level.is_liquid(Math.floor(this.x), Math.floor(this.y + this.eye_height), Math.floor(this.z));
return eyes_in_water(this, this.eye_height, (x, y, z) => this.level.is_liquid(x, y, z));
}
// falls and moves by its velocity for one tick (see move_body), and counts how far it fell. returns what it hit
+2 -2
View File
@@ -3,6 +3,7 @@
// when those move or change, and forgets them when they leave it
import { CHUNK_SIZE } from "$/common/constants.ts";
import { is_within_view } from "$/common/chunk_streaming.ts";
import { is_liquid_block } from "$/common/everything_registry.ts";
import type { ItemStack } from "$/common/inventory.ts";
import type { EntityEvent, EntityInfo, ServerMessage } from "$/common/protocol.ts";
import type { ServerPlayer } from "../player.ts";
@@ -89,8 +90,7 @@ export class EntityManager implements EntityLevel {
}
is_liquid(x: number, y: number, z: number) {
const info = this.#host.world.get_block_info(x, y, z);
return info !== undefined && !info.has_collision && info.replaceable === true;
return is_liquid_block(this.#host.world.get_block_info(x, y, z));
}
get_block_info(x: number, y: number, z: number) {
+16 -12
View File
@@ -4,13 +4,11 @@ import {
FACE_OFFSETS,
Faces,
faces,
PLAYER_EYE_HEIGHT,
PLAYER_HEIGHT,
PLAYER_WIDTH,
TICK_DELTA,
TICKS_PER_SECOND,
} from "$/common/constants.ts";
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import { BlockRegistry, EverythingRegistry, is_liquid_block, ItemRegistry } from "$/common/everything_registry.ts";
import { Container, ItemData, ItemStack } from "$/common/inventory.ts";
import {
AIR_ID,
@@ -437,7 +435,7 @@ export class GameServer {
throw_item(player: ServerPlayer, stack: ItemStack) {
const entity = this.spawn_item(
player.x,
player.y + PLAYER_EYE_HEIGHT - 0.3,
player.y + player.eye_height - 0.3,
player.z,
stack,
PLAYER_DROP_PICKUP_DELAY,
@@ -480,7 +478,7 @@ export class GameServer {
player.teleport_id += 1;
this.#send(player, { type: "teleport", id: player.teleport_id, x, y, z, ...(motion && { motion }) });
this.#update_view(player);
this.#broadcast({ type: "player_move", id: player.id, x, y, z, yaw: player.yaw, pitch: player.pitch }, player);
this.#broadcast(player_move(player), player);
}
set_time(time: number) {
@@ -758,7 +756,8 @@ export class GameServer {
}
this.#on_move(player, x, y, z);
Object.assign(player, { x, y, z, yaw, pitch });
this.#broadcast({ type: "player_move", id: player.id, x, y, z, yaw, pitch }, player);
player.set_swimming(message.swimming === true);
this.#broadcast(player_move(player), player);
this.#update_view(player);
break;
}
@@ -1009,7 +1008,7 @@ export class GameServer {
#occupied(x: number, y: number, z: number) {
return this.players().some((player) =>
box_overlaps_block(
{ x: player.x, y: player.y, z: player.z, width: PLAYER_WIDTH, height: PLAYER_HEIGHT },
{ x: player.x, y: player.y, z: player.z, width: PLAYER_WIDTH, height: player.height },
x,
y,
z,
@@ -1446,8 +1445,7 @@ export class GameServer {
// in a block entities pass through and players can place into, like water
#in_liquid(x: number, y: number, z: number) {
const info = this.world.get_block_info(Math.floor(x), Math.floor(y), Math.floor(z));
return info !== undefined && !info.has_collision && info.replaceable === true;
return is_liquid_block(this.world.get_block_info(Math.floor(x), Math.floor(y), Math.floor(z)));
}
// right click with food: it's eaten if they're hungry, or it's always edible
@@ -1494,7 +1492,7 @@ export class GameServer {
const reach_xz = PLAYER_WIDTH / 2 + PICKUP_REACH_XZ + ITEM_SIZE / 2;
return Math.abs(player.x - entity.x) <= reach_xz && Math.abs(player.z - entity.z) <= reach_xz &&
entity.y + ITEM_SIZE >= player.y - PICKUP_REACH_Y &&
entity.y <= player.y + PLAYER_HEIGHT + PICKUP_REACH_Y;
entity.y <= player.y + player.height + PICKUP_REACH_Y;
}
// as much as fits, the rest stays on the ground
@@ -1630,14 +1628,14 @@ export class GameServer {
#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 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;
}
// from the eyes to the closest point of its box
#entity_in_reach(player: ServerPlayer, entity: LivingEntity) {
const eye_y = player.y + PLAYER_EYE_HEIGHT;
const eye_y = player.y + player.eye_height;
const half = entity.width / 2;
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);
@@ -1780,3 +1778,9 @@ function placed_state(block_id: string, player: ServerPlayer): number | undefine
const facing = ((quarter % 4) + 4) % 4;
return set_state_value(default_block_value(0, info), info, "facing", facing)! >>> 16;
}
// where a player is now, for everyone else
function player_move(player: ServerPlayer): ServerMessage {
const { id, x, y, z, yaw, pitch } = player;
return { type: "player_move", id, x, y, z, yaw, pitch, ...(player.swimming && { swimming: true }) };
}
+1
View File
@@ -1002,6 +1002,7 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
return effect && { amplifier: effect.amplifier, duration: effect.duration };
},
remove_effect: (id) => player.remove_effect(known_effect(id)),
is_swimming: () => player.swimming,
};
}
+17 -1
View File
@@ -1,4 +1,10 @@
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
import {
PLAYER_EYE_HEIGHT,
PLAYER_HEIGHT,
PLAYER_SWIM_EYE_HEIGHT,
PLAYER_SWIM_HEIGHT,
PLAYER_WIDTH,
} from "$/common/constants.ts";
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import { Container, Cursor, ItemData, ItemStack } from "$/common/inventory.ts";
import type { GridRecipe } from "$/common/mod_data.ts";
@@ -45,6 +51,8 @@ export class ServerPlayer extends LivingEntity {
override width = PLAYER_WIDTH;
override height = PLAYER_HEIGHT;
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;
inventory = new Container(INVENTORY_SIZE);
// hunger and saturation, health is the entity's
@@ -180,6 +188,13 @@ export class ServerPlayer extends LivingEntity {
return this.inventory.get_item(this.selected_slot);
}
// the short box and low eyes while swimming, so drowning, reach and what they're in the way of match
set_swimming(swimming: boolean) {
this.swimming = swimming;
this.height = swimming ? PLAYER_SWIM_HEIGHT : PLAYER_HEIGHT;
this.eye_height = swimming ? PLAYER_SWIM_EYE_HEIGHT : PLAYER_EYE_HEIGHT;
}
player_info(): PlayerInfo {
return {
id: this.id,
@@ -192,6 +207,7 @@ export class ServerPlayer extends LivingEntity {
skin: this.skin,
slim: this.slim || undefined,
...(this.worn_list().length ? { worn: this.worn_list() } : {}),
...(this.swimming && { swimming: true }),
};
}
+5 -5
View File
@@ -132,7 +132,7 @@ Deno.test("the giant chestplate goes in the body slot and gives 20 more health w
assertEquals(curios_items(t.take(1))[body], {
id: "bworld:giant_chestplate",
count: 1,
lore: "When worn:\n+20 Max Health\nAfter 10s unhurt: Regeneration II",
lore: "When worn:\n+20 Max Health\nAfter 10s unhurt: Regeneration III",
});
assertEquals(alice.max_health, 40);
@@ -156,7 +156,7 @@ Deno.test("the giant chestplate goes in the body slot and gives 20 more health w
assertEquals(t.game.players()[0].health, 20);
});
Deno.test("the giant chestplate gives regeneration II after 10 seconds without being hurt", async () => {
Deno.test("the giant chestplate gives regeneration III after 10 seconds without being hurt", async () => {
const t = await setup();
t.send(1, { type: "chat", text: "/give bworld:giant_chestplate" });
const slot = last_container(t.take(1), "inventory").findIndex((i: Msg) => i?.id === "bworld:giant_chestplate");
@@ -168,17 +168,17 @@ Deno.test("the giant chestplate gives regeneration II after 10 seconds without b
for (let i = 0; i < 199; i++) t.game.tick();
assertEquals(regeneration(), undefined);
t.game.tick();
assertEquals(regeneration()?.amplifier, 1);
assertEquals(regeneration()?.amplifier, 2);
// it keeps being topped up while they stay unhurt
for (let i = 0; i < 200; i++) t.game.tick();
assertEquals(regeneration()?.amplifier, 1);
assertEquals(regeneration()?.amplifier, 2);
// being hurt starts the 10 seconds again, what they were given runs out
t.game.damage_player(alice, 2, "test");
for (let i = 0; i < 199; i++) t.game.tick();
assertEquals(regeneration(), undefined);
t.game.tick();
assertEquals(regeneration()?.amplifier, 1);
assertEquals(regeneration()?.amplifier, 2);
});
Deno.test("everyone sees what a player wears that has a worn model, and players joining later too", async () => {
+158 -6
View File
@@ -1,17 +1,26 @@
import { assert, assertAlmostEquals, assertEquals } from "@std/assert";
import { assert, assertAlmostEquals, assertEquals, assertFalse } from "@std/assert";
import { LocalPlayer } from "$/client/entity/local_player.ts";
import { InputManager } from "$/client/input_manager.ts";
import { Options } from "$/client/options.ts";
import type { Client } from "$/client/client.ts";
// a player on flat ground at y 0, maybe with a ceiling, and the positions it sends
function setup(ceiling = Infinity) {
const sent: { y: number }[] = [];
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 client = {
level: { has_collision: (_x: number, y: number) => y < 0 || y >= ceiling },
level: {
has_collision: world?.solid ?? ((_x: number, y: number) => y < 0 || y >= ceiling),
is_liquid: world?.water ?? (() => false),
},
screen: undefined,
options: new Options(),
connection: { send: (message: { type: string; y: number }) => message.type === "move" && sent.push(message) },
connection: {
send: (message: { type: string; y: number; swimming?: boolean }) =>
message.type === "move" && sent.push(message),
},
};
const player = new LocalPlayer(client as unknown as Client, "id", "alice");
player.set_position(0.5, 0, 0.5);
@@ -248,3 +257,146 @@ Deno.test("stepping from the edge of a block onto the one diagonal to it doesn't
assertEquals(player.y, 0);
assert(player.on_ground);
});
// a pool from y 0 to water_top, on a floor at y -1, with a wall at z -1 from y 0 to wall_top, its face at z 0. water
// over the wall when it's lower
function pool(water_top: number, wall_top = 1) {
const wall = (y: number, z: number) => z <= -1 && y >= 0 && y < wall_top;
return {
solid: (_x: number, y: number, z: number) => y < 0 || wall(y, z),
water: (_x: number, y: number, z: number) => y >= 0 && y < water_top && !wall(y, z),
};
}
// how fast it's going in blocks a second, from its last tick
function speed_after(player: LocalPlayer, ticks: number, keys: string[]) {
for (const key of keys) InputManager.keys_down.add(key);
for (let tick = 0; tick < ticks; tick++) player.tick();
const { x, y, z } = player;
player.tick();
InputManager.keys_down.clear();
return { horizontal: Math.hypot(player.x - x, player.z - z) * 20, vertical: (player.y - y) * 20 };
}
Deno.test("in water it sinks slowly, walks slowly, swims up holding jump and down sneaking", () => {
const in_pool = () => {
const { player } = setup(Infinity, pool(10));
player.set_position(0.5, 2, 0.5);
return player;
};
assertAlmostEquals(speed_after(in_pool(), 60, []).vertical, -0.45, 0.01);
assertAlmostEquals(speed_after(in_pool(), 60, ["KeyW"]).horizontal, 2, 0.01);
const rising = in_pool();
rising.set_position(0.5, 0, 0.5);
assertAlmostEquals(speed_after(rising, 30, ["Space"]).vertical, 3.55, 0.01);
const sinking = in_pool();
sinking.set_position(0.5, 9, 0.5);
assertAlmostEquals(speed_after(sinking, 30, ["ShiftLeft"]).vertical, -4.45, 0.01);
// holding both, they cancel out and it sinks like holding neither
assertAlmostEquals(speed_after(in_pool(), 60, ["Space", "ShiftLeft"]).vertical, -0.45, 0.01);
});
Deno.test("swimming up against the edge of a pool hops out onto a ledge a block above the water", () => {
// swimming up alone only gets the feet a little above the water
const { player } = setup(Infinity, pool(3, 4));
player.set_position(0.5, 1, 0.5);
for (let tick = 0; tick < 60; tick++) speed_after(player, 0, ["KeyW", "Space"]);
assert(player.z < -0.5 && player.y >= 4, `ended at z ${player.z}, y ${player.y}`);
// not against a wall under water
const under = setup(Infinity, pool(10)).player;
under.set_position(0.5, 0, 0.5);
for (let tick = 0; tick < 60; tick++) speed_after(under, 0, ["KeyW"]);
assert(under.z > 0 && under.y < 1, `went over it to z ${under.z}, y ${under.y}`);
});
// holding these keys for that many ticks
function hold(player: LocalPlayer, ticks: number, keys: string[]) {
for (const key of keys) InputManager.keys_down.add(key);
// like ClientLevel.tick
for (let tick = 0; tick < ticks; tick++) {
player.save_previous_position();
player.tick();
}
InputManager.keys_down.clear();
}
const SWIM = ["KeyW", "ControlLeft"];
Deno.test("sprinting with the eyes under water swims, in the short box with low eyes, and tells the server right away", () => {
const { player, sent } = setup(Infinity, pool(10));
player.set_position(0.5, 3, 0.5);
hold(player, 2, SWIM);
assert(player.swimming);
assertEquals(player.height, 0.8);
assertEquals(sent.at(-1)?.swimming, true);
hold(player, 10, SWIM);
assertAlmostEquals(player.eye_height, 0.6, 0.01);
// level, it doesn't sink, and it's faster than walking in water
const y = player.y;
assertAlmostEquals(speed_after(player, 80, SWIM).horizontal, 4, 0.01);
assertAlmostEquals(player.y, y, 0.01);
// letting go stands it back up, there's room
hold(player, 1, []);
assertFalse(player.swimming);
assertEquals(player.height, 1.79);
assertEquals(sent.at(-1)?.swimming, undefined);
});
Deno.test("it tips over to swim and stands back up over 10 ticks, lying the way it's going", () => {
const { player } = setup(Infinity, pool(10));
player.set_position(0.5, 5, 0.5);
player.pitch = -0.5;
hold(player, 6, SWIM);
assert(player.swim_amount > 0 && player.swim_amount < 1, `at ${player.swim_amount}`);
hold(player, 30, SWIM);
assertEquals(player.swim_amount, 1);
// diving, the body points down
assert(player.swim_pitch < -0.2, `pitch ${player.swim_pitch}`);
// still, it lies the way it looks
player.pitch = 0.3;
hold(player, 100, []);
assertEquals(player.swim_amount, 0);
assertAlmostEquals(player.swim_pitch, 0.3, 0.01);
});
Deno.test("swimming goes where it looks, down and up, but stays in the water at the surface", () => {
const diving = setup(Infinity, pool(10)).player;
diving.set_position(0.5, 5, 0.5);
diving.pitch = -0.5;
hold(diving, 30, SWIM);
assert(diving.swimming && diving.y < 3, `at y ${diving.y}`);
// water up to y 4: it comes up to the surface and swims along it with its head out, its feet in
const rising = setup(Infinity, pool(4)).player;
rising.set_position(0.5, 1, 0.5);
rising.pitch = 0.5;
hold(rising, 100, SWIM);
assert(rising.swimming && rising.in_water, "still swimming in the water");
assert(rising.y > 3 && rising.y < 4, `at y ${rising.y}`);
});
Deno.test("swimming fits through a 1 block gap, and stays lying down in it after letting go", () => {
// water up to y 3, and from z 0 on a ceiling at y 1, so the water there is a tunnel 1 block high
const { player } = setup(Infinity, {
solid: (_x, y, z) => y < 0 || (z < 0 && y >= 1),
water: (_x, y, z) => y >= 0 && (z < 0 ? y < 1 : y < 3),
});
player.set_position(0.5, 0, 0.5);
hold(player, 40, SWIM);
assert(player.z < -2, `stopped at z ${player.z}`);
hold(player, 10, []);
assert(player.swimming);
assertEquals(player.height, 0.8);
});
Deno.test("wading with the eyes out of the water doesn't start sprinting, so it doesn't swim", () => {
const { player } = setup(Infinity, pool(1));
hold(player, 20, SWIM);
assertFalse(player.sprinting);
assertFalse(player.swimming);
});
+29 -2
View File
@@ -1,5 +1,6 @@
import { assert, assertAlmostEquals } from "@std/assert";
import { move_body } from "$/common/physics.ts";
import { assert, assertAlmostEquals, assertEquals } from "@std/assert";
import { eyes_in_water, in_water, move_body } from "$/common/physics.ts";
import { type BlockRegistry, is_liquid_block } from "$/common/everything_registry.ts";
const body = (x: number, z: number, vx: number, vz: number) => ({ x, y: 0, z, vx, vy: 0, vz, width: 0.6, height: 1.8 });
// a block at x 0 to 1, z 1 to 2, on a floor
@@ -41,3 +42,29 @@ Deno.test("a body on the ground steps up onto something low, not onto a full blo
assertAlmostEquals(wall.x, 0.7);
assertAlmostEquals(wall.y, 0);
});
Deno.test("water is a block with no collision that can be placed into", () => {
const block = (has_collision: boolean, replaceable?: boolean) => ({ has_collision, replaceable }) as BlockRegistry;
assertEquals(is_liquid_block(block(false, true)), true);
assertEquals(is_liquid_block(block(true, true)), false);
assertEquals(is_liquid_block(block(false)), false);
assertEquals(is_liquid_block(undefined), false);
});
Deno.test("a body is in water by its feet or the middle of its box, and its eyes by its eye height", () => {
// water up to y 1, two blocks deep
const water = (_x: number, y: number, _z: number) => y === 0 || y === -1;
const at = (y: number) => ({ ...body(0.5, 0.5, 0, 0), y });
// standing in it up to the waist
assert(in_water(at(0), water));
assert(!eyes_in_water(at(0), 1.6, water));
// sunk to the bottom, the eyes too
assert(in_water(at(-1), water) && eyes_in_water(at(-1), 0.9, water));
// standing on the bottom of a 1 deep pool: only the feet are in it
const pool = (_x: number, y: number, _z: number) => y === 0;
assert(in_water(at(0), pool));
// with the feet below it, the middle of its box is in it
assert(in_water(at(-0.5), pool));
assert(!in_water(at(1), pool));
});
+101
View File
@@ -0,0 +1,101 @@
// swimming as the server sees it: each player's client says when they're swimming, which gives them the short box
// and low eyes, and tells everyone else. how they swim is the client's, see local_player_test.ts
import { assert, assertAlmostEquals, assertEquals, assertNotEquals } from "@std/assert";
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_SWIM_EYE_HEIGHT, PLAYER_SWIM_HEIGHT } from "$/common/constants.ts";
import { part_point, PARTS, type PlayerPose, pose_at, pose_to_world } from "$/client/rendering/player_model.ts";
import { test_game } from "./helpers.ts";
// deno-lint-ignore no-explicit-any
type Msg = any;
Deno.test("a player's client says when they swim, which shortens their box and tells everyone else", async () => {
const t = await test_game("mods");
t.join(1, "alice");
t.join(2, "bob");
const alice = t.game.players().find((player) => player.name === "alice")!;
t.take(2);
const api = t.game.mods.player(alice);
assertEquals(api.is_swimming(), false);
t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0, swimming: true });
assert(alice.swimming);
assert(api.is_swimming());
assertEquals(alice.height, PLAYER_SWIM_HEIGHT);
assertEquals(alice.eye_height, PLAYER_SWIM_EYE_HEIGHT);
const moved = t.take(2).findLast((m: Msg) => m.type === "player_move" && m.id === alice.id);
assertEquals(moved.swimming, true);
// someone joining now sees her swimming
const { players } = t.join(3, "carol");
assertEquals(players.find((player: Msg) => player.id === alice.id)?.swimming, true);
// a move without it stands her back up
t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
assertEquals(api.is_swimming(), false);
assertEquals(alice.height, PLAYER_HEIGHT);
assertEquals(alice.eye_height, PLAYER_EYE_HEIGHT);
const stood = t.take(2).findLast((m: Msg) => m.type === "player_move" && m.id === alice.id);
assertEquals(stood.swimming, undefined);
});
// how a swimming player is drawn, see client/rendering/player_model.ts
const pose = (swim?: { amount: number; pitch: number }, pitch = 0, position = 0) =>
pose_at({ x: 0, y: 0, z: 0, yaw: 0, pitch, slim: false, walk: { position, speed: 1 }, swim });
const world = (p: PlayerPose, name: string, x: number, y: number, z: number) => {
const part = PARTS.find((part) => part.name === name)!;
return pose_to_world(p)(...part_point(p, part, x, y, z));
};
Deno.test("not swimming at all, the pose is the walking one", () => {
for (const position of [0, 1, 2.5]) {
const walking = pose(undefined, 0.3, position);
const still = pose({ amount: 0, pitch: -1 }, 0.3, position);
assertEquals(still, walking);
for (const part of PARTS) {
assertEquals(world(still, part.name, 1, 2, 3), world(walking, part.name, 1, 2, 3));
}
}
});
Deno.test("swimming, the body lies flat in the short box, its head forward and facing where they look", () => {
const flat = pose({ amount: 1, pitch: 0 });
// the neck is ahead (the model faces -z) and the feet behind
const [, head_y, head_z] = world(flat, "head", 0, 0, 0);
const [, feet_y, feet_z] = world(flat, "right_leg", 0, -12, 0);
assert(head_z < -0.4 && feet_z > 0.8, `head at ${head_z}, feet at ${feet_z}`);
// the body is inside the box
for (const [x, y, z] of [[-4, 0, -2], [4, 12, 2], [-4, 12, -2], [4, 0, 2]]) {
const [, by] = world(flat, "body", x, y, z);
assert(by >= 0 && by <= PLAYER_SWIM_HEIGHT, `body at ${by}`);
}
assert(Math.abs(head_y - PLAYER_SWIM_HEIGHT / 2) < 0.2 && Math.abs(feet_y - PLAYER_SWIM_HEIGHT / 2) < 0.2);
// the face points where they look, whichever way the body lies
for (const [moving, look] of [[0, 0], [0, -0.5], [-0.8, -0.8], [0.4, 0.2]]) {
const p = pose({ amount: 1, pitch: moving }, look);
const [, back_y, back_z] = world(p, "head", 0, 4, 4);
const [, front_y, front_z] = world(p, "head", 0, 4, -4);
assertAlmostEquals(Math.atan2(front_y - back_y, back_z - front_z), look, 1e-9);
}
// diving, the head goes down
const [, diving_y] = world(pose({ amount: 1, pitch: -1 }), "head", 0, 8, 0);
assert(diving_y < head_y);
});
Deno.test("swimming, the arms go around half a turn apart and the legs flutter", () => {
const arm_tip = (p: PlayerPose, name: string) => world(p, name, 1, -10, 0);
// a whole stroke
const strokes = [0, 3, 6, 9, 12, 15, 18].map((position) => pose({ amount: 1, pitch: 0 }, 0, position));
const right = strokes.map((p) => arm_tip(p, "right_arm"));
// it goes both above and below the body over a stroke
assert(right.some(([, y]) => y > PLAYER_SWIM_HEIGHT) && right.some(([, y]) => y < 0.2));
// the other arm is on the other side
const [, right_y] = arm_tip(strokes[1], "right_arm");
const [, left_y] = arm_tip(strokes[1], "left_arm");
assert(Math.sign(right_y - 0.4) !== Math.sign(left_y - 0.4), `arms at ${right_y}, ${left_y}`);
// legs opposite each other
const [, right_leg] = world(strokes[0], "right_leg", 0, -12, 0);
const [, left_leg] = world(strokes[0], "left_leg", 0, -12, 0);
assertNotEquals(right_leg, left_leg);
});