From 233c518def3d490b0d3bc9a0e3ff3aaaac94aa98 Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 25 Oct 2026 18:46:48 -0300 Subject: [PATCH] Fluid and item visuals --- CREATE.md | 24 ++- MODS.md | 3 +- client/renderer/core.ts | 40 ++-- client/rendering/game_renderer.ts | 2 +- client/rendering/item_renderer.ts | 53 ++++- client/rendering/level_renderer.ts | 4 +- client/rendering/visuals.ts | 305 +++++++++++++++++++++++------ common/mod_api/client.ts | 14 +- common/mod_check.ts | 1 + common/mod_data.ts | 2 + docs/modding/blocks/visuals.md | 55 +++++- docs/modding/resources/fluids.md | 18 +- mods/bworld/fluids/juice.json | 3 +- tests/fluid_registry_test.ts | 6 +- tests/visuals_test.ts | 141 +++++++++++-- 15 files changed, 549 insertions(+), 122 deletions(-) diff --git a/CREATE.md b/CREATE.md index 35b1e28..bb79032 100644 --- a/CREATE.md +++ b/CREATE.md @@ -4,10 +4,10 @@ A plan for porting all of Create to bworld as a mod, `mods/create`: its kinetics redstone, contraptions, trains, equipment, decoration and schematics. It aims to do this with as little hand work as possible, and to stay fast on both the server and the client when a world has thousands of moving parts. -Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed` and `rotating`), R4, R5, -R8, S0, S4, S7, S12, stonecutting from S9, the start of P1's kinetics (shafts and cogwheels turned by a hand crank), -Create's pressing recipes, and the mechanical press pressing items on the ground. Facts about Create come from reading -`ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source. +Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed`, `rotating`, `fluid` and +items), R4, R5, R8, S0, S4, S7, S12, stonecutting from S9, the start of P1's kinetics (shafts and cogwheels turned by a +hand crank), Create's pressing recipes, and the mechanical press pressing items on the ground. Facts about Create come +from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source. ## Sources @@ -248,9 +248,9 @@ draws `rotating` and `transformed` instances of its block's model or of any mode variant. A visual that has to move on the CPU (a crank easing in, a press head) gets `on_frame`, like `DynamicVisual`. Visuals are kept per chunk, and only the ones in chunks in view get `on_frame`. -**R3. Instanced drawing** (P1, `transformed` and `rotating` built). A WebGPU pipeline that draws one model many times -from an instance buffer (`vs_instance` in `client/renderer/core.ts`, cut out like cutout terrain). The instance types, -matching Create's: +**R3. Instanced drawing** (P1, `transformed`, `rotating`, `fluid` and items built). A WebGPU pipeline that draws one +model many times from an instance buffer (`vs_instance` in `client/renderer/core.ts`, cut out like cutout terrain). The +instance types, matching Create's: | Type | Per instance | Shader | | ------------- | ------------------------------------------ | ----------------------------------------------------------------------- | @@ -269,8 +269,14 @@ instances are grouped by model alone. Each group keeps its instances on the CPU range from the first changed instance to the last once a frame. A deleted instance's place is taken by the last one, so a group's instances are always its first ones. Light comes with each chunk mesh. Every instance is drawn each frame, with no culling by chunk, since a draw call per model is cheaper than one per model per chunk until there are far more -instances than P1 has. Faces are shaded on the GPU by the way they face after turning. `scrolling` comes with belts (P4) -and `fluid` with tanks (P5). +instances than P1 has. Faces are shaded on the GPU by the way they face after turning. `scrolling` comes with belts +(P4). + +`fluid` is built apart from the table: each box is a model of its own, built on the CPU when its box is set, cut into a +piece per block it crosses so the texture is never stretched, like Create's `renderTiledFace`, and tinted in its fluid's +color. It's one draw call per box, drawn blended after the other instances and back to front. Items are transformed +instances too, of a model built once from what an item draws, one per way an item looks (its id, texture and layer +colors), so a belt of one item is one draw call. **R4. Models without blocks** (P1). Any model in `models/` can be loaded by id for visuals, baked once into a GPU buffer, and turned for whatever axis it's used on. Built: each model is baked the first time a visual uses it and diff --git a/MODS.md b/MODS.md index d73c103..72b8543 100644 --- a/MODS.md +++ b/MODS.md @@ -38,7 +38,8 @@ deno task build && deno task server # packs the mods and starts a se - [Block Components](docs/modding/blocks/components.md): giving blocks behavior from a server script - [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, the part clients see, and blocks that hold or show items -- [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns +- [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns or the items and fluid in a + machine - [Crops](docs/modding/blocks/crops.md): farming without writing code - [Verdigris](docs/modding/blocks/verdigris.md): blocks that make and use signals, like levers, torches and doors diff --git a/client/renderer/core.ts b/client/renderer/core.ts index 1f1be2d..5fb29d4 100644 --- a/client/renderer/core.ts +++ b/client/renderer/core.ts @@ -43,7 +43,7 @@ let canvas_format: GPUTextureFormat; let pipeline_2d: GPURenderPipeline; let pipeline_3d: GPURenderPipeline; let terrain_pipelines: Record; -let instance_pipeline: GPURenderPipeline; +let instance_pipelines: { cutout: GPURenderPipeline; translucent: GPURenderPipeline }; // 0 1 2 0 2 3 for every quad, shared by all solid and cutout chunk meshes let quad_index_buffer: GPUBuffer | undefined; let quad_index_capacity = 0; @@ -576,16 +576,24 @@ export function draw_terrain( } // draws a model's quads (4 vertices each, see MODEL_VERTEX_BYTES) once for each of the first instance_count instances -// in instances (see INSTANCE_FLOATS), in one draw call -export function draw_instances(model: GPUBuffer, quad_count: number, instances: GPUBuffer, instance_count: number) { +// in instances (see INSTANCE_FLOATS), in one draw call. cut out like cutout terrain, or blended like translucent +// terrain, which needs drawing back to front +export function draw_instances( + model: GPUBuffer, + quad_count: number, + instances: GPUBuffer, + instance_count: number, + translucent = false, +) { if (!current_texture || quad_count === 0 || instance_count === 0) { return; } ensure_quad_indices(quad_count); const render_pass = ensure_pass(); - if (current_pipeline !== instance_pipeline) { - render_pass.setPipeline(instance_pipeline); - current_pipeline = instance_pipeline; + const pipeline = translucent ? instance_pipelines.translucent : instance_pipelines.cutout; + if (current_pipeline !== pipeline) { + render_pass.setPipeline(pipeline); + current_pipeline = pipeline; terrain_binds = undefined; } render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]); @@ -1010,26 +1018,30 @@ function create_pipelines() { primitive: primitive_3d, depthStencil: depth_3d, }); + const blend: GPUBlendState = { + color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" }, + alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" }, + }; terrain_pipelines = { solid: terrain_pipeline("fs_solid"), // alpha to coverage needs msaa cutout: sample_count > 1 ? terrain_pipeline("fs_cutout", undefined, true) : terrain_pipeline("fs_cutout_discard"), - translucent: terrain_pipeline("fs_translucent", { - color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" }, - alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" }, - }), + translucent: terrain_pipeline("fs_translucent", blend), }; - // instances are cut out like cutout terrain + // instances are cut out like cutout terrain, or blended like translucent terrain, like a fluid's box const instance_vertex: GPUVertexState = { module: terrain_module, entryPoint: "vs_instance", buffers: INSTANCED_BUFFERS, }; - instance_pipeline = sample_count > 1 - ? terrain_pipeline("fs_cutout", undefined, true, instance_vertex) - : terrain_pipeline("fs_cutout_discard", undefined, false, instance_vertex); + instance_pipelines = { + cutout: sample_count > 1 + ? terrain_pipeline("fs_cutout", undefined, true, instance_vertex) + : terrain_pipeline("fs_cutout_discard", undefined, false, instance_vertex), + translucent: terrain_pipeline("fs_translucent", blend, false, instance_vertex), + }; } // how vs_instance reads a model's vertices and its instances diff --git a/client/rendering/game_renderer.ts b/client/rendering/game_renderer.ts index 8832e19..3a7a659 100644 --- a/client/rendering/game_renderer.ts +++ b/client/rendering/game_renderer.ts @@ -78,7 +78,7 @@ export class GameRenderer { level.render_block_outline(client.level, client.hit_result, camera); level.render_entities(client.level, camera, client.player, partial_tick); }); - profiler.section("visuals", () => level.render_visuals(client.level, partial_tick)); + profiler.section("visuals", () => level.render_visuals(client.level, camera, partial_tick)); profiler.section("translucent", () => level.render_translucent(client.level, camera)); profiler.section("nameplates", () => render_nameplates(client.level, camera, client.player, partial_tick)); end_mode_3d(); diff --git a/client/rendering/item_renderer.ts b/client/rendering/item_renderer.ts index 8b5cf07..bc326c7 100644 --- a/client/rendering/item_renderer.ts +++ b/client/rendering/item_renderer.ts @@ -8,6 +8,7 @@ import { AssetManager } from "$/client/assets.ts"; import { get_sprite_region } from "$/client/sprites.ts"; import type { ItemEntity } from "$/client/entity/item_entity.ts"; import { contained_fluid, type ItemData, ItemStack } from "$/common/inventory.ts"; +import type { FluidVariant } from "$/common/mod_api/shared.ts"; import { light_color, push_vertex, Texture } from "$/client/renderer/mod.ts"; import { bake_model, @@ -76,6 +77,18 @@ const SHOWN_COPY_SPREAD = 0.075; // a point of an item's model to where it's drawn. models are 1 across, from y 0 to 1, centered on x and z export type ItemTransform = (x: number, y: number, z: number) => [number, number, number]; +// where push_item's vertices go: the batch, or anything else that takes them the same way, like a visual's model +export type VertexSink = typeof push_vertex; + +// an item the size it's drawn on the ground, with its middle at the middle of the block. for a visual's item, which +// is placed from there, like create's items in a basin +export function ground_transform(item: ItemStack): ItemTransform { + const ground = item_model_of(item)?.display.ground; + if (ground) return display_transform(mat4.fromTranslation(mat4.create(), [0.5, 0.5, 0.5]), ground); + const scale = drawn_as_model(item) ? BLOCK_SCALE : ITEM_SCALE; + return (x, y, z) => [0.5 + x * scale, 0.5 + (y - 0.5) * scale, 0.5 + z * scale]; +} + // the atlas has to be the current texture export function render_item_entity(entity: ItemEntity, partial_tick: number) { const atlas = AssetManager.instance.get("bworld:textures"); @@ -288,8 +301,15 @@ export function display_transform(base: mat4, display: DisplayTransform): ItemTr } // an item's model: its own model or its block's item_model, a cube for other blocks, its sprite made 3d for everything -// else (see item_model.ts). tint multiplies its colors, like the light it's in -export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransform, [tr, tg, tb]: Vec3 = [1, 1, 1]) { +// else (see item_model.ts). tint multiplies its colors, like the light it's in. two triangles a quad, its corners 0 1 2 +// and 0 2 3 +export function push_item( + atlas: Texture, + item: ItemStack, + transform: ItemTransform, + [tr, tg, tb]: Vec3 = [1, 1, 1], + vertex: VertexSink = push_vertex, +) { const model = item_model_of(item); if (model) { for (const quad of model.quads) { @@ -299,7 +319,7 @@ export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransf for (const i of [0, 1, 2, 0, 2, 3]) { const p = quad.positions; const [px, py, pz] = transform(p[i * 3] - 0.5, p[i * 3 + 1], p[i * 3 + 2] - 0.5); - push_vertex( + vertex( px, py, pz, @@ -320,17 +340,18 @@ export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransf const region = get_sprite_region(cube_face_texture(block, face.texture)); const corners = face.corners.map(([cx, cy, cz]) => transform(cx - 0.5, cy, cz - 0.5)); const [r, g, b] = cube_face_tint(block, face.texture); - push_textured_quad(atlas, region, corners, [face.shade * r * tr, face.shade * g * tg, face.shade * b * tb]); + const color = [face.shade * r * tr, face.shade * g * tg, face.shade * b * tb]; + push_textured_quad(atlas, region, corners, color, vertex); } return; } // its sprite, then its layers over it: only their fronts and backs, the first two quads, each a little further out const texture_id = item_texture(item); - push_sprite(atlas, texture_id, item_model(texture_id), [tr, tg, tb], 0, transform); + push_sprite(atlas, texture_id, item_model(texture_id), [tr, tg, tb], 0, transform, vertex); item_layers(item).forEach(({ texture, color: [r, g, b] }, i) => { const color: Vec3 = [r * tr, g * tg, b * tb]; - push_sprite(atlas, texture, item_model(texture).slice(0, 2), color, (i + 1) * LAYER_GAP, transform); + push_sprite(atlas, texture, item_model(texture).slice(0, 2), color, (i + 1) * LAYER_GAP, transform, vertex); }); } @@ -342,6 +363,7 @@ function push_sprite( [r, g, b]: Vec3, gap: number, transform: ItemTransform, + vertex: VertexSink, ) { const region = get_sprite_region(texture_id); for (const quad of quads) { @@ -351,7 +373,7 @@ function push_sprite( const [pu, pv] = quad.uvs[i]; const u = (region.x + pu) / atlas.width; const v = (region.y + pv) / atlas.height; - push_vertex(px, py, pz, u, v, quad.shade * r, quad.shade * g, quad.shade * b, 1); + vertex(px, py, pz, u, v, quad.shade * r, quad.shade * g, quad.shade * b, 1); } } } @@ -370,7 +392,12 @@ function layer_color(item: ItemStack, tint: ItemLayer["tint"]): Vec3 | undefined if (tint === undefined) return [1, 1, 1]; if (tint !== "fluid") return color_rgb(tint_without_biome(tint)); const fluid = contained_fluid(item.type_id, item.data); - return fluid && color_rgb(tint_without_biome(fluid_rules.color(fluid) as TintColor)); + return fluid && fluid_rgb(fluid); +} + +// a fluid's color by its rules, as r g b from 0 to 1 +export function fluid_rgb(fluid: FluidVariant): Vec3 { + return color_rgb(tint_without_biome(fluid_rules.color(fluid) as TintColor)); } // where a model's uv in pixels (0-16) is in the atlas. the atlas's border around each sprite (see ATLAS_BORDER) keeps @@ -383,7 +410,13 @@ export function sprite_v(atlas: Texture, region: SpriteRegion, pixels: number) { return (region.y + pixels / TEXTURE_SIZE * region.height) / atlas.height; } -function push_textured_quad(atlas: Texture, region: SpriteRegion, corners: number[][], color: number[]) { +function push_textured_quad( + atlas: Texture, + region: SpriteRegion, + corners: number[][], + color: number[], + vertex: VertexSink, +) { const u0 = region.x / atlas.width; const v0 = region.y / atlas.height; const u1 = (region.x + region.width) / atlas.width; @@ -392,6 +425,6 @@ function push_textured_quad(atlas: Texture, region: SpriteRegion, corners: numbe for (const i of [0, 1, 2, 0, 2, 3]) { const [px, py, pz] = corners[i]; const [cu, cv] = CORNER_UVS[i]; - push_vertex(px, py, pz, cu ? u1 : u0, cv ? v1 : v0, color[0], color[1], color[2], 1); + vertex(px, py, pz, cu ? u1 : u0, cv ? v1 : v0, color[0], color[1], color[2], 1); } } diff --git a/client/rendering/level_renderer.ts b/client/rendering/level_renderer.ts index 09c833a..174f437 100644 --- a/client/rendering/level_renderer.ts +++ b/client/rendering/level_renderer.ts @@ -149,12 +149,12 @@ export class LevelRenderer { } // blocks drawn with code, see client/rendering/visuals.ts. the ones in chunks in view get their on_frame first - render_visuals(level: ClientLevel, partial_tick: number) { + render_visuals(level: ClientLevel, camera: Camera, partial_tick: number) { if (!this.draw.visuals) return; level.visuals.frame(this.#visible, level.ticks + partial_tick); flush_batch(); set_current_texture(level.image.tex); - draw_visuals(level.visuals, level.image); + draw_visuals(level.visuals, level.image, [camera.x, camera.y, camera.z]); } // the cracks on the block being broken, and on the ones machines are breaking, drawn over their models' faces like diff --git a/client/rendering/visuals.ts b/client/rendering/visuals.ts index 9d5e0cf..c225a43 100644 --- a/client/rendering/visuals.ts +++ b/client/rendering/visuals.ts @@ -5,10 +5,13 @@ // block, made when its chunk is meshed and kept by chunk. what they draw are instances of models, and every instance of // a model is drawn in one draw call from a buffer of where each is, how it spins and its light (see vs_instance in // client/renderer/core.ts). the gpu turns rotating ones by the time, so a shaft that keeps turning costs nothing per -// frame +// frame. an item is a model too, one per way an item can look, and a fluid's box is a model of its own import { mat4, vec3 } from "gl-matrix"; import type { + FluidInstance, + FluidVariant, Instances, + ItemStack as ApiItemStack, ModelRef, RotatingInstance, TransformedInstance, @@ -22,11 +25,14 @@ import { type BakedQuad, find_model, item_tint, + type ModelElementJson, type ModelJson, states_of, } from "$/common/block_models.ts"; import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts"; -import { chunk_key } from "$/common/utils.ts"; +import type { FluidJson, ModelFace } from "$/common/mod_data.ts"; +import { ItemStack } from "$/common/inventory.ts"; +import { chunk_key, item_texture } from "$/common/utils.ts"; import { create_vertex_buffer, destroy_buffer, @@ -37,7 +43,7 @@ import { write_buffer, } from "$/client/renderer/mod.ts"; import { get_sprite_region } from "$/client/sprites.ts"; -import { sprite_u, sprite_v } from "./item_renderer.ts"; +import { fluid_rgb, ground_transform, item_layers, push_item, sprite_u, sprite_v } from "./item_renderer.ts"; export interface VisualRegistration { mod: string; @@ -73,23 +79,57 @@ export interface DrawnInstance { light: number; } +// a quad of an instanced model: 4 corners counter clockwise seen from the front, x y z each in the model's space, their +// uvs in atlas pixels, so they don't depend on the atlas's size, its tint, and whether the gpu shades it by the way it +// faces +export interface InstanceQuad { + positions: number[]; + uvs: number[]; + tint: number[]; + shade: boolean; +} + +// what to give sprite_u and sprite_v for uvs in atlas pixels +const ATLAS_PIXELS = { width: 1, height: 1 } as Texture; + +// a model's baked quads as an instanced model's, each tinted +export function instance_quads(quads: BakedQuad[], tint: (quad: BakedQuad) => number[]): InstanceQuad[] { + return quads.map((quad) => { + const region = get_sprite_region(quad.texture); + const uvs = quad.uvs.map((pixels, i) => + i % 2 === 0 ? sprite_u(ATLAS_PIXELS, region, pixels) : sprite_v(ATLAS_PIXELS, region, pixels) + ); + return { positions: quad.positions, uvs, tint: tint(quad), shade: quad.shade }; + }); +} + // the instances of one model, drawn in one draw call. their data is changed on the cpu and written to the gpu once a // frame, from the first instance that changed to the last export class InstanceGroup { - readonly quads: BakedQuad[]; - // each quad's tint, white but for a block's own tinted quads, like leaves - readonly tints: number[][]; + quads: InstanceQuad[]; + // drawn blended after the rest, back to front by center, like a fluid's box + readonly translucent: boolean; + // where it is in the world, for drawing translucent ones back to front + center = vec3.create(); readonly instances: DrawnInstance[] = []; data = new Float32Array(INSTANCE_FLOATS * 16); // the instances changed since the gpu last got them, by index dirty_from = Infinity; dirty_to = -1; + // quads changed since the gpu last got them + model_changed = false; // made the first time it's drawn gpu?: { model: GPUBuffer; instances: GPUBuffer; capacity: number }; - constructor(quads: BakedQuad[], tints: number[][]) { + constructor(quads: InstanceQuad[], translucent = false) { this.quads = quads; - this.tints = tints; + this.translucent = translucent; + } + + // for a model that changes, like a fluid's box filling up + set_quads(quads: InstanceQuad[]) { + this.quads = quads; + this.model_changed = true; } add(instance: DrawnInstance) { @@ -152,9 +192,12 @@ export class Visuals { #level: VisualsLevel; // baked once per level, since a level's mods don't change #models?: Record; - // models from models/ by id and turns, and blocks' own by value + // models from models/ by id and turns, blocks' own by value, and items by how they look #model_groups = new Map(); #block_groups = new Map(); + #item_groups = new Map(); + // a fluid box's model is its own, and goes with it + #fluid_groups = new Set(); constructor(level: VisualsLevel) { this.#level = level; @@ -167,6 +210,8 @@ export class Visuals { *groups(): Iterable { yield* this.#model_groups.values(); yield* this.#block_groups.values(); + yield* this.#item_groups.values(); + yield* this.#fluid_groups; } // the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk and its value. visuals @@ -215,14 +260,10 @@ export class Visuals { for (const entry of this.#chunks.get(key)!.values()) this.#delete(entry); } this.#chunks.clear(); - for (const group of this.groups()) { - if (group.gpu) { - destroy_buffer(group.gpu.model); - destroy_buffer(group.gpu.instances); - } - } + for (const group of this.groups()) destroy_group(group); this.#model_groups.clear(); this.#block_groups.clear(); + this.#item_groups.clear(); } // the visuals in these chunks get their on_frame. every instance is drawn either way, it's the gpu that skips what's @@ -275,10 +316,15 @@ export class Visuals { } #remove_instances(entry: Entry) { - for (const instance of entry.instances) instance.group.remove(instance); + for (const instance of entry.instances) this.#remove_instance(instance); entry.instances.clear(); } + #remove_instance(instance: DrawnInstance) { + instance.group.remove(instance); + if (this.#fluid_groups.delete(instance.group)) destroy_group(instance.group); + } + #relight(entry: Entry) { const light = this.#level.get_light(entry.x, entry.y, entry.z); if (light === entry.light) return; @@ -291,8 +337,7 @@ export class Visuals { #instances(entry: Entry, block: BlockRegistry): Instances { const corner = mat4.fromTranslation(mat4.create(), [entry.x, entry.y, entry.z]); - const add = (model: ModelRef | undefined) => { - const group = model === undefined ? this.#block_group(block, entry.value) : this.#model_group(model); + const add = (group: InstanceGroup) => { const instance: DrawnInstance = { group, index: -1, @@ -307,23 +352,44 @@ export class Visuals { return instance; }; const remove = (instance: DrawnInstance) => () => { - instance.group.remove(instance); + this.#remove_instance(instance); entry.instances.delete(instance); }; + const model_group = (model: ModelRef | undefined) => + model === undefined ? this.#block_group(block, entry.value) : this.#model_group(model); + const transformed = (instance: DrawnInstance): TransformedInstance => ({ + set_transform(matrix) { + if (matrix?.length !== 16) throw new Error("a transform is 16 numbers, a 4x4 matrix"); + mat4.multiply(instance.placement, corner, matrix as mat4); + instance.group.write(instance); + }, + delete: remove(instance), + }); return { - transformed(model): TransformedInstance { - const instance = add(model); + transformed: (model) => transformed(add(model_group(model))), + item: (stack) => transformed(add(this.#item_group(stack))), + fluid: (fluid) => { + const { texture, tint } = fluid_look(fluid); + const group = new InstanceGroup([], true); + this.#fluid_groups.add(group); + const instance = add(group); return { - set_transform(matrix) { - if (matrix?.length !== 16) throw new Error("a transform is 16 numbers, a 4x4 matrix"); - mat4.multiply(instance.placement, corner, matrix as mat4); - instance.group.write(instance); + set_box(from, to) { + const box = [from, to].map((corner) => [0, 1, 2].map((axis) => corner?.[axis])); + if (!box.flat().every(Number.isFinite)) throw new Error("a box is from [x, y, z] to [x, y, z]"); + group.set_quads(fluid_box(texture, tint, box[0], box[1])); + vec3.set( + group.center, + entry.x + (box[0][0] + box[1][0]) / 32, + entry.y + (box[0][1] + box[1][1]) / 32, + entry.z + (box[0][2] + box[1][2]) / 32, + ); }, delete: remove(instance), - }; + } satisfies FluidInstance; }, rotating(model): RotatingInstance { - const instance = add(model); + const instance = add(model_group(model)); return { set_rotation(axis, rpm, offset = 0) { if (!AXES[axis]) throw new Error(`an axis is "x", "y" or "z", not ${axis}`); @@ -346,8 +412,7 @@ export class Visuals { this.#models ??= Object.fromEntries(EverythingRegistry.entries("models")); const json = find_model(model, this.#models); if (!json) throw new Error(`there's no model ${model}`); - const quads = bake_model(json, undefined, y, x); - group = new InstanceGroup(quads, quads.map(() => [1, 1, 1])); + group = new InstanceGroup(instance_quads(bake_model(json, undefined, y, x), () => [1, 1, 1])); this.#model_groups.set(key, group); } return group; @@ -358,11 +423,113 @@ export class Visuals { if (!group) { this.#models ??= Object.fromEntries(EverythingRegistry.entries("models")); const quads = bake_block(block, value, this.#models); - group = new InstanceGroup(quads, quads.map((quad) => item_tint(block, quad.variables))); + group = new InstanceGroup(instance_quads(quads, (quad) => item_tint(block, quad.variables))); this.#block_groups.set(value, group); } return group; } + + // stacks that look the same share one: the same item, texture and layers in the same colors, like bottles of one + // juice + #item_group(stack: ApiItemStack): InstanceGroup { + if (!EverythingRegistry.get("items", stack?.id)) throw new Error(`there's no item ${stack?.id}`); + const item = new ItemStack(stack.id); + if (stack.data !== undefined) item.data = structuredClone(stack.data); + const key = JSON.stringify([item.type_id, item_texture(item), item_layers(item)]); + let group = this.#item_groups.get(key); + if (!group) { + group = new InstanceGroup(item_quads(item)); + this.#item_groups.set(key, group); + } + return group; + } +} + +// an item's model the way push_item draws it, the size it's drawn on the ground. its shading is in its tints already, +// like a dropped item's, so the gpu doesn't shade it again +function item_quads(item: ItemStack): InstanceQuad[] { + const vertices: number[][] = []; + push_item(ATLAS_PIXELS, item, ground_transform(item), [1, 1, 1], (x, y, z, u, v, r = 1, g = 1, b = 1) => { + vertices.push([x, y, z, u, v, r, g, b]); + }); + const quads: InstanceQuad[] = []; + // two triangles a quad, its corners 0 1 2 and 0 2 3 + for (let i = 0; i < vertices.length; i += 6) { + const corners = [vertices[i], vertices[i + 1], vertices[i + 2], vertices[i + 5]]; + quads.push({ + positions: corners.flatMap(([x, y, z]) => [x, y, z]), + uvs: corners.flatMap(([, , , u, v]) => [u, v]), + tint: corners[0].slice(5, 8), + shade: false, + }); + } + return quads; +} + +// a fluid's texture and its color by its rules, for a box of it +function fluid_look(fluid: FluidVariant) { + const json = EverythingRegistry.get("fluids", fluid?.id); + if (!json) throw new Error(`there's no fluid ${fluid?.id}`); + return { texture: json.texture ?? "engine:missing", tint: fluid_rgb(structuredClone(fluid)) }; +} + +// a box's faces, by the axis they're across and whether they're at its high end or its low one +const BOX_FACES: { face: ModelFace; axis: number; high: boolean }[] = [ + { face: "west", axis: 0, high: false }, + { face: "east", axis: 0, high: true }, + { face: "bottom", axis: 1, high: false }, + { face: "top", axis: 1, high: true }, + { face: "north", axis: 2, high: false }, + { face: "south", axis: 2, high: true }, +]; + +// a box of a texture from one corner to the other, in pixels, like a fluid in a tank. it's cut where it goes from one +// block into the next, and each piece is textured with the part of the texture it covers in its block, like a model +// element's faces are, so the texture is never stretched and repeats once a block. only the outside faces are drawn. +// nothing for a box that's flat or inside out +export function fluid_box(texture: string, tint: number[], from: number[], to: number[]): InstanceQuad[] { + if ([0, 1, 2].some((axis) => to[axis] <= from[axis])) return []; + // where each axis's pieces start and end + const cuts = [0, 1, 2].map((axis) => { + const points = [from[axis]]; + for (let at = (Math.floor(from[axis] / 16) + 1) * 16; at < to[axis]; at += 16) points.push(at); + return [...points, to[axis]]; + }); + const model: ModelJson = { id: "engine:fluid_box", textures: { fluid: texture }, elements: [] }; + const quads: InstanceQuad[] = []; + for (let i = 0; i < cuts[0].length - 1; i++) { + for (let j = 0; j < cuts[1].length - 1; j++) { + for (let k = 0; k < cuts[2].length - 1; k++) { + const low = [cuts[0][i], cuts[1][j], cuts[2][k]]; + const high = [cuts[0][i + 1], cuts[1][j + 1], cuts[2][k + 1]]; + const block = low.map((at) => Math.floor(at / 16)); + const element: ModelElementJson = { + from: low.map((at, axis) => at - block[axis] * 16) as [number, number, number], + to: high.map((at, axis) => at - block[axis] * 16) as [number, number, number], + faces: {}, + }; + for (const { face, axis, high: side } of BOX_FACES) { + if (side ? high[axis] === to[axis] : low[axis] === from[axis]) { + element.faces[face] = { texture: "#fluid" }; + } + } + const baked = bake_model({ ...model, elements: [element] }, undefined); + for (const quad of baked) { + quad.positions = quad.positions.map((at, n) => at + block[n % 3]); + } + quads.push(...instance_quads(baked, () => tint)); + } + } + } + return quads; +} + +// a group's gpu buffers go, for a group that won't be drawn again +function destroy_group(group: InstanceGroup) { + if (!group.gpu) return; + destroy_buffer(group.gpu.model); + destroy_buffer(group.gpu.instances); + group.gpu = undefined; } // false when it threw, which is logged with the mod and block @@ -376,39 +543,54 @@ function run_visual(entry: Entry, what: string, fn: () => void) { } } -// every instance, a draw call per model. a group's model goes to the gpu the first time it's drawn, and its instances -// whenever they changed. the atlas has to be the current texture -export function draw_visuals(visuals: Visuals, atlas: Texture) { +// every instance, a draw call per model, and the translucent ones after the rest, back to front from the camera so each +// shows what's behind it. a group's model goes to the gpu the first time it's drawn and again when it changed, and its +// instances whenever they changed. the atlas has to be the current texture +export function draw_visuals(visuals: Visuals, atlas: Texture, camera: Readonly) { + const translucent: InstanceGroup[] = []; for (const group of visuals.groups()) { - const count = group.instances.length; - if (count === 0) continue; - const capacity = group.data.length / INSTANCE_FLOATS; - if (!group.gpu || group.gpu.capacity !== capacity) { - // the whole buffer again, when it's new or the cpu copy grew - if (group.gpu) destroy_buffer(group.gpu.instances); - group.gpu = { - model: group.gpu?.model ?? create_vertex_buffer(pack_model(group.quads, group.tints, atlas)), - instances: create_vertex_buffer(group.data), - capacity, - }; - } else if (group.dirty_to >= 0) { - const from = group.dirty_from * INSTANCE_FLOATS; - write_buffer( - group.gpu.instances, - from * 4, - group.data, - from, - (group.dirty_to + 1) * INSTANCE_FLOATS - from, - ); - } - group.dirty_from = Infinity; - group.dirty_to = -1; - draw_instances(group.gpu.model, group.quads.length, group.gpu.instances, count); + if (group.translucent) translucent.push(group); + else draw_group(group, atlas); } + const distance = (group: InstanceGroup) => vec3.squaredDistance(group.center, camera); + translucent.sort((a, b) => distance(b) - distance(a)); + for (const group of translucent) draw_group(group, atlas); +} + +function draw_group(group: InstanceGroup, atlas: Texture) { + const count = group.instances.length; + if (count === 0 || group.quads.length === 0) return; + const capacity = group.data.length / INSTANCE_FLOATS; + if (group.gpu && group.model_changed) { + destroy_buffer(group.gpu.model); + group.gpu.model = create_vertex_buffer(pack_model(group.quads, atlas)); + } + group.model_changed = false; + if (!group.gpu || group.gpu.capacity !== capacity) { + // the whole buffer again, when it's new or the cpu copy grew + if (group.gpu) destroy_buffer(group.gpu.instances); + group.gpu = { + model: group.gpu?.model ?? create_vertex_buffer(pack_model(group.quads, atlas)), + instances: create_vertex_buffer(group.data), + capacity, + }; + } else if (group.dirty_to >= 0) { + const from = group.dirty_from * INSTANCE_FLOATS; + write_buffer( + group.gpu.instances, + from * 4, + group.data, + from, + (group.dirty_to + 1) * INSTANCE_FLOATS - from, + ); + } + group.dirty_from = Infinity; + group.dirty_to = -1; + draw_instances(group.gpu.model, group.quads.length, group.gpu.instances, count, group.translucent); } // a model's quads as vertices for vs_instance, 4 a quad, see MODEL_VERTEX_BYTES -export function pack_model(quads: BakedQuad[], tints: number[][], atlas: Texture): Uint8Array { +export function pack_model(quads: InstanceQuad[], atlas: Texture): Uint8Array { const bytes = new Uint8Array(quads.length * 4 * MODEL_VERTEX_BYTES); const view = new DataView(bytes.buffer); const normal = vec3.create(); @@ -418,13 +600,12 @@ export function pack_model(quads: BakedQuad[], tints: number[][], atlas: Texture // counterclockwise seen from the front, so it points out of the front const [a, b, d] = [corner(0), corner(1), corner(3)]; vec3.normalize(normal, vec3.cross(normal, vec3.sub(b, b, a), vec3.sub(d, d, a))); - const region = get_sprite_region(quad.texture); - const tint = tints[q]; + const tint = quad.tint; for (let k = 0; k < 4; k++) { const at = (q * 4 + k) * MODEL_VERTEX_BYTES; for (let axis = 0; axis < 3; axis++) view.setFloat32(at + axis * 4, p[k * 3 + axis], true); - view.setUint16(at + 12, Math.round(sprite_u(atlas, region, quad.uvs[k * 2]) * 65535), true); - view.setUint16(at + 14, Math.round(sprite_v(atlas, region, quad.uvs[k * 2 + 1]) * 65535), true); + view.setUint16(at + 12, Math.round(quad.uvs[k * 2] / atlas.width * 65535), true); + view.setUint16(at + 14, Math.round(quad.uvs[k * 2 + 1] / atlas.height * 65535), true); for (let c = 0; c < 3; c++) bytes[at + 16 + c] = Math.round(tint[c] * 255); bytes[at + 19] = quad.shade ? 255 : 0; for (let axis = 0; axis < 3; axis++) view.setInt8(at + 20 + axis, Math.round(normal[axis] * 127)); diff --git a/common/mod_api/client.ts b/common/mod_api/client.ts index 25faacb..7ef012a 100644 --- a/common/mod_api/client.ts +++ b/common/mod_api/client.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // what client scripts get, see docs/modding/gui/index.md -import type { FluidApi, Id, ItemStack, KeyCode, ModInfo, Position, Season, TagApi } from "./shared.ts"; +import type { FluidApi, FluidVariant, Id, ItemStack, KeyCode, ModInfo, Position, Season, TagApi } from "./shared.ts"; import type { LootTableJson } from "../loot.ts"; export type { @@ -132,6 +132,11 @@ export interface Instances { transformed(model?: ModelRef): TransformedInstance; // turning at a steady speed worked out from the time, so it never needs anything per frame rotating(model?: ModelRef): RotatingInstance; + // one of an item, whatever the stack's count: the size it's drawn on the ground, with its middle at the middle of + // the block, placed by a matrix like a transformed model. like a block entity renderer drawing an item + item(stack: ItemStack): TransformedInstance; + // a box of a fluid, its texture tinted in its color, see FluidInstance. it shows what's behind it + fluid(fluid: FluidVariant): FluidInstance; } export interface Instance { @@ -145,6 +150,13 @@ export interface TransformedInstance extends Instance { set_transform(matrix: ArrayLike): void; } +// nothing is drawn until set_box is called +export interface FluidInstance extends Instance { + // from one corner to the other, in pixels like a model's elements: 0 to 16 across the block, past it for a box that + // reaches into the blocks around, like a tank's. the texture is cut to fit, never stretched + set_box(from: [number, number, number], to: [number, number, number]): void; +} + export interface RotatingInstance extends Instance { // turns around axis through the middle of the block, counterclockwise seen from the axis's positive end when rpm // is positive, at time * rpm * 0.3 + offset degrees. still when not set diff --git a/common/mod_check.ts b/common/mod_check.ts index 53f62d7..3ebcdaf 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -490,6 +490,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable 1) { errors.push(`${file}: fluid ${json.id} is also defined by ${fluid_owners.get(json.id)!.join(", ")}`); } + if (json.texture !== undefined) uses(file, json.texture, "texture"); } for (const { file, json } of mod.spawns) { check_namespace(file, json.entity); diff --git a/common/mod_data.ts b/common/mod_data.ts index cf4c712..88c8d3f 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -484,6 +484,8 @@ const fluid_schema = z.object({ name: text.optional(), // for whatever shows it, like a layer tinted "fluid" on a full container color, + // what a box of it is drawn with, tinted by its color, like neoforge's still texture. engine:missing when not set + texture: z.string().optional(), }); export type FluidJson = z.infer; diff --git a/docs/modding/blocks/visuals.md b/docs/modding/blocks/visuals.md index a7fc5cd..e8fc1f2 100644 --- a/docs/modding/blocks/visuals.md +++ b/docs/modding/blocks/visuals.md @@ -1,8 +1,9 @@ # Visuals -A visual draws a block with code, for blocks that move: a shaft that turns, a crank's handle, a press coming down. A -client script registers one for a block, and every block of that kind in a shown chunk gets its own. It's bworld's -version of Minecraft's block entity renderers, shaped like the Flywheel visuals Create draws its machines with. +A visual draws a block with code, for blocks that move or show what's in them: a shaft that turns, a press coming down, +the items and fluid in a machine. A client script registers one for a block, and every block of that kind in a shown +chunk gets its own. It's bworld's version of Minecraft's block entity renderers, shaped like the Flywheel visuals Create +draws its machines with. ## Registering @@ -73,6 +74,50 @@ head.set_transform([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -0.5, 0, 1]); // half `delete()` stops drawing an instance for good. +### Items + +An **item** instance draws one of an item, whatever the stack's count, the way it looks in a slot: its model, its block, +or its sprite with its [layers](../items/index.md#layers) in their colors, like a bottle with its juice. It's the size +it's drawn on the ground (half a block across, a block's item a quarter), with its middle at the middle of the block, +and it's placed by a matrix like a transformed model: + +```ts +const stack = block.get_client_data("item"); +if (stack) { + const item = instances.item(stack); + const lying = mat4.fromTranslation(mat4.create(), [0.5, 0.2, 0.5]); + mat4.rotateX(lying, lying, Math.PI / 2); + mat4.translate(lying, lying, [-0.5, -0.5, -0.5]); + item.set_transform(lying); // flat, a bit above the bottom of the block +} +``` + +The server tells the visual what to draw through [client data](tiledata.md#client-data), like the stack above. To draw a +stack as more than one, like a basin with a copy for every 8 items, make an instance per copy. To change what an +instance draws, delete it and make another. + +### Fluids + +A **fluid** instance draws a box of a [fluid](../resources/fluids.md), its `texture` tinted in its color for its data, +like what's in a tank: + +```ts +const tank = block.get_client_data<{ fluid: FluidVariant; amount: number }>("tank"); +if (tank) { + const juice = instances.fluid(tank.fluid); + juice.set_box([2, 2, 2], [14, 2 + 12 * tank.amount / 1000, 14]); // filling the 12 pixels inside its walls +} +``` + +`set_box(from, to)` is in pixels, like a model's elements: 0 to 16 across the block, or past it for a box that reaches +into the blocks around, like a tank's. The texture is cut to fit, never stretched, and repeats once a block. Nothing is +drawn until a box is set, and it can be set again whenever the fluid goes up or down. Only the box's outside is drawn, +so it can't be seen from inside it. + +A fluid's box shows what's behind it, as much as its texture's alpha lets through. Boxes are drawn after the rest of the +visuals, the farthest first. Translucent terrain like water is drawn after them, so water behind a box isn't seen +through it. + ## Moving Every Frame A visual whose instances move in a way the time can't say, like a crank's handle slowing to a stop, moves them in @@ -105,3 +150,7 @@ Only visuals in chunks in view get `on_frame`, so keep anything that has to happ Every instance of a model is drawn in one draw call, and the GPU turns rotating instances by the time, so a block that keeps turning costs nothing per frame. Setting an instance's rotation or transform sends just that instance to the GPU again. What costs CPU time is `on_frame`, so use a rotating instance wherever the movement is steady. + +Items that look the same are one model: every bottle of strawberry juice in every visual is one draw call, and one of +melon juice another. A fluid's box is a model of its own, so each is a draw call, and setting its box sends its few +faces to the GPU again. diff --git a/docs/modding/resources/fluids.md b/docs/modding/resources/fluids.md index 4d49d7d..3428e6e 100644 --- a/docs/modding/resources/fluids.md +++ b/docs/modding/resources/fluids.md @@ -16,16 +16,22 @@ here has no block, so it can't be placed. "fluid": { "id": "copper_tools:maple_syrup", "name": "Maple Syrup", - "color": "#a0522d" + "color": "#a0522d", + "texture": "bworld:water_still" } } ``` -| Field | Required | What it does | -| ------- | -------- | ------------------------------------------------------------------------------------------- | -| `id` | yes | The fluid's id, in the mod's [namespace](../concepts/registries.md#identifiers). | -| `name` | no | What players see. `copper_tools:maple_syrup` is "Maple Syrup" when not set, like an item's. | -| `color` | yes | Its color, like `"#a0522d"`, for whatever shows it. | +| Field | Required | What it does | +| --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- | +| `id` | yes | The fluid's id, in the mod's [namespace](../concepts/registries.md#identifiers). | +| `name` | no | What players see. `copper_tools:maple_syrup` is "Maple Syrup" when not set, like an item's. | +| `color` | yes | Its color, like `"#a0522d"`, for whatever shows it. | +| `texture` | no | What a [box of it](../blocks/visuals.md#fluids) is drawn with, tinted by its color, like NeoForge's still texture. See below. | + +Like a fluid container's layer, the texture is multiplied by the fluid's color, so a light gray one comes out in the +fluid's own color, and its alpha is how much shows through. The base game's `bworld:water_still` is such a texture, +animated, and any fluid can use it. Without one, a box of the fluid is drawn with the missing texture. ## Fluids With Data diff --git a/mods/bworld/fluids/juice.json b/mods/bworld/fluids/juice.json index b6ef70d..d942851 100644 --- a/mods/bworld/fluids/juice.json +++ b/mods/bworld/fluids/juice.json @@ -3,6 +3,7 @@ "fluid": { "id": "bworld:juice", "name": "Juice", - "color": "#e8a33d" + "color": "#e8a33d", + "texture": "bworld:water_still" } } diff --git a/tests/fluid_registry_test.ts b/tests/fluid_registry_test.ts index 58e39e0..8ff3eb4 100644 --- a/tests/fluid_registry_test.ts +++ b/tests/fluid_registry_test.ts @@ -40,10 +40,14 @@ function fluid_mod(dir: string, fluids: Record, shared_script?: Deno.test("a mod's fluids/ file registers a fluid, packed into its .bmod", async () => { const dir = Deno.makeTempDirSync({ prefix: "bworld_fluids_" }); - const syrup = { id: "testfluids:syrup", name: "Maple Syrup", color: "#a0522d" }; + const syrup = { id: "testfluids:syrup", name: "Maple Syrup", color: "#a0522d", texture: "testfluids:syrup_still" }; fluid_mod(dir, { "syrup.json": syrup }); const mods = load_and_check(dir); assertEquals(mods[0].report.errors, []); + // it has no textures + assertEquals(mods[0].report.warnings, [ + "fluids/syrup.json: texture testfluids:syrup_still doesn't exist, it will show as missing", + ]); const bmod = read_bmod(await pack_mod(mods[0]), "testfluids.bmod"); EverythingRegistry.clear(); register_mod_data([{ id: "testfluids", data: bmod.data }]); diff --git a/tests/visuals_test.ts b/tests/visuals_test.ts index e8f2fe0..e1eb578 100644 --- a/tests/visuals_test.ts +++ b/tests/visuals_test.ts @@ -3,15 +3,15 @@ // blocks drawn with code: the chunk mesher finds them, their visuals come and go with them and their chunks, and the gpu // draws their instances, placed and turned by the time -import { assert, assertEquals, assertRejects } from "@std/assert"; +import { assert, assertEquals, assertRejects, assertThrows } from "@std/assert"; import { mat4 } from "gl-matrix"; import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts"; import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts"; import { block_value } from "$/common/utils.ts"; import type { ModListing } from "$/common/mod_loader.ts"; import { read_bmod } from "$/common/bmod.ts"; -import type { RotatingInstance, Visual } from "$/common/mod_api/client.ts"; -import { block_visuals, InstanceGroup, pack_model, Visuals } from "$/client/rendering/visuals.ts"; +import type { FluidInstance, Instances, RotatingInstance, Visual } from "$/common/mod_api/client.ts"; +import { block_visuals, instance_quads, InstanceGroup, pack_model, Visuals } from "$/client/rendering/visuals.ts"; import { INSTANCE_FLOATS, INSTANCED_BUFFERS, terrain_shader_src, type Texture } from "$/client/renderer/mod.ts"; import type { BakedQuad } from "$/common/block_models.ts"; import { AssetManager } from "$/client/assets.ts"; @@ -25,10 +25,13 @@ const HALF = { elements: [{ from: [6, 0, 6], to: [10, 8, 10], faces: { north: { texture: "#0" } } }], }; -// testmod: a shaft with an axis state and a model of half of one, and maybe a client script +// testmod: a shaft with an axis state and a model of half of one, syrup, a jar drawn with the syrup in it, and maybe a +// client script function write_testmod(dir: string, client_script?: string) { const mod = `${dir}/testmod`; - for (const folder of ["blocks", "models", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true }); + for (const folder of ["blocks", "models", "scripts", "fluids", "items"]) { + Deno.mkdirSync(`${mod}/${folder}`, { recursive: true }); + } const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json)); write("manifest.json", { format_version: 1, @@ -48,16 +51,30 @@ function write_testmod(dir: string, client_script?: string) { }, }); write("models/half.json", { format_version: 1, model: { id: "testmod:half", ...HALF } }); + write("fluids/syrup.json", { + format_version: 1, + fluid: { id: "testmod:syrup", color: "#a0522d", texture: "testmod:syrup_still" }, + }); + write("items/jar.json", { + format_version: 1, + item: { + id: "testmod:jar", + texture: "engine:missing", + fluid_container: { capacity: 250 }, + layers: [{ texture: "engine:break_0", tint: "fluid" }], + }, + }); if (client_script) Deno.writeTextFileSync(`${mod}/scripts/client.ts`, client_script); } -// a game's registries with mods/bworld and testmod +// a game's registries with mods/bworld and testmod. there's no atlas, so every texture is where the missing one would be async function registries() { const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" }); copy_dir("mods/bworld", `${dir}/bworld`); write_testmod(dir); await test_game(dir); Deno.removeSync(dir, { recursive: true }); + AssetManager.instance.assets["bworld:textures_info"] = {}; const nid = (id: string) => EverythingRegistry.get_id("blocks", id)!; const value = (id: string, state = 0) => block_value(nid(id), state); return { nid, value }; @@ -262,6 +279,110 @@ Deno.test("an instance's placement, spin and light are kept for the gpu, and onl block_visuals.clear(); }); +// a visual on one shaft, at 1 64 1, that makes what make does +function one_visual(nid: (id: string) => number, value: (id: string) => number, make: (instances: Instances) => void) { + const visuals = new Visuals({ get_block_data: () => undefined, get_light: () => 0 }); + block_visuals.clear(); + block_visuals.set(nid("testmod:shaft"), { + mod: "testmod", + replaces_model: false, + create(_block, instances) { + make(instances); + return {}; + }, + }); + const mesh = (blocks: number[]) => visuals.meshed(0, 0, Uint32Array.from(blocks)); + mesh([index_of(1, 64, 1), value("testmod:shaft")]); + return { visuals, mesh }; +} + +// the smallest and biggest of every nth number from the first'th, like an axis of a model's positions or uvs +const range = (groups: InstanceGroup[], numbers: "positions" | "uvs", nth: number, first: number) => { + const picked = groups.flatMap((group) => group.quads.flatMap((quad) => quad[numbers])) + .filter((_, i) => i % nth === first); + return [Math.min(...picked), Math.max(...picked)]; +}; + +const SYRUP = [0xa0 / 255, 0x52 / 255, 0x2d / 255]; + +Deno.test("an item is drawn the size it is on the ground, with one model for every stack that looks the same", async () => { + const { nid, value } = await registries(); + const full = { fluid: { id: "testmod:syrup" } }; + const { visuals } = one_visual(nid, value, (instances) => { + instances.item({ id: "testmod:jar", count: 16 }); + instances.item({ id: "testmod:jar", count: 1 }); + instances.item({ id: "testmod:jar", count: 1, data: full }); + instances.item({ id: "testmod:shaft", count: 1 }); + assertThrows( + () => instances.item({ id: "testmod:nothing", count: 1 }), + Error, + "there's no item testmod:nothing", + ); + }); + // the jar's front and back, and its syrup's when it's full, and the shaft's item is a cube. one of each, whatever the + // count + assertEquals(drawn(visuals), ["2 quads x2", "4 quads x1", "6 quads x1"]); + const [empty, filled, cube] = [...visuals.groups()].filter((group) => group.instances.length > 0); + assertEquals(filled.quads.slice(2).map((quad) => quad.tint), [SYRUP, SYRUP]); + // half a block across like a dropped item, and a block a quarter, around the block's middle + assertEquals([range([empty], "positions", 3, 0), range([empty], "positions", 3, 1)], [[0.25, 0.75], [0.25, 0.75]]); + assertEquals([0, 1, 2].map((axis) => range([cube], "positions", 3, axis)), [ + [0.375, 0.625], + [0.375, 0.625], + [0.375, 0.625], + ]); + block_visuals.clear(); +}); + +Deno.test("a fluid's box is its texture cut to fit and tinted in its color, a model of its own that goes with it", async () => { + const { nid, value } = await registries(); + AssetManager.instance.assets["bworld:textures_info"] = { + "testmod:syrup_still": { x: 32, y: 0, width: 16, height: 16 }, + }; + let box: FluidInstance | undefined; + const { visuals, mesh } = one_visual(nid, value, (instances) => { + box = instances.fluid({ id: "testmod:syrup" }); + assertThrows(() => instances.fluid({ id: "testmod:nothing" }), Error, "there's no fluid testmod:nothing"); + }); + const boxes = () => [...visuals.groups()].filter((group) => group.translucent); + // nothing until it has a box + assertEquals(boxes().map((group) => group.quads.length), [0]); + + box!.set_box([2, 2, 2], [14, 8, 14]); + const [group] = boxes(); + assertEquals(group.quads.length, 6); + assert(group.quads.every((quad) => quad.tint === group.quads[0].tint && quad.shade)); + assertEquals(group.quads[0].tint, SYRUP); + // in the block's space, and its top is the middle 12 pixels of the texture, not all 16 squeezed into it + assertEquals([0, 1, 2].map((axis) => range([group], "positions", 3, axis)), [ + [0.125, 0.875], + [0.125, 0.5], + [0.125, 0.875], + ]); + const top = new InstanceGroup( + group.quads.filter((quad) => quad.positions.every((at, i) => i % 3 !== 1 || at === 0.5)), + ); + assertEquals([range([top], "uvs", 2, 0), range([top], "uvs", 2, 1)], [[34, 46], [2, 14]]); + // where it's drawn back to front from + assertEquals([...group.center], [1.5, 64 + 5 / 16, 1.5]); + + // two blocks long it's a piece in each, and the texture repeats + box!.set_box([0, 0, 0], [32, 16, 16]); + assertEquals([group.quads.length, group.model_changed], [10, true]); + assertEquals(range([group], "positions", 3, 0), [0, 2]); + assertEquals([range([group], "uvs", 2, 0), range([group], "uvs", 2, 1)], [[32, 48], [0, 16]]); + + // it goes with its instance, or its visual + box!.delete(); + assertEquals(boxes(), []); + mesh([]); + mesh([index_of(1, 64, 1), value("testmod:shaft")]); + assertEquals(boxes().length, 1); + visuals.unload(0, 0); + assertEquals(boxes(), []); + block_visuals.clear(); +}); + const adapter = await navigator.gpu?.requestAdapter().catch(() => null) ?? null; Deno.test({ @@ -316,16 +437,14 @@ Deno.test({ AssetManager.instance.assets["bworld:textures_info"] = { "testmod:shaft": { x: 0, y: 0, width: 16, height: 16 }, }; - const model = buffer( - GPUBufferUsage.VERTEX, - pack_model([quad], [[1, 1, 1]], { width: 16, height: 16 } as Texture), - ); + const quads = instance_quads([quad], () => [1, 1, 1]); + const model = buffer(GPUBufferUsage.VERTEX, pack_model(quads, { width: 16, height: 16 } as Texture)); const indices = buffer(GPUBufferUsage.INDEX, Uint32Array.of(0, 1, 2, 0, 2, 3)); const camera = mat4.orthoZO(mat4.create(), 0, 1, 0, 1, -10, 10); // the red of the 2x2 pixels the block covers: top left, top right, bottom left, bottom right const render = async (time: number, rpm: number, offset: number) => { - const group = new InstanceGroup([quad], [[1, 1, 1]]); + const group = new InstanceGroup(quads); group.add({ group, index: -1, placement: mat4.create(), axis: [0, 0, 1], rpm, offset, light: 0xff }); device.queue.writeBuffer(uniforms, 0, Float32Array.of(...camera, time, 0, 0, 0)); const target = device.createTexture({