Water phyisics

This commit is contained in:
2026-10-07 19:38:27 -03:00
parent d101fa2ef3
commit 78117f65c9
13 changed files with 338 additions and 13 deletions
+8
View File
@@ -144,6 +144,14 @@ export class LocalPlayer extends Player {
this.gravity = this.flying ? 0 : !this.#in_water ? LAND_GRAVITY : this.swimming ? 0 : WATER_GRAVITY;
this.drag = this.flying ? FLY_VERTICAL_DRAG : this.#in_water ? WATER_DRAG : LAND_DRAG;
if (this.swimming && this.#in_water) this.#steer(input);
if (!this.flying) {
physics.push_by_liquid(
this,
(x, y, z) => this.level.liquid_at(x, y, z),
(x, y, z) => this.level.collision_shape(x, y, z),
true,
);
}
this.#prev_eye_height = this.eye_height;
const eye_height = this.swimming
? PLAYER_SWIM_EYE_HEIGHT
+8 -1
View File
@@ -1,4 +1,4 @@
import { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
import { block_value, chunk_key, default_block_value, liquid_in_cell } from "$/common/utils.ts";
import { AIR_ID } from "$/common/protocol.ts";
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
import { DEFAULT_WATER_COLOR, foliage_color, grass_color, water_color } from "$/common/worldgen/biome_colors.ts";
@@ -333,6 +333,13 @@ export class ClientLevel {
.biome_colors[CHUNK_AREA * 2 + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
}
// the liquid there and how high it is, for liquids pushing things along. unloaded chunks have none
liquid_at(x: number, y: number, z: number) {
const value = this.get_block_value(x, y, z);
const nid = value & ID_MASK;
return nid === VOID || nid === AIR ? undefined : liquid_in_cell(value, this.#blocks[nid]);
}
// 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);
+147 -1
View File
@@ -244,6 +244,152 @@ export function eyes_in_water(
return is_liquid(Math.floor(body.x), Math.floor(body.y + eye_height), Math.floor(body.z));
}
// a liquid in a cell, for liquids pushing things along
export interface LiquidInCell {
// which liquid, its block's numeric id. a liquid's flow only goes by cells of the same one
id: number;
// its surface, 0 to 1 (see liquid_height), not counting more of it above
height: number;
}
// the liquid in a cell, undefined for none
export type LiquidAt = (x: number, y: number, z: number) => LiquidInCell | undefined;
const HORIZONTAL = [[1, 0], [-1, 0], [0, 1], [0, -1]];
// blocks per second added each tick, minecraft's water 0.014 blocks per tick per tick
const LIQUID_PUSH = 0.014 * 20;
// moving slower than this sideways, a push is at least LIQUID_MIN_PUSH, so things still drift off flat-ish water
const LIQUID_STILL_SPEED = 0.003 * 20;
const LIQUID_MIN_PUSH = 0.0045 * 20;
function blocks_motion(collision: boolean | Shape) {
return shape_of(collision).length > 0;
}
function normalized(x: number, y: number, z: number): [number, number, number] {
const length = Math.hypot(x, y, z);
return length < 1e-5 ? [0, 0, 0] : [x / length, y / length, z / length];
}
// which way the liquid at x y z flows, a length 1 vector or nothing, like minecraft's FlowingFluid.getFlow: towards
// lower cells of it beside it, and towards drops where it pours over an edge. falling down a wall it goes down too
export function liquid_flow(
x: number,
y: number,
z: number,
liquid_at: LiquidAt,
is_solid: BlockCollision,
): [number, number, number] {
const here = liquid_at(x, y, z);
if (!here) return [0, 0, 0];
let fx = 0;
let fz = 0;
for (const [dx, dz] of HORIZONTAL) {
const neighbor = liquid_at(x + dx, y, z + dz);
// another liquid doesn't change this one's flow
if (neighbor && neighbor.id !== here.id) continue;
let drop = 0;
if (neighbor) {
drop = here.height - neighbor.height;
} else if (!blocks_motion(is_solid(x + dx, y, z + dz))) {
// an edge it pours over, onto more of itself
const below = liquid_at(x + dx, y - 1, z + dz);
if (below?.id === here.id) drop = here.height - (below.height - 1);
}
fx += dx * drop;
fz += dz * drop;
}
[fx, , fz] = normalized(fx, 0, fz);
// falling: flowing, not a source, with more of it above. a deep pool of sources isn't
let fy = 0;
if (here.height < 1 && liquid_at(x, y + 1, z)?.id === here.id) {
const against_wall = HORIZONTAL.some(([dx, dz]) =>
blocks_motion(is_solid(x + dx, y, z + dz)) || blocks_motion(is_solid(x + dx, y + 1, z + dz))
);
if (against_wall) fy = -6;
}
return normalized(fx, fy, fz);
}
// liquid the body is in pushes it the way it flows, like minecraft's Entity.updateFluidHeightAndDoFluidPushing: the
// flow of every cell of it the box reaches, averaged, weaker where it's shallow. players get that average as it is,
// other things are pushed at full strength whichever way it points. changes the body's velocity
export function push_by_liquid(body: Body, liquid_at: LiquidAt, is_solid: BlockCollision, is_player: boolean) {
const half = body.width / 2 - 0.001;
const min_y = body.y + 0.001;
const max_y = body.y + body.height - 0.001;
let px = 0;
let py = 0;
let pz = 0;
let count = 0;
let depth = 0;
for (let x = Math.floor(body.x - half); x <= Math.floor(body.x + half); x++) {
for (let y = Math.floor(min_y); y <= Math.floor(max_y); y++) {
for (let z = Math.floor(body.z - half); z <= Math.floor(body.z + half); z++) {
const liquid = liquid_at(x, y, z);
if (!liquid) continue;
const surface = y + (liquid_at(x, y + 1, z)?.id === liquid.id ? 1 : liquid.height);
if (surface < min_y) continue;
depth = Math.max(depth, surface - min_y);
let [fx, fy, fz] = liquid_flow(x, y, z, liquid_at, is_solid);
// minecraft's, which goes by the deepest cell so far
if (depth < 0.4) {
fx *= depth;
fy *= depth;
fz *= depth;
}
px += fx;
py += fy;
pz += fz;
count++;
}
}
}
if (Math.hypot(px, py, pz) === 0) return;
[px, py, pz] = is_player ? [px / count, py / count, pz / count] : normalized(px, py, pz);
px *= LIQUID_PUSH;
py *= LIQUID_PUSH;
pz *= LIQUID_PUSH;
if (
Math.abs(body.vx) < LIQUID_STILL_SPEED && Math.abs(body.vz) < LIQUID_STILL_SPEED &&
Math.hypot(px, py, pz) < LIQUID_MIN_PUSH
) {
[px, py, pz] = normalized(px, py, pz).map((n) => n * LIQUID_MIN_PUSH);
}
body.vx += px;
body.vy += py;
body.vz += pz;
}
// how far the body's feet are under the surface of liquid it's in, 0 for none, like minecraft's getFluidHeight
export function liquid_depth(body: Body, liquid_at: LiquidAt): number {
const half = body.width / 2 - 0.001;
const min_y = body.y + 0.001;
let depth = 0;
for (let x = Math.floor(body.x - half); x <= Math.floor(body.x + half); x++) {
for (let y = Math.floor(min_y); y <= Math.floor(body.y + body.height - 0.001); y++) {
for (let z = Math.floor(body.z - half); z <= Math.floor(body.z + half); z++) {
const liquid = liquid_at(x, y, z);
if (!liquid) continue;
const surface = y + (liquid_at(x, y + 1, z)?.id === liquid.id ? 1 : liquid.height);
depth = Math.max(depth, surface - min_y);
}
}
}
return depth;
}
// what the engine calls through, so engine access mods can hook these like methods (module exports can't be
// reassigned). see docs/modding/misc/engine.md
export const physics = { move_body, back_off_from_edge, box_is_free, in_water, eyes_in_water };
export const physics = {
move_body,
back_off_from_edge,
box_is_free,
in_water,
eyes_in_water,
liquid_flow,
push_by_liquid,
liquid_depth,
};
+10 -1
View File
@@ -1,8 +1,9 @@
import { ID_MASK, STATE_SHIFT } from "./constants.ts";
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "./everything_registry.ts";
import { BlockRegistry, EverythingRegistry, ItemRegistry, liquid_height } from "./everything_registry.ts";
import { block_item_texture, cube_face_texture } from "./block_models.ts";
import { FULL_SHAPE, type Shape } from "./block_shapes.ts";
import type { ItemStack } from "./inventory.ts";
import type { LiquidInCell } from "./physics.ts";
import { list_matches } from "./tags.ts";
export function point_inside_rec(
@@ -185,3 +186,11 @@ export function box_overlaps_block(
export function chunk_key(x: number, z: number) {
return (x + 32768) * 65536 + (z + 32768);
}
// the liquid a block value is, for liquids pushing things (see push_by_liquid in physics.ts), or undefined for blocks
// that aren't liquids
export function liquid_in_cell(value: number, block: BlockRegistry | undefined): LiquidInCell | undefined {
if (!block?.liquid) return undefined;
const level = get_state_value(value, block, "level") ?? 0;
return { id: value & ID_MASK, height: liquid_height(level, block.liquid.range) };
}
+2
View File
@@ -130,6 +130,8 @@ shore.
- It gets a `level` [state](states.md) of its own, after any it lists: `0` is a source, a full block, and `1` up to
`range` as it flows away from one, each lower.
- `collision` defaults to `false` and `replaceable` to `true`. Entities swim in it and falling into it doesn't hurt.
- Where it flows, it pushes entities in it along, like Minecraft's water: towards lower levels of it beside them, over
edges where it pours down, and down where it falls beside a wall. Players aren't pushed while flying.
- It can't have a `model`, `variants`, `parts`, `shape`, `collision_shape` or `item_model`, since the engine draws it.
- `tint` works on the `still` and `flowing` textures.
+16 -1
View File
@@ -8,7 +8,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 { Shape } from "$/common/block_shapes.ts";
import { type Collisions, physics } from "$/common/physics.ts";
import { type Collisions, type LiquidInCell, physics } from "$/common/physics.ts";
import type { EntityData, EntityEvent, EntityInfo } from "$/common/protocol.ts";
import type { ServerPlayer } from "../player.ts";
@@ -67,6 +67,8 @@ export interface EntityLevel {
collision_shape(x: number, y: number, z: number): boolean | Shape;
// water, and other blocks you're in instead of on
is_liquid(x: number, y: number, z: number): boolean;
// the liquid there and how high it is, for liquids pushing things along
liquid_at(x: number, y: number, z: number): LiquidInCell | undefined;
get_block_info(x: number, y: number, z: number): BlockRegistry | undefined;
add_entity(entity: Entity): void;
get_entity(id: string): Entity | undefined;
@@ -229,6 +231,14 @@ export abstract class Entity {
this.fall_distance = 0;
this.fire = 0;
}
if (this.pushed_by_liquid) {
physics.push_by_liquid(
this,
(x, y, z) => this.level.liquid_at(x, y, z),
(x, y, z) => this.level.collision_shape(x, y, z),
false,
);
}
if (this.fire > 0) {
if (this.fire_immune) {
@@ -246,6 +256,11 @@ export abstract class Entity {
}
}
// flowing liquid pushes it along, like minecraft's isPushedByFluid
get pushed_by_liquid() {
return true;
}
update_in_water() {
this.in_water = physics.in_water(this, (x, y, z) => this.level.is_liquid(x, y, z));
}
+6
View File
@@ -4,6 +4,7 @@
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 { liquid_in_cell } from "$/common/utils.ts";
import type { ItemStack } from "$/common/inventory.ts";
import type { EntityEvent, EntityInfo, ServerMessage } from "$/common/protocol.ts";
import type { ServerPlayer } from "../player.ts";
@@ -101,6 +102,11 @@ export class EntityManager implements EntityLevel {
return this.#host.world.get_block_info(x, y, z);
}
liquid_at(x: number, y: number, z: number) {
const world = this.#host.world;
return liquid_in_cell(world.get_block_value(x, y, z), world.get_block_info(x, y, z));
}
nearest_player(x: number, y: number, z: number, max_distance: number): ServerPlayer | undefined {
let nearest: ServerPlayer | undefined;
let nearest_distance = max_distance;
+21 -1
View File
@@ -1,5 +1,7 @@
import { type ItemData, ItemStack } from "$/common/inventory.ts";
import type { EntityInfo } from "$/common/protocol.ts";
import { TICK_DELTA } from "$/common/constants.ts";
import { physics } from "$/common/physics.ts";
import { type Attacker, type DamageSource, Entity, finite, type SavedEntity } from "./entity.ts";
export const ITEM_ENTITY_TYPE = "bworld:item";
@@ -15,6 +17,12 @@ const GROUND_FRICTION = 0.6 * 0.98;
const MIN_SPEED = 0.01;
// how fast an item stuck inside a block floats out of it
const UNSTICK_SPEED = 2;
// deeper in water than this it floats instead of falling: speeding up 0.0005 blocks per tick each tick until it rises
// at 0.06 blocks per tick, slowing sideways a little, like minecraft's setUnderwaterMovement. it bobs at the surface
const FLOAT_DEPTH = 0.1;
const FLOAT_ACCELERATION = 0.0005 * 20;
const FLOAT_SPEED = 0.06 * 20;
const WATER_DRAG = 0.99;
// items this close (past their own size) merge into one stack
const MERGE_DISTANCE = 0.5;
const MAX_HEALTH = 5;
@@ -40,7 +48,8 @@ export class ItemEntity extends Entity {
override width = ITEM_SIZE;
override height = ITEM_SIZE;
override eye_height = ITEM_SIZE / 2;
override gravity = GRAVITY;
// it falls in tick() instead, see there
override gravity = 0;
// ticks until a player can pick it up
pickup_delay: number;
@@ -74,6 +83,17 @@ export class ItemEntity extends Entity {
this.vy = UNSTICK_SPEED;
}
// like minecraft's ItemEntity.tick, gravity goes on its speed before it moves, not along the way like
// move_body's. the floating numbers are made for that: an item bobbing up out of the water drops straight back
// in, instead of hanging above it a tick longer and falling twice as fast
if (physics.liquid_depth(this, (x, y, z) => level.liquid_at(x, y, z)) > FLOAT_DEPTH) {
this.vx *= WATER_DRAG;
this.vz *= WATER_DRAG;
if (this.vy < FLOAT_SPEED) this.vy += FLOAT_ACCELERATION;
} else if (!this.no_gravity) {
this.vy += GRAVITY * TICK_DELTA;
}
this.move();
const friction = this.on_ground ? GROUND_FRICTION : AIR_DRAG;
this.vx *= friction;
+5
View File
@@ -134,6 +134,11 @@ export class ServerPlayer extends LivingEntity {
// 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, liquids included, see LocalPlayer
override get pushed_by_liquid() {
return false;
}
override tick() {
this.base_tick();
this.attack_strength_ticker += 1;
+27 -8
View File
@@ -116,15 +116,34 @@ Deno.test("q throws one of an item the way the player looks, ctrl throws the who
assertEquals(game.item_entities().length, 2);
});
Deno.test("water has no collision, items sink through it to the floor", async () => {
Deno.test("items fall into water, float back up and bob at its surface", async () => {
const { game, join } = await test_game("mods");
join(1, "alice");
build_floor(game);
for (let y = 100; y <= 102; y++) {
game.set_block(6, y, 0, "bworld:water");
// a pool 3 deep in a stone basin, so the water stays still
for (let x = 3; x <= 9; x++) {
for (let z = -3; z <= 3; z++) {
for (let y = 99; y <= 103; y++) {
const inside = x >= 4 && x <= 8 && z >= -2 && z <= 2 && y >= 100;
game.set_block(x, y, z, inside ? (y <= 102 ? "bworld:water" : "bworld:air") : "bworld:stone");
}
}
}
const item = game.spawn_item(6.5, 104, 0.5, new ItemStack("bworld:dirt"));
for (let i = 0; i < 40; i++) game.tick();
assert(item.on_ground);
assertEquals(item.y, 100, "on the stone under the water");
const item = game.spawn_item(6.5, 104.5, 0.5, new ItemStack("bworld:dirt"));
let lowest = Infinity;
for (let i = 0; i < 40; i++) {
game.tick();
lowest = Math.min(lowest, item.y);
}
assert(lowest < 102, `it went in, down to ${lowest}`);
for (let i = 0; i < 400; i++) game.tick();
const heights: number[] = [];
for (let i = 0; i < 200; i++) {
game.tick();
heights.push(item.y);
}
// about a tenth of it out of the water at the top, never far under
assert(Math.max(...heights) > 102.85 && Math.max(...heights) < 103, `up to ${Math.max(...heights)}`);
assert(Math.min(...heights) > 102.4, `down to ${Math.min(...heights)}`);
assertEquals([item.x, item.z], [6.5, 0.5]);
});
+27
View File
@@ -4,6 +4,7 @@ import { type BlockRegistry, EverythingRegistry } from "$/common/everything_regi
import { get_state_value } from "$/common/utils.ts";
import { LIQUID_DEFAULTS } from "$/common/everything_registry.ts";
import { LiquidFlow } from "$/server/game/liquids.ts";
import { ItemStack } from "$/common/inventory.ts";
import { test_game } from "./helpers.ts";
type Game = Awaited<ReturnType<typeof test_game>>["game"];
@@ -152,3 +153,29 @@ Deno.test("water stops at chunks that aren't loaded instead of making them", ()
assert(!blocks.has("1,1,0"));
assert(asked.includes(1));
});
Deno.test("flowing water pushes things in it downstream, still water doesn't", async () => {
// entities only move near a player
const { game, join } = await test_game("mods");
join(1, "alice");
floor(game, 10);
game.set_block(0, Y, 0, "bworld:water");
ticks(game, 60);
// in the water flowing towards +x
const item = game.spawn_item(3.5, Y, 0.5, new ItemStack("bworld:stone"));
item.vx = item.vy = item.vz = 0;
ticks(game, 20);
assert(item.x > 4, `drifted to ${item.x}`);
assert(Math.abs(item.z - 0.5) < 0.01, `and stayed in its row, at z ${item.z}`);
// a pool of sources is still
const { game: pool, join: join_pool } = await test_game("mods");
join_pool(1, "alice");
floor(pool, 10);
for (let x = -2; x <= 2; x++) for (let z = -2; z <= 2; z++) pool.set_block(x, Y, z, "bworld:water");
const floating = pool.spawn_item(0.5, Y, 0.5, new ItemStack("bworld:stone"));
floating.vx = floating.vy = floating.vz = 0;
ticks(pool, 20);
assertEquals([floating.x, floating.z], [0.5, 0.5]);
});
+59
View File
@@ -0,0 +1,59 @@
// which way liquid flows and how it pushes what's in it, like minecraft's FlowingFluid.getFlow
import { assert, assertAlmostEquals, assertEquals } from "@std/assert";
import { type Body, liquid_flow, type LiquidInCell, push_by_liquid } from "$/common/physics.ts";
const WATER = 1;
// cells by "x,y,z", and solid blocks
function world(liquids: Record<string, number>, solid: string[] = []) {
const liquid_at = (x: number, y: number, z: number): LiquidInCell | undefined => {
const height = liquids[`${x},${y},${z}`];
return height === undefined ? undefined : { id: WATER, height };
};
const is_solid = (x: number, y: number, z: number) => solid.includes(`${x},${y},${z}`);
return { liquid_at, is_solid };
}
const rounded = (v: number[]) => v.map((n) => Math.round(n * 1000) / 1000 + 0);
Deno.test("liquid flows towards lower cells of it and over edges, not into walls or air beside it", () => {
// a source with lower water to +x
const stream = world({ "0,0,0": 1, "1,0,0": 0.8 });
assertEquals(rounded(liquid_flow(0, 0, 0, stream.liquid_at, stream.is_solid)), [1, 0, 0]);
// level, nothing
const pool = world({ "0,0,0": 1, "1,0,0": 1, "-1,0,0": 1 });
assertEquals(rounded(liquid_flow(0, 0, 0, pool.liquid_at, pool.is_solid)), [0, 0, 0]);
// air beside it with nothing below doesn't pull, air with more of it below does
assertEquals(rounded(liquid_flow(0, 0, 0, world({ "0,0,0": 1 }).liquid_at, () => false)), [0, 0, 0]);
const edge = world({ "0,0,0": 0.5, "0,-1,1": 1 });
assertEquals(rounded(liquid_flow(0, 0, 0, edge.liquid_at, edge.is_solid)), [0, 0, 1]);
// falling down beside a wall, down
const fall = world({ "0,0,0": 0.9, "0,1,0": 1 }, ["1,0,0"]);
assertEquals(rounded(liquid_flow(0, 0, 0, fall.liquid_at, fall.is_solid)), [0, -1, 0]);
// a source under more water beside a wall is still, like the bottom of a pool
const deep = world({ "0,0,0": 1, "0,1,0": 1 }, ["1,0,0"]);
assertEquals(rounded(liquid_flow(0, 0, 0, deep.liquid_at, deep.is_solid)), [0, 0, 0]);
});
Deno.test("a body in flowing liquid is pushed along it, a player only by the average", () => {
const stream = world({ "0,0,0": 1, "1,0,0": 0.8 });
const body = (): Body => ({ x: 0.5, y: 0, z: 0.5, vx: 0, vy: 0, vz: 0, width: 0.25, height: 0.25 });
const item = body();
push_by_liquid(item, stream.liquid_at, stream.is_solid, false);
assertAlmostEquals(item.vx, 0.28);
assertEquals([item.vy, item.vz], [0, 0]);
// half in a still cell, half in the flowing one
const wide: Body = { ...body(), x: 0, width: 0.5 };
const half = world({ "-1,0,0": 1, "0,0,0": 1, "1,0,0": 0.8 });
const player = { ...wide };
push_by_liquid(player, half.liquid_at, half.is_solid, true);
const other = { ...wide };
push_by_liquid(other, half.liquid_at, half.is_solid, false);
assert(player.vx > 0 && player.vx < other.vx, `${player.vx} < ${other.vx}`);
// out of the liquid, nothing
const dry = { ...body(), y: 3 };
push_by_liquid(dry, stream.liquid_at, stream.is_solid, false);
assertEquals([dry.vx, dry.vy, dry.vz], [0, 0, 0]);
});
+2
View File
@@ -14,6 +14,8 @@ function setup(ceiling = Infinity, world?: { solid: Blocks; water: Blocks }) {
level: {
collision_shape: world?.solid ?? ((_x: number, y: number) => y < 0 || y >= ceiling),
is_liquid: world?.water ?? (() => false),
// its water is all still sources
liquid_at: (x: number, y: number, z: number) => world?.water(x, y, z) ? { id: 1, height: 1 } : undefined,
},
screen: undefined,
options: new Options(),