Fishing hook

This commit is contained in:
2026-09-28 20:52:53 -03:00
parent d606bc4b55
commit ad6adb49dc
16 changed files with 258 additions and 37 deletions
+39 -9
View File
@@ -532,16 +532,35 @@ Mobs are an entity in `entities/` and a bedrock entity model in `models/`. `enti
} }
``` ```
| Field | Default | What it does | | Field | Default | What it does |
| ---------------- | ------- | --------------------------------------------------------------------------- | | ---------------- | ---------- | ------------------------------------------------------------------------------------- |
| `model` | | An entity model, see below. | | `model` | | An entity model, see below. Without one it's drawn as its texture, facing the camera. |
| `texture` | | Any texture, stretched to the model's `texture_width` and `texture_height`. | | `texture` | | Any texture, stretched to the model's `texture_width` and `texture_height`. |
| `width`/`height` | | Its collision box in blocks. Its eyes are at 85% of the height. | | `behavior` | `"animal"` | `"animal"` or `"scripted"`, see below. |
| `max_health` | `10` | Half hearts. | | `width`/`height` | | Its collision box in blocks. Its eyes are at 85% of the height. |
| `movement_speed` | `0.25` | Minecraft's per tick speed, 0.25 for most animals. | | `max_health` | `10` | Half hearts. |
| `movement_speed` | `0.25` | Minecraft's per tick speed, 0.25 for most animals. |
Every entity is an animal for now: it wanders around, panics when hurt, looks at players now and then, swims up in An animal wanders around, panics when hurt, looks at players now and then, swims up in water and never despawns. A
water and never despawns. `/summon <entity>` spawns one where you stand. scripted entity stays where a script puts it (see `spawn_entity` in [Server scripts](#server-scripts)): it doesn't fall,
think or get hurt, and isn't saved with the world, so a script never finds one it doesn't know about after a restart.
The fishing hook is one, drawn as its texture since it has no model:
```json
{
"format_version": 1,
"entity": {
"id": "bworld:fishing_hook",
"texture": "bworld:fishing_hook",
"behavior": "scripted",
"width": 0.25,
"height": 0.25
}
}
```
Without a model, the whole texture is drawn 16 pixels to a block, centered on the middle of its box.
`/summon <entity>` spawns one where you stand.
Entity models are `models/<name>.geo.json`, as Blockbench exports them for Bedrock (the "Bedrock Entity" format), with Entity models are `models/<name>.geo.json`, as Blockbench exports them for Bedrock (the "Bedrock Entity" format), with
id `<mod_id>:<name>`. Only the first geometry is used, and from it the bones' `name`, `parent`, `pivot` and `rotation` id `<mod_id>:<name>`. Only the first geometry is used, and from it the bones' `name`, `parent`, `pivot` and `rotation`
@@ -791,6 +810,7 @@ interface ServerWorld {
set_state(x: number, y: number, z: number, name: string, value: number): boolean; set_state(x: number, y: number, z: number, name: string, value: number): boolean;
get_block_data<T>(x: number, y: number, z: number): T | undefined; get_block_data<T>(x: number, y: number, z: number): T | undefined;
drop_item(x: number, y: number, z: number, item: ItemStack): void; // pops out of the block, like drops drop_item(x: number, y: number, z: number, item: ItemStack): void; // pops out of the block, like drops
spawn_entity(id: string, x: number, y: number, z: number): EntityRef; // feet at x y z, see Entities
is_loaded(x: number, z: number): boolean; is_loaded(x: number, z: number): boolean;
readonly seed: string; readonly seed: string;
readonly time: number; // world time, see below readonly time: number; // world time, see below
@@ -798,6 +818,16 @@ interface ServerWorld {
set_time(time: number): void; // synced to every player set_time(time: number): void; // synced to every player
} }
// once it's removed, by a script or anything else, it stays removed and teleporting it does nothing
interface EntityRef {
readonly id: string;
readonly type: string;
readonly position: { x: number; y: number; z: number };
readonly removed: boolean;
teleport(x: number, y: number, z: number): void;
remove(): void;
}
interface Player { interface Player {
readonly id: string; readonly id: string;
readonly name: string; readonly name: string;
+56 -7
View File
@@ -1,9 +1,12 @@
// mobs mods define (entities/<name>.json), drawn with their entity model and a texture from the atlas. there are no // entities mods define (entities/<name>.json), drawn with their entity model and a texture from the atlas. there are no
// animations yet: the model turns to the entity's yaw, and a bone named "head" to where it looks // animations yet: the model turns to the entity's yaw, and a bone named "head" to where it looks. entities without a
// model are their texture facing the camera, like minecraft's fishing hook
import { AssetManager } from "$/client/assets.ts"; import { AssetManager } from "$/client/assets.ts";
import type { Camera } from "$/client/camera.ts";
import type { RemoteEntity } from "$/client/entity/remote_entity.ts"; import type { RemoteEntity } from "$/client/entity/remote_entity.ts";
import type { Texture } from "$/client/renderer/mod.ts"; import { push_vertex, type Texture } from "$/client/renderer/mod.ts";
import { get_sprite_region } from "$/client/sprites.ts"; import { get_sprite_region } from "$/client/sprites.ts";
import type { SpriteRegion } from "$/common/constants.ts";
import { EverythingRegistry } from "$/common/everything_registry.ts"; import { EverythingRegistry } from "$/common/everything_registry.ts";
import type { EntityBoneJson, EntityJson, EntityModelJson } from "$/common/mod_data.ts"; import type { EntityBoneJson, EntityJson, EntityModelJson } from "$/common/mod_data.ts";
import { push_box, type Vec3 } from "./player_renderer.ts"; import { push_box, type Vec3 } from "./player_renderer.ts";
@@ -14,13 +17,18 @@ const PIXEL = 1 / 16;
const HURT_TINT: Vec3 = [1, 0.6, 0.6]; const HURT_TINT: Vec3 = [1, 0.6, 0.6];
// the atlas has to be the current texture // the atlas has to be the current texture
export function render_mod_entity(entity: RemoteEntity, partial_tick: number) { export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_tick: number) {
const json = EverythingRegistry.get<EntityJson>("entities", entity.type); const json = EverythingRegistry.get<EntityJson>("entities", entity.type);
const model = json && EverythingRegistry.get<EntityModelJson>("entity_models", json.model); if (!json) return;
if (!model) return;
const atlas = AssetManager.instance.get<Texture>("bworld:textures"); const atlas = AssetManager.instance.get<Texture>("bworld:textures");
const region = get_sprite_region(json.texture); const region = get_sprite_region(json.texture);
if (json.model === undefined) {
render_sprite(entity, camera, atlas, region, partial_tick);
return;
}
const model = EverythingRegistry.get<EntityModelJson>("entity_models", json.model);
if (!model) return;
const to_uv = (u: number, v: number): [number, number] => [ const to_uv = (u: number, v: number): [number, number] => [
(region.x + u * region.width / model.texture_width) / atlas.width, (region.x + u * region.width / model.texture_width) / atlas.width,
(region.y + v * region.height / model.texture_height) / atlas.height, (region.y + v * region.height / model.texture_height) / atlas.height,
@@ -57,6 +65,47 @@ export function render_mod_entity(entity: RemoteEntity, partial_tick: number) {
} }
} }
// the whole texture, 16 pixels to a block, facing the camera around the middle of the entity's box
function render_sprite(
entity: RemoteEntity,
camera: Camera,
atlas: Texture,
region: SpriteRegion,
partial_tick: number,
) {
const { x, y, z } = entity.render_position(partial_tick);
const cy = y + entity.height / 2;
// the camera's right and up, halved to the sprite's size
const half_width = region.width * PIXEL / 2;
const half_height = region.height * PIXEL / 2;
const [yaw_sin, yaw_cos] = [Math.sin(camera.yaw), Math.cos(camera.yaw)];
const [pitch_sin, pitch_cos] = [Math.sin(camera.pitch), Math.cos(camera.pitch)];
const right: Vec3 = [yaw_cos * half_width, 0, -yaw_sin * half_width];
const up: Vec3 = [yaw_sin * pitch_sin * half_height, pitch_cos * half_height, yaw_cos * pitch_sin * half_height];
const [r, g, b] = entity.hurt_time > 0 || entity.dead ? HURT_TINT : [1, 1, 1];
const u0 = region.x / atlas.width;
const v0 = region.y / atlas.height;
const u1 = (region.x + region.width) / atlas.width;
const v1 = (region.y + region.height) / atlas.height;
// bottom left, bottom right, top right, top left: counter clockwise seen from the camera
const corners = [[-1, -1], [1, -1], [1, 1], [-1, 1]];
for (const i of [0, 1, 2, 0, 2, 3]) {
const [sx, sy] = corners[i];
push_vertex(
x + right[0] * sx + up[0] * sy,
cy + right[1] * sx + up[1] * sy,
z + right[2] * sx + up[2] * sy,
sx < 0 ? u0 : u1,
sy < 0 ? v1 : v0,
r,
g,
b,
1,
);
}
}
// 3 rows of 4, the last column moving: a turn and a move, from a bone's pixels to the model's // 3 rows of 4, the last column moving: a turn and a move, from a bone's pixels to the model's
type Matrix = number[]; type Matrix = number[];
+1 -1
View File
@@ -42,7 +42,7 @@ export class GameRenderer {
begin_mode_3d(camera); begin_mode_3d(camera);
this.level_renderer.render_opaque(client.level, camera); this.level_renderer.render_opaque(client.level, camera);
this.level_renderer.render_destroy_progress(client.game_mode); this.level_renderer.render_destroy_progress(client.game_mode);
this.level_renderer.render_entities(client.level, client.player, partial_tick); this.level_renderer.render_entities(client.level, camera, client.player, partial_tick);
this.level_renderer.render_translucent(client.level, camera); this.level_renderer.render_translucent(client.level, camera);
end_mode_3d(); end_mode_3d();
this.hand.render(client.player.inventories); this.hand.render(client.player.inventories);
+2 -2
View File
@@ -94,7 +94,7 @@ export class LevelRenderer {
} }
// every entity but the one the camera is in // every entity but the one the camera is in
render_entities(level: ClientLevel, camera_entity: Entity, partial_tick: number) { render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity, partial_tick: number) {
flush_batch(); flush_batch();
const default_skin = AssetManager.instance.get<Texture>("bworld:skin"); const default_skin = AssetManager.instance.get<Texture>("bworld:skin");
for (const entity of level.entities.values()) { for (const entity of level.entities.values()) {
@@ -114,7 +114,7 @@ export class LevelRenderer {
if (entity instanceof ItemEntity) { if (entity instanceof ItemEntity) {
render_item_entity(entity, partial_tick); render_item_entity(entity, partial_tick);
} else if (entity instanceof RemoteEntity) { } else if (entity instanceof RemoteEntity) {
render_mod_entity(entity, partial_tick); render_mod_entity(entity, camera, partial_tick);
} }
} }
flush_batch(); flush_batch();
+4 -4
View File
@@ -98,10 +98,10 @@ function draw_item_item(item: ItemStack, item_info: ItemRegistry, x: number, y:
const sprite_region = get_sprite_region(texture_id); const sprite_region = get_sprite_region(texture_id);
draw_texture_region( draw_texture_region(
AssetManager.instance.get("bworld:textures"), AssetManager.instance.get("bworld:textures"),
sprite_region.x * 16, sprite_region.x,
sprite_region.y * 16, sprite_region.y,
16, sprite_region.width,
16, sprite_region.height,
x + 3, x + 3,
y + 3, y + 3,
SLOT_SIZE - 6, SLOT_SIZE - 6,
+12
View File
@@ -177,6 +177,8 @@ export interface ServerWorld {
get_block_data<T>(x: number, y: number, z: number): T | undefined; get_block_data<T>(x: number, y: number, z: number): T | undefined;
// pops an item out of the block at x y z, like a broken block's drops // pops an item out of the block at x y z, like a broken block's drops
drop_item(x: number, y: number, z: number, item: ItemStack): void; drop_item(x: number, y: number, z: number, item: ItemStack): void;
// an entity from entities/ with its feet at x y z. throws for kinds that don't exist
spawn_entity(id: Id, x: number, y: number, z: number): EntityRef;
is_loaded(x: number, z: number): boolean; is_loaded(x: number, z: number): boolean;
readonly seed: string; readonly seed: string;
// ticks since 06:00 of day 1. a day is 36000 ticks (06:00 to 18:00), a night 12000 // ticks since 06:00 of day 1. a day is 36000 ticks (06:00 to 18:00), a night 12000
@@ -186,6 +188,16 @@ export interface ServerWorld {
set_time(time: number): void; set_time(time: number): void;
} }
// an entity in the world. once it's removed, by a script or anything else, it stays removed and moving it does nothing
export interface EntityRef {
readonly id: string;
readonly type: Id;
readonly position: Readonly<Position>;
readonly removed: boolean;
teleport(x: number, y: number, z: number): void;
remove(): void;
}
export interface Player { export interface Player {
readonly id: string; readonly id: string;
readonly name: string; readonly name: string;
+1 -1
View File
@@ -178,7 +178,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
if ((entity_owners.get(json.id)?.length ?? 0) > 1) { if ((entity_owners.get(json.id)?.length ?? 0) > 1) {
errors.push(`${file}: entity ${json.id} is also defined by ${entity_owners.get(json.id)!.join(", ")}`); errors.push(`${file}: entity ${json.id} is also defined by ${entity_owners.get(json.id)!.join(", ")}`);
} }
uses(file, json.model, "entity model"); if (json.model !== undefined) uses(file, json.model, "entity model");
uses(file, json.texture, "texture"); uses(file, json.texture, "texture");
} }
for (const { file, json } of mod.entity_models) { for (const { file, json } of mod.entity_models) {
+9 -3
View File
@@ -80,12 +80,15 @@ export interface ItemJson {
components?: Record<string, unknown>; components?: Record<string, unknown>;
} }
// a kind of mob, drawn with an entity model and one texture. it wanders around, panics when hurt and looks at players // a kind of entity, drawn with an entity model and one texture, or without a model as its texture facing the camera
export interface EntityJson { export interface EntityJson {
id: string; id: string;
// an entity model, see EntityModelJson // an entity model, see EntityModelJson
model: string; model?: string;
texture: string; texture: string;
// "animal" (the default) wanders around, panics when hurt and looks at players. "scripted" stays where scripts put
// it: no gravity, ai or health, and it isn't saved with the world, like the fishing hook
behavior?: "animal" | "scripted";
// its collision box in blocks, width is for both x and z // its collision box in blocks, width is for both x and z
width: number; width: number;
height: number; height: number;
@@ -629,9 +632,12 @@ export function validate_entity(json: unknown): Problems {
if (!is_object(json)) return ["entity must be an object"]; if (!is_object(json)) return ["entity must be an object"];
const problems = [ const problems = [
...validate_id(json.id, "id"), ...validate_id(json.id, "id"),
...validate_id(json.model, "model"), ...(json.model === undefined ? [] : validate_id(json.model, "model")),
...validate_id(json.texture, "texture"), ...validate_id(json.texture, "texture"),
]; ];
if (json.behavior !== undefined && json.behavior !== "animal" && json.behavior !== "scripted") {
problems.push('behavior must be "animal" or "scripted"');
}
for (const key of ["width", "height"]) { for (const key of ["width", "height"]) {
if (typeof json[key] !== "number" || json[key] <= 0 || json[key] > 16) { if (typeof json[key] !== "number" || json[key] <= 0 || json[key] > 16) {
problems.push(`${key} must be a number of blocks above 0, at most 16`); problems.push(`${key} must be a number of blocks above 0, at most 16`);
+10
View File
@@ -0,0 +1,10 @@
{
"format_version": 1,
"entity": {
"id": "bworld:fishing_hook",
"texture": "bworld:fishing_hook",
"behavior": "scripted",
"width": 0.25,
"height": 0.25
}
}
+20 -5
View File
@@ -1,5 +1,5 @@
// the base game's block and item behavior, written against the same api as any other mod // the base game's block and item behavior, written against the same api as any other mod
import type { BlockRef, Container, Player, ScreenHandle, ServerContext } from "bworld/server"; import type { BlockRef, Container, EntityRef, Player, ScreenHandle, ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) { export function setup(ctx: ServerContext) {
register_hoeable(ctx); register_hoeable(ctx);
@@ -508,12 +508,19 @@ function register_farming(ctx: ServerContext) {
}); });
} }
// fishing, like minecraft's without the bobber: right click water with a rod to cast, wait for a bite, and right click // fishing, like minecraft's: right click water with a rod to cast, wait for a bite, and right click again before it
// again before it gets away to reel it in. there's no hook entity yet, so a chat message says when something bites // gets away to reel it in. the hook floats on the water, and goes under when something bites
const FISHING_ROD = "bworld:fishing_rod"; const FISHING_ROD = "bworld:fishing_rod";
const FISHING_HOOK = "bworld:fishing_hook";
// further than this from where they cast, the line snaps // further than this from where they cast, the line snaps
const LINE_LENGTH = 16; const LINE_LENGTH = 16;
// the hook's feet under the water's surface, so its red stripe floats right on it (the hook's sprite is 16 pixels
// around the middle of its 0.25 block box, the stripe is 1.5 pixels above that)
const HOOK_DEPTH = 0.125 + 1.5 / 16;
// how far it bobs up and down, and how far under it goes with a bite
const HOOK_BOB = 0.03;
const HOOK_DIP = 0.15;
interface FishingRodParams { interface FishingRodParams {
// ticks until something bites, the shortest and longest, like minecraft's 5 to 30 seconds // ticks until something bites, the shortest and longest, like minecraft's 5 to 30 seconds
@@ -532,6 +539,7 @@ interface Cast {
// the hotbar slot the rod is in, switching away reels it in // the hotbar slot the rod is in, switching away reels it in
slot: number; slot: number;
params: FishingRodParams; params: FishingRodParams;
hook: EntityRef;
// ticks, when something bites and when it gets away // ticks, when something bites and when it gets away
bite_at: number; bite_at: number;
escape_at?: number; escape_at?: number;
@@ -559,6 +567,7 @@ function register_fishing(ctx: ServerContext) {
const stop = (player: Player | undefined, id: string) => { const stop = (player: Player | undefined, id: string) => {
const cast = casts.get(id); const cast = casts.get(id);
casts.delete(id); casts.delete(id);
cast?.hook.remove();
const rod = cast && player?.inventory.get(cast.slot); const rod = cast && player?.inventory.get(cast.slot);
if (rod?.id === FISHING_ROD) rod.data = undefined; if (rod?.id === FISHING_ROD) rod.data = undefined;
}; };
@@ -601,6 +610,7 @@ function register_fishing(ctx: ServerContext) {
block: water.block, block: water.block,
slot: player.selected_slot, slot: player.selected_slot,
params, params,
hook: ctx.world.spawn_entity(FISHING_HOOK, water.x + 0.5, water.y + 1 - HOOK_DEPTH, water.z + 0.5),
bite_at: ctx.system.current_tick + between(params.wait), bite_at: ctx.system.current_tick + between(params.wait),
}); });
rod.data = { cast: true }; rod.data = { cast: true };
@@ -615,10 +625,13 @@ function register_fishing(ctx: ServerContext) {
const distance = Math.hypot(x - cast.x, y - cast.y, z - cast.z); const distance = Math.hypot(x - cast.x, y - cast.y, z - cast.z);
if ( if (
!player || player.selected_slot !== cast.slot || player.held_item?.id !== FISHING_ROD || !player || player.selected_slot !== cast.slot || player.held_item?.id !== FISHING_ROD ||
distance > LINE_LENGTH || ctx.world.get_block(cast.x, cast.y, cast.z) !== cast.block distance > LINE_LENGTH || ctx.world.get_block(cast.x, cast.y, cast.z) !== cast.block ||
cast.hook.removed
) { ) {
stop(player, id); stop(player, id);
} else if (cast.escape_at === undefined && now >= cast.bite_at) { continue;
}
if (cast.escape_at === undefined && now >= cast.bite_at) {
cast.escape_at = now + between(cast.params.bite); cast.escape_at = now + between(cast.params.bite);
player.send_message("Something's biting! Right click to reel it in"); player.send_message("Something's biting! Right click to reel it in");
} else if (cast.escape_at !== undefined && now >= cast.escape_at) { } else if (cast.escape_at !== undefined && now >= cast.escape_at) {
@@ -626,6 +639,8 @@ function register_fishing(ctx: ServerContext) {
cast.escape_at = undefined; cast.escape_at = undefined;
cast.bite_at = now + between(cast.params.wait); cast.bite_at = now + between(cast.params.wait);
} }
const bob = cast.escape_at === undefined ? Math.sin(now / 40 * Math.PI * 2) * HOOK_BOB : -HOOK_DIP;
cast.hook.teleport(cast.x + 0.5, cast.y + 1 - HOOK_DEPTH + bob, cast.z + 0.5);
} }
}); });
} }
+5
View File
@@ -191,6 +191,11 @@ export abstract class Entity {
return MAX_AIR; return MAX_AIR;
} }
// saved with the world. things scripts keep track of themselves aren't, they wouldn't know them after a restart
get persistent() {
return true;
}
set_position(x: number, y: number, z: number) { set_position(x: number, y: number, z: number) {
this.x = x; this.x = x;
this.y = y; this.y = y;
+3 -1
View File
@@ -250,7 +250,9 @@ export class EntityManager implements EntityLevel {
// entities riding something are saved with what they ride // entities riding something are saved with what they ride
save(): SavedEntity[] { save(): SavedEntity[] {
const saved = this.all().filter((entity) => !entity.vehicle).map((entity) => entity.save()); const saved = this.all().filter((entity) => !entity.vehicle && entity.persistent).map((entity) =>
entity.save()
);
return [...saved, ...this.#unknown]; return [...saved, ...this.#unknown];
} }
+30 -2
View File
@@ -1,7 +1,8 @@
// mobs mods define in entities/<name>.json (see EntityJson): each one is a kind of animal that wanders around, // the kinds of entity mods define in entities/<name>.json (see EntityJson): animals that wander around, panic when hurt
// panics when hurt and looks at players now and then, like minecraft's simpler animals // and look at players now and then, like minecraft's simpler animals, and scripted ones that stay where scripts put them
import type { EntityJson } from "$/common/mod_data.ts"; import type { EntityJson } from "$/common/mod_data.ts";
import { ATTRIBUTES, type AttributeType } from "./attributes.ts"; import { ATTRIBUTES, type AttributeType } from "./attributes.ts";
import { Entity } from "./entity.ts";
import type { EntityFactory } from "./entity_types.ts"; import type { EntityFactory } from "./entity_types.ts";
import { FloatGoal, LookAtPlayerGoal, PanicGoal, RandomLookAroundGoal, RandomStrollGoal } from "./goals.ts"; import { FloatGoal, LookAtPlayerGoal, PanicGoal, RandomLookAroundGoal, RandomStrollGoal } from "./goals.ts";
import { Mob } from "./mob.ts"; import { Mob } from "./mob.ts";
@@ -9,6 +10,10 @@ import { Mob } from "./mob.ts";
// the entity's class. the attributes are read while LivingEntity is being built, before any field of a subclass is // the entity's class. the attributes are read while LivingEntity is being built, before any field of a subclass is
// set, so each kind gets its own class that has its json already // set, so each kind gets its own class that has its json already
export function mod_entity_factory(json: EntityJson): EntityFactory { export function mod_entity_factory(json: EntityJson): EntityFactory {
if (json.behavior === "scripted") {
return (level) => new ScriptedEntity(level, json);
}
class ModEntity extends Mob { class ModEntity extends Mob {
readonly type = json.id; readonly type = json.id;
override width = json.width; override width = json.width;
@@ -38,3 +43,26 @@ export function mod_entity_factory(json: EntityJson): EntityFactory {
} }
return (level) => new ModEntity(level); return (level) => new ModEntity(level);
} }
// it doesn't fall, think or get hurt, the script that spawned it moves it and takes it away, like the fishing hook.
// it isn't saved with the world: after a restart that script wouldn't know about it anymore
class ScriptedEntity extends Entity {
readonly type: string;
override no_gravity = true;
constructor(level: Entity["level"], json: EntityJson) {
super(level);
this.type = json.id;
this.width = json.width;
this.height = json.height;
this.eye_height = json.height * 0.85;
}
override tick() {
this.base_tick();
}
override get persistent() {
return false;
}
}
+31
View File
@@ -11,6 +11,7 @@ import type {
CommandSource, CommandSource,
Container, Container,
ContainerScreenOptions, ContainerScreenOptions,
EntityRef,
EventSignal, EventSignal,
ItemComponent, ItemComponent,
ItemStack, ItemStack,
@@ -40,6 +41,8 @@ import { AIR_ID } from "$/common/protocol.ts";
import type { GameServer } from "./game_server.ts"; import type { GameServer } from "./game_server.ts";
import type { OpenScreen, ServerPlayer } from "./player.ts"; import type { OpenScreen, ServerPlayer } from "./player.ts";
import { MAX_HEALTH } from "./vitals.ts"; import { MAX_HEALTH } from "./vitals.ts";
import type { Entity } from "./entity/entity.ts";
import { create_entity } from "./entity/entity_types.ts";
import type { ScreenLayout } from "$/common/protocol.ts"; import type { ScreenLayout } from "$/common/protocol.ts";
// a list of handlers that can't break each other: one throwing is logged under its mod and the rest still run // a list of handlers that can't break each other: one throwing is logged under its mod and the rest still run
@@ -432,6 +435,15 @@ export class ModRuntime {
}, },
get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never, get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never,
drop_item: (x, y, z, item) => void game().pop_item(x, y, z, new_stack(item)), drop_item: (x, y, z, item) => void game().pop_item(x, y, z, new_stack(item)),
spawn_entity: (id, x, y, z) => {
const entity = EverythingRegistry.get("entities", id)
? create_entity(game().entities, id)
: undefined;
if (!entity) throw new Error(`unknown entity ${id}`);
entity.set_position(x, y, z);
game().entities.add_entity(entity);
return entity_ref(entity);
},
is_loaded: () => true, is_loaded: () => true,
get seed() { get seed() {
return game().world.seed; return game().world.seed;
@@ -788,3 +800,22 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
}, },
}; };
} }
function entity_ref(entity: Entity): EntityRef {
return {
id: entity.id,
type: entity.type,
get position() {
return { x: entity.x, y: entity.y, z: entity.z };
},
get removed() {
return entity.removed;
},
teleport(x, y, z) {
if (!entity.removed) entity.set_position(x, y, z);
},
remove() {
entity.remove();
},
};
}
+15 -1
View File
@@ -36,18 +36,28 @@ async function setup() {
} }
return false; return false;
}; };
return { ...t, slot, rod, cast, reel, fish, wait_for_bite }; const hooks = () => t.game.entities.all().filter((e) => e.type === "bworld:fishing_hook");
return { ...t, slot, rod, cast, reel, fish, wait_for_bite, hooks };
} }
Deno.test("cast into water, reel in a fish once something bites", async () => { Deno.test("cast into water, reel in a fish once something bites", async () => {
const t = await setup(); const t = await setup();
t.cast(); t.cast();
assertEquals(t.rod()?.data, { cast: true }); assertEquals(t.rod()?.data, { cast: true });
// the hook floats on the water, and goes under when something bites
assertEquals(t.hooks().length, 1);
const hook = t.hooks()[0];
assertEquals([hook.x, hook.z], [2.5, 0.5]);
const floating = hook.y;
assert(floating > 100.7 && floating < 101, String(floating));
assert(t.wait_for_bite()); assert(t.wait_for_bite());
assert(hook.y < floating - 0.1, String(hook.y));
t.reel(); t.reel();
assertEquals(t.fish().length, 1); assertEquals(t.fish().length, 1);
assertEquals(t.rod()?.data, undefined); assertEquals(t.rod()?.data, undefined);
t.game.tick();
assertEquals(t.hooks().length, 0);
}); });
Deno.test("reeling in before a bite catches nothing", async () => { Deno.test("reeling in before a bite catches nothing", async () => {
@@ -72,6 +82,8 @@ Deno.test("switching away from the rod takes the line out", async () => {
t.send(1, { type: "select_slot", slot: (t.slot + 1) % 9 }); t.send(1, { type: "select_slot", slot: (t.slot + 1) % 9 });
t.game.tick(); t.game.tick();
assertEquals(t.rod()?.data, undefined); assertEquals(t.rod()?.data, undefined);
t.game.tick();
assertEquals(t.hooks().length, 0);
t.send(1, { type: "select_slot", slot: t.slot }); t.send(1, { type: "select_slot", slot: t.slot });
assert(!t.wait_for_bite()); assert(!t.wait_for_bite());
}); });
@@ -82,6 +94,8 @@ Deno.test("the line comes out when the water is gone", async () => {
t.game.set_block(2, 100, 0, "bworld:stone"); t.game.set_block(2, 100, 0, "bworld:stone");
t.game.tick(); t.game.tick();
assertEquals(t.rod()?.data, undefined); assertEquals(t.rod()?.data, undefined);
t.game.tick();
assertEquals(t.hooks().length, 0);
}); });
Deno.test("a cast rod shows its cast texture", async () => { Deno.test("a cast rod shows its cast texture", async () => {
+20 -1
View File
@@ -2,6 +2,7 @@
import { assert, assertEquals, assertStringIncludes } from "@std/assert"; import { assert, assertEquals, assertStringIncludes } from "@std/assert";
import { entity_model_from_geo, validate_entity } from "$/common/mod_data.ts"; import { entity_model_from_geo, validate_entity } from "$/common/mod_data.ts";
import { Mob } from "$/server/game/entity/mob.ts"; import { Mob } from "$/server/game/entity/mob.ts";
import { create_entity } from "$/server/game/entity/entity_types.ts";
import { test_game } from "./helpers.ts"; import { test_game } from "./helpers.ts";
Deno.test("a bedrock geo.json becomes an entity model with only what the engine uses", () => { Deno.test("a bedrock geo.json becomes an entity model with only what the engine uses", () => {
@@ -34,7 +35,7 @@ Deno.test("a bedrock geo.json becomes an entity model with only what the engine
assertEquals(entity_model_from_geo({ format_version: "1.12.0" }, "a:b").model, undefined); assertEquals(entity_model_from_geo({ format_version: "1.12.0" }, "a:b").model, undefined);
}); });
Deno.test("an entity needs a model, a texture and a size", () => { Deno.test("an entity needs a texture and a size", () => {
assertEquals(validate_entity({ id: "a:b", model: "a:b", texture: "a:b", width: 0.5, height: 1 }), []); assertEquals(validate_entity({ id: "a:b", model: "a:b", texture: "a:b", width: 0.5, height: 1 }), []);
assertEquals(validate_entity({ id: "a:b", model: "a:b", texture: "a:b", width: 0, height: 1, max_health: -1 }), [ assertEquals(validate_entity({ id: "a:b", model: "a:b", texture: "a:b", width: 0, height: 1, max_health: -1 }), [
"width must be a number of blocks above 0, at most 16", "width must be a number of blocks above 0, at most 16",
@@ -42,6 +43,24 @@ Deno.test("an entity needs a model, a texture and a size", () => {
]); ]);
}); });
Deno.test("an entity without a model is drawn as its texture, and a scripted one has no ai", () => {
assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "scripted", width: 0.25, height: 0.25 }), []);
assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "flying", width: 0.25, height: 0.25 }), [
'behavior must be "animal" or "scripted"',
]);
});
Deno.test("scripted entities stay put and aren't saved with the world", async () => {
const { game } = await test_game("mods");
const hook = create_entity(game.entities, "bworld:fishing_hook")!;
assert(!(hook instanceof Mob));
hook.set_position(0.5, 100, 0.5);
game.entities.add_entity(hook);
for (let i = 0; i < 20; i++) game.tick();
assertEquals([hook.x, hook.y, hook.z, hook.removed], [0.5, 100, 0.5, false]);
assertEquals(game.entities.save().filter((saved) => saved.id === "bworld:fishing_hook"), []);
});
Deno.test("/summon spawns a mod's entity where the player is", async () => { Deno.test("/summon spawns a mod's entity where the player is", async () => {
const { join, take, send, game } = await test_game("mods"); const { join, take, send, game } = await test_game("mods");
join(1, "alice"); join(1, "alice");