Cache ticking blocks

This commit is contained in:
2026-10-12 19:37:04 -03:00
parent c5ffc23bcd
commit 02cbeda0a0
9 changed files with 195 additions and 56 deletions
+37
View File
@@ -23,6 +23,19 @@ export function setup(ctx: ServerContext) {
ctx.components.register_block("testmod:lazy", {
on_tick() { log("lazy_tick"); },
});
// a machine that works for 5 ticks at a time, then waits to be woken
ctx.components.register_block("testmod:sleeper", {
on_create(block) { block.data = { ticks: 0 }; },
on_tick(block) {
block.data.ticks += 1;
log("sleeper_tick");
if (block.data.ticks % 5 === 0) block.set_ticking(false);
},
on_interact(block) {
ctx.world.set_block_ticking(block.x, block.y, block.z, true);
return true;
},
});
ctx.components.register_block("testmod:broken", {
on_create(block) { block.data = {}; },
on_tick() { throw new Error("broken on purpose"); },
@@ -133,6 +146,10 @@ function test_mods() {
block("testmod:ticker", { components: { "testmod:ticker": {} } }),
);
Deno.writeTextFileSync(`${mod}/blocks/lazy.json`, block("testmod:lazy", { components: { "testmod:lazy": {} } }));
Deno.writeTextFileSync(
`${mod}/blocks/sleeper.json`,
block("testmod:sleeper", { interactive: true, components: { "testmod:sleeper": {} } }),
);
Deno.writeTextFileSync(
`${mod}/blocks/broken.json`,
block("testmod:broken", { components: { "testmod:broken": {} } }),
@@ -195,6 +212,26 @@ Deno.test("components tick 20 times a second and on_second once, only with block
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a block can turn its ticking off and be woken, and both last through saving", async () => {
const { game, log, dir } = await setup();
game.set_block(2, 100, 2, "testmod:ticker");
game.set_block(3, 100, 2, "testmod:sleeper");
for (let i = 0; i < 20; i++) game.tick();
assertEquals(log()["sleeper_tick"]?.length, 5);
const saved = game.save();
Deno.removeSync(dir, { recursive: true });
const again = await setup(saved);
for (let i = 0; i < 20; i++) again.game.tick();
assertEquals(again.log()["tick_2"]?.length, 40, "blocks loaded with the world tick");
assertEquals(again.log()["sleeper_tick"]?.length, 5, "and one that turned it off stays off");
again.send(1, { type: "use_block", x: 3, y: 100, z: 2, face: "top" });
for (let i = 0; i < 20; i++) again.game.tick();
assertEquals(again.log()["sleeper_tick"]?.length, 10);
Deno.removeSync(again.dir, { recursive: true });
});
Deno.test("timers and the tick event run on the game loop's ticks", async () => {
const { game, log, dir } = await setup();
for (let i = 0; i < 50; i++) game.tick();