// liquids: blocks with "liquid", drawn like luanti's with surfaces that slope down to where they flow import { assert, assertAlmostEquals, assertEquals } from "@std/assert"; import { type BlockRegistry, EverythingRegistry, is_liquid_block, liquid_height, liquid_textures, } from "$/common/everything_registry.ts"; import { block_from_json, block_to_json, type BlockJson, validate_block } from "$/common/mod_data.ts"; import { cube_face_texture } from "$/common/block_models.ts"; import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts"; import { get_state_value, set_state_value } from "$/common/utils.ts"; import { cell_index, corner_height, liquid_quads, type LiquidCell } from "$/client/workers/liquid_mesh.ts"; import { TERRAIN_VERTEX_BYTES } from "$/client/workers/chunk_messages.ts"; import { test_game } from "./helpers.ts"; const OIL: BlockJson = { id: "oily:oil", textures: { still: "oily:oil_still", flowing: "oily:oil_flow" }, render_layer: "translucent", liquid: { range: 4 }, }; Deno.test("a liquid gets a level state, no collision and can be placed into", () => { const { block } = block_from_json(OIL); assert(is_liquid_block(block)); assertEquals(block.liquid, { range: 4, ticks: 5, renewable: true }); assertEquals(block.states, [{ name: "level", bits: 3, default: 0 }]); assertEquals(block.has_collision, false); assertEquals(block.replaceable, true); // and goes back to the same json assertEquals(block_to_json(block, true), OIL); // its own states keep their bits, the level goes after them const { block: hot } = block_from_json({ ...OIL, states: [{ name: "hot", bits: 1, default: 0 }] }); assertEquals(hot.states!.map((s) => s.name), ["hot", "level"]); const value = set_state_value(set_state_value(5, hot, "level", 3)!, hot, "hot", 1)!; assertEquals(get_state_value(value, hot, "level"), 3); assertEquals(block_to_json(hot, true).states, [{ name: "hot", bits: 1, default: 0 }]); // a range of 7 is the default const water = block_from_json({ id: "a:water", textures: "a:water", liquid: {} }).block; assertEquals(water.liquid, { range: 7, ticks: 5, renewable: true }); assertEquals(block_to_json(water, true).liquid, {}); }); Deno.test("a liquid's still texture is its top and bottom, the flowing one its sides", () => { const { block } = block_from_json(OIL); assertEquals(liquid_textures(block.textures), { still: "oily:oil_still", flowing: "oily:oil_flow" }); assertEquals(cube_face_texture(block, "top"), "oily:oil_still"); assertEquals(cube_face_texture(block, "side"), "oily:oil_flow"); // one texture is both assertEquals(liquid_textures("a:water"), { still: "a:water", flowing: "a:water" }); assertEquals(liquid_textures({ still: "a:water" }), { still: "a:water", flowing: "a:water" }); }); Deno.test("check-mods catches liquids that can't work", () => { assertEquals(validate_block(OIL), []); const problems = (json: Record) => validate_block({ ...OIL, ...json }); assertEquals(problems({ liquid: { range: 8 } }), ["liquid.range must be a whole number from 1 to 7"]); assertEquals(problems({ liquid: true }), ["liquid must be { range, ticks, renewable }, or {}"]); assertEquals(problems({ liquid: { ticks: 0 } }), ["liquid.ticks must be a whole number of 1 or more"]); assertEquals(problems({ liquid: { speed: 2 } }), ["liquid.speed isn't a liquid property"]); assertEquals(problems({ textures: { top: "a:b" } }), [ "a liquid's textures must be a texture id or { still, flowing }", ]); assertEquals(problems({ model: "engine:cross" }), ["a liquid can't have model, the engine draws it"]); assertEquals(problems({ states: [{ name: "level", bits: 2, default: 0 }] }), [ 'a liquid gets a "level" state of its own', ]); }); Deno.test("a liquid's surface is full at a source and lower each block it flows", () => { assertEquals(liquid_height(0, 7), 1); assertAlmostEquals(liquid_height(1, 7), 6.5 / 7); assertAlmostEquals(liquid_height(7, 7), 0.5 / 7); // past its range it's as low as it goes assertEquals(liquid_height(5, 4), liquid_height(4, 4)); }); // the 3x3 cells around a liquid, all air unless set function cells(set: Record> = {}) { const list: LiquidCell[] = Array.from({ length: 9 }, () => ({ same: false, height: 0, air: true, solid: false, top_same: false, })); for (const [key, cell] of Object.entries(set)) { const [dx, dz] = key.split(",").map(Number); Object.assign(list[cell_index(dx, dz)], { air: false }, cell); } return list; } const liquid = (height: number): Partial => ({ same: true, height }); const OPEN = { same: false, solid: false }; const SOLID = { same: false, solid: true }; // the highest and lowest y of each quad, by face function extents(quads: ReturnType) { return quads.map((q) => { const ys = [q.positions[1], q.positions[4], q.positions[7], q.positions[10]]; return { face: q.face, min: Math.min(...ys), max: Math.max(...ys) }; }); } Deno.test("a lone source is a full block, on the ground it has no bottom", () => { const quads = liquid_quads(cells({ "0,0": liquid(1) }), OPEN, SOLID); assertEquals(quads.map((q) => q.face).sort(), [0, 2, 3, 4, 5]); for (const { min, max, face } of extents(quads)) { if (face === 0) assertEquals([min, max], [1, 1]); else assertEquals([min, max], [0, 1]); } }); Deno.test("the middle of a lake is only its surface", () => { const lake: Record> = {}; for (let dx = -1; dx <= 1; dx++) for (let dz = -1; dz <= 1; dz++) lake[`${dx},${dz}`] = liquid(1); assertEquals(liquid_quads(cells(lake), OPEN, SOLID).map((q) => q.face), [0]); // deeper down, nothing at all assertEquals(liquid_quads(cells(lake), { same: true, solid: false }, { same: true, solid: false }), []); // a full surface right under a solid block can't be seen assertEquals(liquid_quads(cells(lake), SOLID, SOLID), []); }); Deno.test("flowing liquid slopes down from the source beside it, and thins out to a film at the shore", () => { const flowing = liquid_height(1, 7); // a source to the -x side const set = cells({ "0,0": liquid(flowing), "-1,0": liquid(1) }); assertEquals(corner_height(set, 0, 0), 1); assertEquals(corner_height(set, 0, 1), 1); // the +x corners have it and air around them assertAlmostEquals(corner_height(set, 1, 0), 0.02); const quads = liquid_quads(set, OPEN, SOLID); // no side facing the source assert(!quads.some((q) => q.face === 4)); const top = extents(quads).find((q) => q.face === 0)!; assertEquals(top.max, 1); assertAlmostEquals(top.min, 0.02); // between two flowing cells, the average const two = cells({ "0,0": liquid(0.5), "1,0": liquid(0.3), "1,1": liquid(0.1), "0,1": { solid: true } }); assertAlmostEquals(corner_height(two, 1, 1), 0.3); }); Deno.test("a lower neighbor's surface rises to meet a column of liquid, so there's no gap", () => { // liquid with more of itself above: every corner is full, so the side toward the lower one has no height const column = cells({ "0,0": { ...liquid(1), top_same: true }, "0,1": liquid(0.3) }); const quads = liquid_quads(column, { same: true, solid: false }, SOLID); assert(!quads.some((q) => q.face === 2 || q.face === 0)); // the lower one, beside the column at -z: its top goes up to the top of the cell there const low = cells({ "0,0": liquid(0.3), "0,-1": { ...liquid(1), top_same: true } }); const top = liquid_quads(low, OPEN, SOLID).find((q) => q.face === 0)!; const ys_at_z = (z: number) => [0, 1, 2, 3].filter((k) => top.positions[k * 3 + 2] === z).map((k) => top.positions[k * 3 + 1]); assertEquals(ys_at_z(0), [1, 1]); }); // the translucent quads of the middle chunk with these blocks in it, as the chunk worker meshes them. blocks are // [x, y, z, id, level] in the middle chunk, x can be -1 for the chunk to its -x side async function mesh(blocks: [number, number, number, string, number?][]) { await test_game("mods"); const registry = EverythingRegistry.get_registry("blocks"); const ids: Record = {}; registry.forEach((b, nid) => ids[b.id] = nid); const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); worker.postMessage({ type: "init", // with the registry's gaps, like the client sends it blocks_registry: registry.map((block) => JSON.parse(JSON.stringify(block))), models: {}, textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } }, image: { width: 1024, height: 1024 }, }); const chunks = Array.from({ length: 9 }, () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT)); for (const [x, y, z, id, level] of blocks) { const chunk = x < 0 ? chunks[3] : chunks[4]; chunk[y * CHUNK_AREA + z * CHUNK_SIZE + ((x + CHUNK_SIZE) % CHUNK_SIZE)] = ids[id] | ((level ?? 0) << 16); } // deno-lint-ignore no-explicit-any const meshed = await new Promise((resolve) => { worker.onmessage = (e) => resolve(e.data); worker.postMessage({ type: "mesh", chunk_x: 0, chunk_z: 0, version: 1, chunks, biome_colors: chunks.map(() => null), camera: [0, 0, 0], }); }); worker.terminate(); const f32 = new Float32Array(meshed.translucent.vertices.buffer); const quads: number[][][] = []; for (let quad = 0; quad < meshed.translucent.quad_count; quad++) { const byte = quad * 4 * TERRAIN_VERTEX_BYTES; quads.push([0, 1, 2, 3].map((k) => [0, 1, 2].map((i) => f32[(byte + k * TERRAIN_VERTEX_BYTES) / 4 + i]))); } return quads; } // the y of a quad's normal from its corners' winding, counterclockwise is the front function facing_y(corners: number[][]) { const [a, b, c] = corners; return (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2]); } Deno.test("the chunk worker draws water sloping down from a source, across a chunk's edge too", async () => { // three rows of it: a source at x -1, in the chunk to the -x side, then flowing water at x 0 and 1, on stone const blocks: [number, number, number, string, number?][] = []; for (let z = 7; z <= 9; z++) { blocks.push([-1, 10, z, "bworld:water", 0], [0, 10, z, "bworld:water", 1], [1, 10, z, "bworld:water", 2]); blocks.push([0, 9, z, "bworld:stone"], [1, 9, z, "bworld:stone"]); } const quads = await mesh(blocks); // the tops of the middle chunk's water, by the x of their corners. each is drawn facing up and, to be seen from // under water, facing down const tops = quads.filter((corners) => corners.every(([, y]) => y > 10)); assertEquals(tops.length, 12); assertEquals(tops.filter((corners) => facing_y(corners) > 0).length, 6); assertEquals(tops.filter((corners) => facing_y(corners) < 0).length, 6); const height_at = (x: number) => Math.max(...tops.flat().filter(([cx]) => Math.abs(cx - x) < 1e-6).map(([, y]) => y - 10)); // full where it meets the source, then down assertEquals(height_at(0), 1); // the average of the levels around it, between the rows assertAlmostEquals(height_at(1), (liquid_height(1, 7) + liquid_height(2, 7)) / 2, 1e-6); assertAlmostEquals(height_at(2), 0.02, 1e-6); // no sides between cells of it, only on the outside assert(!quads.some((corners) => corners.every(([x]) => x === 1))); assert(quads.some((corners) => corners.every(([x]) => x === 2))); }); Deno.test("with a flowing texture of its own, a sloping top flows downhill and the sides show part of it", () => { // level water stays still, whatever the flowing texture const lake: Record> = {}; for (let dx = -1; dx <= 1; dx++) for (let dz = -1; dz <= 1; dz++) lake[`${dx},${dz}`] = liquid(1); assert(liquid_quads(cells(lake), OPEN, SOLID, 0.5).every((q) => q.still)); // a source to the -x side, so it flows towards +x const set = cells({ "0,0": liquid(liquid_height(1, 7)), "-1,0": liquid(1) }); const quads = liquid_quads(set, OPEN, SOLID, 0.5); const top = quads.find((q) => q.face === 0)!; assertEquals(top.still, false); // the middle half of the texture, turned so v (down the texture) runs with x, downstream const uv_at = (x: number, z: number) => { const k = [0, 1, 2, 3].find((k) => top.positions[k * 3] === x && top.positions[k * 3 + 2] === z)!; return top.uvs.slice(k * 2, k * 2 + 2).map((n) => Math.round(n * 1000) / 1000); }; assertEquals(uv_at(0, 0), [12, 4]); assertEquals(uv_at(1, 0), [12, 12]); assertEquals(uv_at(0, 1), [4, 4]); for (const n of top.uvs) assert(n >= 4 - 1e-9 && n <= 12 + 1e-9); // the sides show the flowing texture's top left half for (const side of quads.filter((q) => q.face !== 0)) { assertEquals(side.still, false); for (const n of side.uvs) assert(n >= 0 && n <= 8); } // with only one texture, the top stays still and the sides show all of it const plain = liquid_quads(set, OPEN, SOLID); assert(plain.find((q) => q.face === 0)!.still); assert(plain.some((q) => q.face !== 0 && q.uvs.some((n) => n > 8))); }); Deno.test("a waterloggable block gets a waterlogged state after its own, and can't be a liquid", () => { const json: BlockJson = { id: "a:post", textures: "a:post", states: [{ name: "lit", bits: 1, default: 0 }], waterloggable: "a:water", }; const { block } = block_from_json(json); assertEquals(block.states!.map((s) => s.name), ["lit", "waterlogged"]); assertEquals(block_to_json(block, true), json); assertEquals(validate_block(json), []); assert(validate_block({ ...json, waterloggable: "water" }).some((p) => p.includes("waterloggable"))); assert(validate_block({ id: "a:w", textures: "a:w", liquid: {}, waterloggable: "a:water" }).length > 0); assert( validate_block({ ...json, states: [{ name: "waterlogged", bits: 1, default: 0 }] }) .some((p) => p.includes("of its own")), ); // only ever placed waterlogged, which needs something to be waterlogged with const only: BlockJson = { ...json, waterlogged_only: true }; assertEquals(block_to_json(block_from_json(only).block, true), only); assertEquals(validate_block(only), []); assert(validate_block({ id: "a:post", textures: "a:post", waterlogged_only: true }).length > 0); }); Deno.test("the chunk worker draws the water in a waterlogged fence, joined to the water beside it", async () => { await test_game("mods"); const fence = EverythingRegistry.get("blocks", "bworld:oak_fence")!; const waterlogged = set_state_value(0, fence, "waterlogged", 1)! >>> 16; // a fence in water at x 1 with water at x 2, and a dry fence at x 5 const quads = await mesh([ [1, 10, 8, "bworld:oak_fence", waterlogged], [2, 10, 8, "bworld:water", 0], [5, 10, 8, "bworld:oak_fence", 0], ]); const water_in = (x: number) => quads.filter((corners) => corners.every(([cx]) => cx >= x - 1e-6 && cx <= x + 1 + 1e-6)); // a full top, facing up and down, and no side between it and the water next to it const tops = water_in(1).filter((corners) => corners.every(([, y]) => y === 11)); assertEquals(tops.length, 2); assert(!water_in(1).some((corners) => corners.every(([cx]) => Math.abs(cx - 2) < 1e-6))); assertEquals(water_in(5).length, 0); });