Fluid and item visuals
This commit is contained in:
+26
-14
@@ -43,7 +43,7 @@ let canvas_format: GPUTextureFormat;
|
||||
let pipeline_2d: GPURenderPipeline;
|
||||
let pipeline_3d: GPURenderPipeline;
|
||||
let terrain_pipelines: Record<RenderLayer, GPURenderPipeline>;
|
||||
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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<Texture>("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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
+243
-62
@@ -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<string, ModelJson>;
|
||||
// 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<string, InstanceGroup>();
|
||||
#block_groups = new Map<number, InstanceGroup>();
|
||||
#item_groups = new Map<string, InstanceGroup>();
|
||||
// a fluid box's model is its own, and goes with it
|
||||
#fluid_groups = new Set<InstanceGroup>();
|
||||
|
||||
constructor(level: VisualsLevel) {
|
||||
this.#level = level;
|
||||
@@ -167,6 +210,8 @@ export class Visuals {
|
||||
*groups(): Iterable<InstanceGroup> {
|
||||
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<ModelJson>("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<ModelJson>("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<FluidJson>("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<vec3>) {
|
||||
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<ArrayBuffer> {
|
||||
export function pack_model(quads: InstanceQuad[], atlas: Texture): Uint8Array<ArrayBuffer> {
|
||||
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));
|
||||
|
||||
Reference in New Issue
Block a user