Predict interactions with blocks

This commit is contained in:
2026-10-10 14:21:27 -03:00
parent 7fe9c15b67
commit 79ff6f9ad5
15 changed files with 355 additions and 73 deletions
+41 -11
View File
@@ -4,7 +4,7 @@ import type { Client } from "./client.ts";
import type { BlockHitResult } from "./level/client_level.ts";
import type { Container } from "$/common/inventory.ts";
import { AIR_ID } from "$/common/protocol.ts";
import { box_overlaps_block, can_place, placement_target, waterlog_placement } from "$/common/utils.ts";
import { box_overlaps_block, can_place, liquid_block, placement_target, waterlog_placement } from "$/common/utils.ts";
import { block_rules, predict_neighbors } from "./mods.ts";
import { collision_shape_at } from "$/common/block_shapes.ts";
import type { EntityJson } from "$/common/mod_data.ts";
@@ -47,9 +47,11 @@ export class MultiPlayerGameMode {
if (this.destroy_progress >= this.destroy_time) {
// show it right away, the server decides drops and corrects us if it disagrees
this.client.level.break_block(hit.x, hit.y, hit.z);
predict_neighbors(hit.x, hit.y, hit.z);
this.client.connection.send({ type: "break_block", x: hit.x, y: hit.y, z: hit.z });
this.#predict((seq) => {
this.client.level.break_block(hit.x, hit.y, hit.z);
predict_neighbors(hit.x, hit.y, hit.z);
this.client.connection.send({ type: "break_block", x: hit.x, y: hit.y, z: hit.z, seq });
});
this.destroy_progress = 0;
this.destroy_time = 0;
}
@@ -63,26 +65,42 @@ export class MultiPlayerGameMode {
// right click on a block
use_item_on(hit: BlockHitResult) {
const level = this.client.level;
// the server checks that the block isn't going inside the player with where it is now, like this does
this.client.player.send_position_now();
this.client.connection.send({ type: "use_block", x: hit.x, y: hit.y, z: hit.z, face: hit.face, hit: hit.hit });
this.#predict((seq) => {
const { x, y, z, face } = hit;
this.client.connection.send({ type: "use_block", x, y, z, face, hit: hit.hit, seq });
this.#guess_use(hit);
});
}
// what using a block will do, shown right away
#guess_use(hit: BlockHitResult) {
const level = this.client.level;
// the shared rules' on_interact, like a trapdoor opening, shows right away. the server runs them too and corrects
// this if it disagrees. when they do something nothing is placed, like on the server
// an item aimed at liquids, like a bucket, uses the liquid in a waterlogged block instead, like on the server
const block_info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)!;
const held = this.held_item();
const value = level.get_block_value(hit.x, hit.y, hit.z);
const used = (held?.targets_liquids && liquid_block(value, block_info)) || block_info;
const interaction = { face: hit.face, hit: hit.hit };
if (block_rules.interact(used, hit.x, hit.y, hit.z, interaction, this.client.player.yaw)) return;
// guess that it places the held block, unless the block does something when used. the same rules as the server:
// into the clicked block when it's replaceable, and only where place_in and place_on allow
const block_info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)!;
const target = placement_target(hit.x, hit.y, hit.z, FACE_OFFSETS[hit.face], block_info);
const current = level.get_block(target.x, target.y, target.z);
const below = level.get_block(target.x, target.y - 1, target.z);
const below_id = EverythingRegistry.get_by_id<BlockRegistry>("blocks", below)?.id ?? AIR_ID;
const held = this.held_item();
// items with components might do something else on the server, like on_use
const place_id = held?.components ? undefined : held?.block_id;
const place_block = place_id !== undefined
? EverythingRegistry.get<BlockRegistry>("blocks", place_id)
: undefined;
// with the states the server will give it, see BlockRules.placement_value, and holding the liquid it goes into
const value = place_block &&
const place_value = place_block &&
waterlog_placement(
block_rules.placement_value(place_block, this.client.player.yaw, {
...target,
@@ -98,9 +116,9 @@ export class MultiPlayerGameMode {
current === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", current),
level.get_block_value(target.x, target.y, target.z),
below_id,
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, value!));
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, place_value!));
if (!block_info.interactive && place_id && placeable) {
level.add_block({ ...target, id: place_id }, value! >>> 16);
level.add_block({ ...target, id: place_id }, place_value! >>> 16);
predict_neighbors(target.x, target.y, target.z);
const slot = this.#held_slot();
slot.amount = slot.amount! - 1;
@@ -151,6 +169,18 @@ export class MultiPlayerGameMode {
return false;
}
// runs guess with the blocks it changes kept track of, like minecraft's startPrediction. what the server says about
// them waits until it answers the message guess sends with seq, see client/level/block_predictions.ts
#predict(guess: (seq: number) => void) {
const predictions = this.client.level.predictions;
const seq = predictions.start();
try {
guess(seq);
} finally {
predictions.end();
}
}
#held_slot() {
const inventories = this.client.player.inventories;
return inventories.inventory.get_slot(inventories.hotbar_selected);
+68
View File
@@ -0,0 +1,68 @@
// what this client changed ahead of the server, like minecraft's BlockStatePredictionHandler. each break_block and
// use_block gets a sequence number, and the server sends block_ack with it once it's handled it, after the set_blocks
// it caused. until then, what the server says about a block a guess changed is kept here instead of shown, so the
// answer to an older click can't undo a newer guess, like a trapdoor clicked twice flickering open again
// a block as the server sends it, see set_block
export interface ServerBlock {
x: number;
y: number;
z: number;
id: string;
state: number;
}
export class BlockPredictions {
// the last sequence number handed out
#seq = 0;
// whether a guess is running, see start
#predicting = false;
// the blocks guesses changed, by "x,y,z": the newest guess that changed it, and what the server last said is there
#server = new Map<string, { seq: number; block: ServerBlock }>();
// a guess is starting: the blocks it changes are kept track of until end. returns its sequence number, for the
// message that tells the server what the player did
start(): number {
this.#seq++;
this.#predicting = true;
return this.#seq;
}
end() {
this.#predicting = false;
}
// this client is about to change the block at x y z, which is what current gives now. the first guess to change it
// keeps that as what the server said, later ones only make it wait for their ack too
retain(x: number, y: number, z: number, current: () => ServerBlock) {
if (!this.#predicting) return;
const key = `${x},${y},${z}`;
const known = this.#server.get(key);
if (known) {
known.seq = this.#seq;
} else {
this.#server.set(key, { seq: this.#seq, block: current() });
}
}
// the server says x y z is id with state. returns true when a guess about it is waiting for its ack, then it's kept
// for then instead of shown
from_server(x: number, y: number, z: number, id: string, state: number): boolean {
const known = this.#server.get(`${x},${y},${z}`);
if (!known) return false;
known.block = { x, y, z, id, state };
return true;
}
// the server handled everything up to seq: the blocks only those guesses changed, as the server says they are now,
// to show instead of the guesses
ack(seq: number): ServerBlock[] {
const done: ServerBlock[] = [];
for (const [key, { seq: newest, block }] of this.#server) {
if (newest > seq) continue;
this.#server.delete(key);
done.push(block);
}
return done;
}
}
+32 -1
View File
@@ -29,6 +29,7 @@ import type { Entity } from "../entity/entity.ts";
import type { ModelJson } from "$/common/block_models.ts";
import { clip_shape, collision_shape_at, FULL_SHAPE, type Shape, shape_at } from "$/common/block_shapes.ts";
import type { ItemStack } from "$/common/inventory.ts";
import { BlockPredictions } from "./block_predictions.ts";
export interface Block {
id: string;
@@ -119,6 +120,8 @@ export class ClientLevel {
view_distance: number;
// the chunk the server says the player is in
center: { x: number; z: number } | undefined;
// what this client changed ahead of the server, see MultiPlayerGameMode.predict
predictions = new BlockPredictions();
workers: ChunkWorkerPool;
#blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
@@ -259,6 +262,7 @@ export class ClientLevel {
}
const [nid, info] = EverythingRegistry.get_full<BlockRegistry>("blocks", block.id)!;
this.#retain(block.x, block.y, block.z);
const lx = block.x - block_chunk_x * CHUNK_SIZE;
const lz = block.z - block_chunk_z * CHUNK_SIZE;
@@ -375,6 +379,8 @@ export class ClientLevel {
return;
}
this.#retain(x, y, z);
const lx = x - block_chunk_x * CHUNK_SIZE;
const lz = z - block_chunk_z * CHUNK_SIZE;
const ly = y;
@@ -451,8 +457,33 @@ export class ClientLevel {
return [x, y, z];
}
// set a block the server told us about. the server only sends them for chunks this client has
// set a block the server told us about. the server only sends them for chunks this client has. a block this
// client guessed waits for the server's ack instead, see BlockPredictions
apply_change(x: number, y: number, z: number, id: string, state = 0) {
if (this.predictions.from_server(x, y, z, id, state)) {
return;
}
this.#set_from_server(x, y, z, id, state);
}
// the server handled this client's guesses up to seq, what it said about the blocks they changed shows now
ack_predictions(seq: number) {
for (const { x, y, z, id, state } of this.predictions.ack(seq)) {
this.#set_from_server(x, y, z, id, state);
}
}
// while guessing, keeps what's at x y z before the guess changes it, as the server would say it
#retain(x: number, y: number, z: number) {
this.predictions.retain(x, y, z, () => {
const value = this.get_block_value(x, y, z);
const nid = value & ID_MASK;
const id = nid === AIR ? AIR_ID : this.#blocks[nid]?.id ?? AIR_ID;
return { x, y, z, id, state: value >>> 16 };
});
}
#set_from_server(x: number, y: number, z: number, id: string, state: number) {
const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
if (!chunk) {
return;
+3
View File
@@ -175,6 +175,9 @@ export class ClientPacketListener {
case "set_block":
level.apply_change(message.x, message.y, message.z, message.id, message.state);
break;
case "block_ack":
level.ack_predictions(message.seq);
break;
case "set_block_item":
level.set_block_item(
message.x,