Files
2026-11-22 07:44:13 -03:00

273 lines
9.4 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
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";
import { Menu, PlayerMenu } from "./menu.ts";
import { PlayerInfo } from "@/common/protocol.ts";
import { EXHAUSTION, type SavedVitals, Vitals } from "./vitals.ts";
import { PlayerChunks } from "./player_chunks.ts";
import { ATTRIBUTES, type AttributeType } from "./entity/attributes.ts";
import type { DamageSource, EntityLevel } from "./entity/entity.ts";
import { LivingEntity } from "./entity/living_entity.ts";
export const INVENTORY_SIZE = 9 * 4;
export const CRAFTING_SIZE = 10;
// what's saved about a player between sessions, by name
export interface SavedPlayer {
x: number;
y: number;
z: number;
yaw: number;
pitch: number;
selected_slot: number;
inventory: (ItemData | null)[];
// players saved before health and hunger start full
vitals?: SavedVitals;
// base64 png, see /skin
skin?: string;
slim?: boolean;
// see /fly
flying?: boolean;
// see /creative
creative?: boolean;
}
// the connection of the player machines use items as, see GameServer.use_item_on. nothing is ever sent to it
export const MACHINE_CONN = -1;
// the most ticks the server moves a knocked back player, in case they never land, like in water
const MAX_KNOCKBACK_TICKS = 20;
// a player is a living entity, like minecraft's Player: they have health, can be hurt and pushed around by mobs and
// other players, and have effects. their client moves them, except while they're knocked back: then the server does
// until they land, so it works even when their client isn't running, like in a background tab. they're kept apart
// from the entity manager's entities, clients hear about players through their own messages
export class ServerPlayer extends LivingEntity {
readonly type = "cubi:player";
readonly conn: number;
readonly name: string;
override y = 100;
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;
// 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;
// from /creative: placing doesn't use up what they hold, and breaking is instant and drops nothing. their client
// times breaking, so it only needs to know
creative = false;
inventory = new Container(INVENTORY_SIZE);
// hunger and saturation, health is the entity's
vitals = new Vitals();
// counts every position the server gave them. their client says which one it's heard of with each move, and moves
// from before the latest are ignored, they'd put them back where they were
teleport_id = 0;
// ticks the server has been moving them for, undefined when their client does
knockback_ticks: number | undefined;
// when the last move came, to tell walking from sprinting
last_move_tick = 0;
// ticks since they last attacked or changed their held item, like minecraft's attackStrengthTicker
attack_strength_ticker = 0;
crafting = new Container(CRAFTING_SIZE);
cursor: Cursor = { item: undefined };
selected_slot = 0;
// menu 0, always there
inventory_menu: PlayerMenu;
// the menu they have open, like minecraft's containerMenu without the inventory menu
menu: Menu | undefined;
// the last menu id given out, they go 1 to 100 and around
menu_id = 0;
// what mods show on them, by each mod's key, see set_worn. not saved, mods set it again when they join
worn = new Map<string, ItemStack[]>();
// the json of the worn list everyone was last sent, to send it again when it changes
worn_sent = "[]";
// base64 png, see /skin. undefined is the default skin
skin: string | undefined;
// the skin is for the model with 3 pixel wide arms
slim = false;
// a /skin download is on its way, one at a time
downloading_skin = false;
// last json sent for each synced thing, so only changes get sent
sent = new Map<string, string>();
// the chunks their client has and still needs
chunks: PlayerChunks;
// the view distance their client asked for, which the server's might cap, undefined when it didn't say
requested_view_distance: number | undefined;
constructor(
level: EntityLevel,
conn: number,
name: string,
view_distance: number,
recipes: () => GridRecipe[] = () => [],
) {
super(level);
this.conn = conn;
this.name = name;
this.chunks = new PlayerChunks(view_distance);
this.inventory_menu = new PlayerMenu(this.inventory, this.crafting, recipes);
}
// the open menu, or menu 0 when none is
get container_menu(): Menu {
return this.menu ?? this.inventory_menu;
}
override default_attributes(): [AttributeType, number?][] {
return [
...super.default_attributes(),
// a fist does half a heart, like minecraft
[ATTRIBUTES.attack_damage, 1],
[ATTRIBUTES.attack_speed],
[ATTRIBUTES.physical_shielding],
[ATTRIBUTES.arcane_shielding],
[ATTRIBUTES.block_interaction_range],
[ATTRIBUTES.entity_interaction_range],
];
}
// they're saved by name with the players, not with the world's entities
override get persistent() {
return false;
}
// their client moves them, this only burns, falls out of the world and counts effects and hurt time down. while
// knocked back it moves them like a mob that isn't walking anywhere, landing hands them back to their client
// its client moves it, fluids included, see LocalPlayer
override get pushed_by_fluid() {
return false;
}
override tick() {
this.base_tick();
this.attack_strength_ticker += 1;
if (!this.dead) {
this.tick_effects();
}
if (this.knockback_ticks === undefined) return;
this.forward = this.strafe = this.speed = 0;
this.travel();
this.knockback_ticks += 1;
if ((this.on_ground && this.vy <= 0) || this.knockback_ticks >= MAX_KNOCKBACK_TICKS) {
this.knockback_ticks = undefined;
}
}
override knockback(strength: number, dx: number, dz: number) {
super.knockback(strength, dx, dz);
if (this.vx || this.vy || this.vz) this.knockback_ticks ??= 0;
}
// back to their client, where they are now
stop_knockback() {
this.knockback_ticks = undefined;
this.vx = this.vy = this.vz = 0;
}
override on_hurt(_source: DamageSource) {
this.vitals.add_exhaustion(EXHAUSTION.damage);
}
// they don't drop loot or fall over, the game server drops what they carry and respawns them
override die(source: DamageSource) {
this.level.on_death(this, source);
}
// like minecraft's getAttackStrengthScale: 0 right after attacking, filling up to 1 over 20 / attack_speed ticks
attack_strength(): number {
const delay = 20 / this.attribute(ATTRIBUTES.attack_speed);
return Math.min(1, Math.max(0, (this.attack_strength_ticker + 0.5) / delay));
}
get held_item(): ItemStack | undefined {
return this.inventory.get_item(this.selected_slot);
}
// whether a sound at x y z heard as far as range reaches their ears
hears(x: number, y: number, z: number, range: number) {
return Math.hypot(x - this.x, y - (this.y + this.eye_height), z - this.z) < range;
}
// 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,
name: this.name,
x: this.x,
y: this.y,
z: this.z,
yaw: this.yaw,
pitch: this.pitch,
skin: this.skin,
slim: this.slim || undefined,
...(this.worn_list().length ? { worn: this.worn_list() } : {}),
...(this.swimming && { swimming: true }),
};
}
// what they wear that shows, every key's in the order they were first set: the items that have a worn model
worn_list(): ItemData[] {
return [...this.worn.values()].flat()
.filter((stack) => EverythingRegistry.get<ItemRegistry>("items", stack.type_id)?.worn)
.map((stack) => stack.to_data());
}
save_player(): SavedPlayer {
return {
x: this.x,
y: this.y,
z: this.z,
yaw: this.yaw,
pitch: this.pitch,
selected_slot: this.selected_slot,
inventory: this.inventory.to_data(),
vitals: { health: this.health, ...this.vitals.save() },
skin: this.skin,
slim: this.slim || undefined,
flying: this.flying || undefined,
creative: this.creative || undefined,
};
}
load_player(saved: SavedPlayer) {
this.x = saved.x;
this.y = saved.y;
this.z = saved.z;
this.yaw = saved.yaw;
this.pitch = saved.pitch;
this.selected_slot = saved.selected_slot;
this.inventory.load(saved.inventory);
this.vitals.load(saved.vitals);
this.load_health(saved.vitals?.health ?? this.max_health);
this.skin = saved.skin;
this.slim = saved.slim ?? false;
this.flying = saved.flying === true;
this.creative = saved.creative === true;
}
}