Scheduled ticks !!

This commit is contained in:
2026-10-20 13:50:35 -03:00
parent 77cd327f94
commit 1c2dcd0dbc
7 changed files with 444 additions and 1 deletions
+58
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {
AIR,
BREAK_STAGES,
CHUNK_HEIGHT,
CHUNK_SIZE,
@@ -68,6 +69,7 @@ import type { Menu } from "./menu.ts";
import { MACHINE_CONN, SavedPlayer, ServerPlayer } from "./player.ts";
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
import { ServerWorld, SPAWN_AREA_CHUNKS, Tile } from "./world.ts";
import { ScheduledTicks } from "./scheduled_ticks.ts";
import type { WorldSave, WorldSource } from "./saves.ts";
import {
BLOCK_DROP_PICKUP_DELAY,
@@ -137,6 +139,9 @@ export interface SavedLevel {
// world time in ticks
time: number;
tiles: Tile[];
// the ticks blocks scheduled that haven't run, in the order they'll run, see ServerWorld.schedule_tick. ticks_left
// is 0 or less for ones waiting for a player to come near
scheduled_ticks: [x: number, y: number, z: number, id: string, ticks_left: number, priority: number][];
// every ctx.containers container, by id
containers: Record<string, (ItemData | null)[]>;
players: Record<string, SavedPlayer>;
@@ -164,6 +169,8 @@ export class GameServer {
#next_chunk_player = 0;
#saved_players: Record<string, SavedPlayer> = {};
#tick = 0;
// see ServerWorld.schedule_tick, due on game ticks
#scheduled = new ScheduledTicks();
// the last morning new day handlers ran for
#day = 0;
#mods: GameMods;
@@ -260,6 +267,11 @@ export class GameServer {
this.containers.set(id, container);
}
for (const tile of saved?.tiles ?? []) this.world.add_tile({ ...tile });
for (const [x, y, z, id, ticks_left, priority] of saved?.scheduled_ticks ?? []) {
// unless its mod is gone
const nid = this.world.block_ids[id];
if (nid !== undefined) this.#scheduled.add(x, y, z, nid, ticks_left, priority);
}
this.entities.load(saved?.version === 4 ? upgrade_v4_entities(saved.entities) : saved?.entities ?? []);
this.#saved_players = saved?.players ?? {};
// a new world is saved straight away
@@ -344,6 +356,8 @@ export class GameServer {
this.#broadcast({ type: "time", time: this.world.time });
}
this.#run_scheduled_ticks();
// the tiles near players that tick, picked before any runs so one that a handler adds waits for the next tick
const ticking: Tile[] = [];
if (this.world.has_ticking_tiles) {
@@ -399,6 +413,42 @@ export class GameServer {
}
}
// runs the block's components' on_scheduled_tick in delay ticks, see ServerWorld.schedule_tick
schedule_tick(x: number, y: number, z: number, delay: number, priority: number) {
const nid = this.world.get_block_nid(x, y, z);
if (nid === AIR) return;
this.#scheduled.add(x, y, z, nid, this.#tick + delay, priority);
this.world.dirty = true;
}
has_scheduled_tick(x: number, y: number, z: number) {
return this.#scheduled.has(x, y, z, this.world.get_block_nid(x, y, z));
}
// the scheduled ticks due near players, all taken before any runs, so one a handler schedules waits for its tick
#run_scheduled_ticks() {
const due = this.#scheduled.take_due(
this.#tick,
(chunk_x, chunk_z) => this.#near_any_player(chunk_x * CHUNK_SIZE, chunk_z * CHUNK_SIZE),
);
for (const { x, y, z, nid } of due) {
// another kind of block took its place
if (this.world.get_block_nid(x, y, z) !== nid) continue;
const id = this.world.get_block_id(x, y, z);
const components = this.mods.components_with(id, "on_scheduled_tick");
if (components.length === 0) continue;
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(
mod,
`${component_id} on_scheduled_tick`,
() => component.on_scheduled_tick!(block, params),
);
}
}
if (due.length > 0) this.world.dirty = true;
}
// level.json and the chunks generated or changed since the last save
save(): Required<WorldSave> {
for (const player of this.#players.values()) {
@@ -409,6 +459,14 @@ export class GameServer {
seed: this.world.seed,
time: this.world.time,
tiles: [...this.world.tiles.values()].map((tile) => ({ ...tile })),
scheduled_ticks: this.#scheduled.all().map((tick) => [
tick.x,
tick.y,
tick.z,
EverythingRegistry.get_by_id<BlockRegistry>("blocks", tick.nid)!.id,
tick.due - this.#tick,
tick.priority,
]),
containers: Object.fromEntries(
[...this.containers].map(([id, container]) => [id, container.to_data()]),
),
+11
View File
@@ -58,6 +58,7 @@ import {
} from "$/common/commands.ts";
import { AIR_ID } from "$/common/protocol.ts";
import type { GameServer } from "./game_server.ts";
import { MAX_PRIORITY, MIN_PRIORITY } from "./scheduled_ticks.ts";
import type { ServerPlayer } from "./player.ts";
import { Menu, type MenuSlot } from "./menu.ts";
import { damage_source, type Entity } from "./entity/entity.ts";
@@ -746,6 +747,16 @@ export class ModRuntime {
},
neighbor_changed: (x, y, z, from) =>
this.rules.neighbor_changed(x, y, z, { x: from.x, y: from.y, z: from.z }),
schedule_tick: (x, y, z, delay, priority = 0) => {
if (!Number.isInteger(delay) || delay < 1) {
throw new Error(`a tick is scheduled at least 1 tick ahead, in whole ticks, not ${delay}`);
}
if (!Number.isInteger(priority) || priority < MIN_PRIORITY || priority > MAX_PRIORITY) {
throw new Error(`a tick's priority is ${MIN_PRIORITY} to ${MAX_PRIORITY}, not ${priority}`);
}
game().schedule_tick(x, y, z, delay, priority);
},
has_scheduled_tick: (x, y, z) => game().has_scheduled_tick(x, y, z),
is_face_sturdy: (x, y, z, face) => covers_face(game().world.collision_shape(x, y, z), face),
get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never,
get_block_ref: (x, y, z) => {
+143
View File
@@ -0,0 +1,143 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// ticks blocks asked for some ticks ahead, see ServerWorld.schedule_tick. kept by chunk and grouped by when they're due,
// so a tick costs nothing until it's due, and a chunk with none due is passed over with one comparison
import { CHUNK_SIZE } from "$/common/constants.ts";
import { chunk_key } from "$/common/utils.ts";
import { index_in_chunk } from "./world.ts";
// the most that run in one tick. the rest run first the next
export const MAX_SCHEDULED_TICKS = 65536;
// priorities go from -8 to 7, so with 8 added one fits in 4 bits under the due tick
export const MIN_PRIORITY = -8;
export const MAX_PRIORITY = 7;
export interface ScheduledTick {
readonly x: number;
readonly y: number;
readonly z: number;
// the numeric id of the block it was scheduled for. it's dropped if another kind of block is there when it's due
readonly nid: number;
readonly due: number;
readonly priority: number;
// due * 16 + priority + 8: smaller runs first
readonly key: number;
// counts up with every tick scheduled, so of ticks with the same key the first scheduled runs first
readonly order: number;
// nid * 65536 + index in chunk, which is one per block, see ChunkTicks.waiting
readonly block: number;
}
class ChunkTicks {
// by key, each in the order they were scheduled
groups = new Map<number, ScheduledTick[]>();
// the keys of groups, smallest first. only a few, since delays are short
keys: number[] = [];
// ScheduledTick.block of every tick waiting here, so the same block can't wait twice
waiting = new Set<number>();
constructor(readonly x: number, readonly z: number) {}
add(tick: ScheduledTick) {
this.waiting.add(tick.block);
const group = this.groups.get(tick.key);
if (group) {
group.push(tick);
return;
}
this.groups.set(tick.key, [tick]);
// usually later than every other
let i = this.keys.length;
while (i > 0 && this.keys[i - 1] > tick.key) i--;
this.keys.splice(i, 0, tick.key);
}
// takes out every tick that runs before or with the tick with this key and order
remove_through(key: number, order: number) {
while (this.keys.length > 0 && this.keys[0] <= key) {
const group = this.groups.get(this.keys[0])!;
let taken = group.length;
if (this.keys[0] === key) {
taken = 0;
while (taken < group.length && group[taken].order <= order) taken++;
}
for (let i = 0; i < taken; i++) this.waiting.delete(group[i].block);
if (taken < group.length) {
group.splice(0, taken);
return;
}
this.groups.delete(this.keys[0]);
this.keys.shift();
}
}
}
export class ScheduledTicks {
#chunks = new Map<number, ChunkTicks>();
#order = 0;
// adds a tick for the block nid at x y z on tick due, unless one already waits for it there
add(x: number, y: number, z: number, nid: number, due: number, priority: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const key = chunk_key(chunk_x, chunk_z);
let chunk = this.#chunks.get(key);
const block = block_key(x, y, z, chunk_x, chunk_z, nid);
if (chunk?.waiting.has(block)) return;
if (!chunk) this.#chunks.set(key, chunk = new ChunkTicks(chunk_x, chunk_z));
const order = this.#order++;
chunk.add({ x, y, z, nid, due, priority, key: due * 16 + priority + 8, order, block });
}
has(x: number, y: number, z: number, nid: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const chunk = this.#chunks.get(chunk_key(chunk_x, chunk_z));
return chunk?.waiting.has(block_key(x, y, z, chunk_x, chunk_z, nid)) ?? false;
}
// takes the ticks due by now in the chunks near says are near players, at most max, in the order they run: by
// due tick, then priority, then the order they were scheduled in. what's left over stays, and runs first next time
take_due(now: number, near: (chunk_x: number, chunk_z: number) => boolean, max = MAX_SCHEDULED_TICKS) {
const due_before = (now + 1) * 16;
const chunks: ChunkTicks[] = [];
const due: ScheduledTick[] = [];
for (const chunk of this.#chunks.values()) {
if (chunk.keys[0] >= due_before || !near(chunk.x, chunk.z)) continue;
chunks.push(chunk);
for (const key of chunk.keys) {
if (key >= due_before) break;
for (const tick of chunk.groups.get(key)!) due.push(tick);
}
}
if (due.length === 0) return due;
due.sort(run_order);
if (due.length > max) due.length = max;
const last = due[due.length - 1];
for (const chunk of chunks) {
chunk.remove_through(last.key, last.order);
if (chunk.waiting.size === 0) this.#chunks.delete(chunk_key(chunk.x, chunk.z));
}
return due;
}
// every tick waiting, in the order they'd run, for saving
all(): ScheduledTick[] {
const all: ScheduledTick[] = [];
for (const chunk of this.#chunks.values()) {
for (const group of chunk.groups.values()) all.push(...group);
}
return all.sort(run_order);
}
}
function run_order(a: ScheduledTick, b: ScheduledTick) {
return a.key - b.key || a.order - b.order;
}
// a block's place in its chunk, under 65536 since chunks are 256 tall, with its numeric id above
function block_key(x: number, y: number, z: number, chunk_x: number, chunk_z: number, nid: number) {
return nid * 65536 + index_in_chunk(x, y, z, chunk_x, chunk_z);
}
+1 -1
View File
@@ -733,7 +733,7 @@ function fallback_caller(stack: string) {
return match ? `${match[1] ?? "?"} ${match[2]}` : outside;
}
function index_in_chunk(x: number, y: number, z: number, chunk_x: number, chunk_z: number) {
export function index_in_chunk(x: number, y: number, z: number, chunk_x: number, chunk_z: number) {
return y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE);
}