Better block models !

This commit is contained in:
2026-10-03 15:57:47 -03:00
parent ecc0295f6d
commit 24fe7cdede
23 changed files with 678 additions and 122 deletions
+1 -1
View File
@@ -127,7 +127,7 @@ export abstract class Entity {
// falls and moves by its velocity for one tick (see move_body), then slows down from drag and friction
move() {
const is_solid = (x: number, y: number, z: number) => this.level.has_collision(x, y, z);
const is_solid = (x: number, y: number, z: number) => this.level.collision_shape(x, y, z);
const can_step = this.#air_ticks <= this.step_grace_ticks && this.vy <= 0;
const friction = this.horizontal_friction();
const collisions = move_body(this, this.gravity, is_solid, this.step_height, can_step);
+3 -3
View File
@@ -157,7 +157,7 @@ export class LocalPlayer extends Player {
const was_on_ground = this.on_ground;
// not while jumping, so it can still jump off a ledge
if (this.sneaking && this.on_ground && this.vy <= 0) {
const is_solid = (x: number, y: number, z: number) => this.level.has_collision(x, y, z);
const is_solid = (x: number, y: number, z: number) => this.level.collision_shape(x, y, z);
const [dx, dz] = back_off_from_edge(
this,
this.vx * TICK_DELTA,
@@ -195,7 +195,7 @@ export class LocalPlayer extends Player {
vy: 0,
vz: 0,
};
if (box_is_free(standing, 0, 0, 0, (x, y, z) => this.level.has_collision(x, y, z))) this.set_swimming(false);
if (box_is_free(standing, 0, 0, 0, (x, y, z) => this.level.collision_shape(x, y, z))) this.set_swimming(false);
}
// turns up or down toward where it's looking. not up once its head is out, so it swims along the surface instead
@@ -232,7 +232,7 @@ export class LocalPlayer extends Player {
#hop_out_of_water(from_y: number) {
if (!this.colliding_x && !this.colliding_z) return;
const blocked = (x: number, y: number, z: number) =>
this.level.has_collision(x, y, z) || this.level.is_liquid(x, y, z);
this.level.is_liquid(x, y, z) || this.level.collision_shape(x, y, z);
const dy = from_y - this.y + this.vy * TICK_DELTA + WATER_HOP_HEIGHT;
if (box_is_free(this, this.vx * TICK_DELTA, dy, this.vz * TICK_DELTA, blocked)) this.vy = WATER_HOP;
}
+6 -4
View File
@@ -4,7 +4,8 @@ import type { Client } from "./client.ts";
import type { BlockHitResult } from "./level/client_level.ts";
import type { Container } from "$/common/inventory.ts";
import { AIR_ID } from "$/common/protocol.ts";
import { box_overlaps_block, can_place, placement_target } from "$/common/utils.ts";
import { box_overlaps_block, can_place, default_block_value, placement_target } from "$/common/utils.ts";
import { shape_at } from "$/common/block_shapes.ts";
import type { EntityJson } from "$/common/mod_data.ts";
import { RemoteEntity } from "./entity/remote_entity.ts";
import { Player } from "./entity/player.ts";
@@ -77,7 +78,7 @@ export class MultiPlayerGameMode {
place_block,
current === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", current),
below_id,
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z));
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block));
if (!block_info.interactive && place_id && placeable) {
level.add_block({ ...target, id: place_id });
const slot = this.#held_slot();
@@ -117,13 +118,14 @@ export class MultiPlayerGameMode {
// whether a mob's or player's collision box overlaps the block, the server doesn't let solid blocks go there. mobs
// are the mod entities that aren't scripted, players are this one and the others
#occupied(x: number, y: number, z: number) {
#occupied(x: number, y: number, z: number, block: BlockRegistry) {
const shape = shape_at(block, default_block_value(0, block));
for (const entity of this.client.level.entities.values()) {
const json = entity instanceof RemoteEntity
? EverythingRegistry.get<EntityJson>("entities", entity.type)
: undefined;
const blocks = entity instanceof Player || (json !== undefined && json.behavior !== "scripted");
if (blocks && box_overlaps_block(entity, x, y, z)) return true;
if (blocks && box_overlaps_block(entity, x, y, z, shape)) return true;
}
return false;
}
+46 -38
View File
@@ -20,6 +20,7 @@ import { crosses_planes } from "../workers/translucent_sort.ts";
import { Camera } from "../camera.ts";
import type { Entity } from "../entity/entity.ts";
import type { ModelJson } from "$/common/block_models.ts";
import { clip_shape, collision_shape_at, FULL_SHAPE, type Shape, shape_at } from "$/common/block_shapes.ts";
import type { ItemStack } from "$/common/inventory.ts";
export interface Block {
@@ -309,6 +310,16 @@ export class ClientLevel {
return block === VOID || (block !== AIR && (this.#blocks[block]?.has_collision ?? true));
}
// what entities bump into there, see common/physics.ts. unloaded chunks are full blocks, like has_collision
collision_shape(x: number, y: number, z: number): boolean | Shape {
const value = this.get_block_value(x, y, z);
const nid = value & ID_MASK;
if (nid === VOID) return true;
if (nid === AIR) return false;
const block = this.#blocks[nid];
return block ? collision_shape_at(block, value) : true;
}
// water, see is_liquid_block. unloaded chunks aren't
is_liquid(x: number, y: number, z: number) {
const block = this.get_block(x, y, z);
@@ -640,7 +651,8 @@ export class ClientLevel {
return closest;
}
// the first block along the view of something at x/y/z looking at yaw/pitch, like minecraft's pick
// the first block along the view of something at x/y/z looking at yaw/pitch, like minecraft's pick. it has to go
// into one of the block's boxes (see common/block_shapes.ts), so it looks past the empty half of a slab
pick(
x: number,
y: number,
@@ -651,55 +663,51 @@ export class ClientLevel {
step = 0.05,
): BlockHitResult | undefined {
const cos_pitch = Math.cos(pitch);
const dx = -Math.sin(yaw) * cos_pitch;
const dy = Math.sin(pitch);
const dz = -Math.cos(yaw) * cos_pitch;
const direction = [-Math.sin(yaw) * cos_pitch, Math.sin(pitch), -Math.cos(yaw) * cos_pitch];
const origin = [x, y, z];
let prev_bx = Math.floor(x);
let prev_by = Math.floor(y);
let prev_bz = Math.floor(z);
let dist = 0;
while (dist <= max_distance) {
x += dx * step;
y += dy * step;
z += dz * step;
dist += step;
const bx = Math.floor(x);
const by = Math.floor(y);
const bz = Math.floor(z);
// a little past the end, so a block whose cell the steps reach after max_distance is still tried
for (let dist = step; dist <= max_distance + step; dist += step) {
const bx = Math.floor(origin[0] + direction[0] * dist);
const by = Math.floor(origin[1] + direction[1] * dist);
const bz = Math.floor(origin[2] + direction[2] * dist);
if (bx === prev_bx && by === prev_by && bz === prev_bz) {
continue;
}
const block = this.get_block(bx, by, bz);
if (block && block !== AIR && block !== VOID) {
let face: Faces;
if (bx > prev_bx) {
face = "west";
} else if (bx < prev_bx) {
face = "east";
} else if (by > prev_by) {
face = "bottom";
} else if (by < prev_by) {
face = "top";
} else if (bz > prev_bz) {
face = "north";
} else {
face = "south";
}
return { x: bx, y: by, z: bz, face, block };
}
prev_bx = bx;
prev_by = by;
prev_bz = bz;
const value = this.get_block_value(bx, by, bz);
const block = value & ID_MASK;
if (block === AIR || block === VOID) {
continue;
}
const info = this.#blocks[block];
const hit = clip_shape(
info ? shape_at(info, value) : FULL_SHAPE,
bx,
by,
bz,
origin,
direction,
max_distance,
);
if (!hit) {
continue;
}
// the side of the box it went in by
const face: Faces = hit.axis === 0
? (hit.sign > 0 ? "west" : "east")
: hit.axis === 1
? (hit.sign > 0 ? "bottom" : "top")
: (hit.sign > 0 ? "north" : "south");
return { x: bx, y: by, z: bz, face, block };
}
return undefined;
+2 -1
View File
@@ -44,7 +44,8 @@ export class GameRenderer {
const level = this.level_renderer;
level.render_opaque(client.level, camera);
profiler.section("entities", () => {
level.render_destroy_progress(client.game_mode);
level.render_destroy_progress(client.level, client.game_mode);
level.render_block_outline(client.level, client.hit_result, camera);
level.render_entities(client.level, camera, client.player, partial_tick);
});
profiler.section("translucent", () => level.render_translucent(client.level, camera));
+200 -28
View File
@@ -19,30 +19,31 @@ import {
draw_terrain,
flush_batch,
get_current_texture,
push_back_face,
push_bottom_face,
push_front_face,
push_left_face,
push_right_face,
push_top_face,
push_vertex,
set_current_texture,
Texture,
view_projection,
white_tex,
} from "$/client/renderer/mod.ts";
import type { RenderLayer } from "$/common/everything_registry.ts";
import { type BlockRegistry, EverythingRegistry, type RenderLayer } from "$/common/everything_registry.ts";
import {
bake_model,
type BakedQuad,
block_variant,
BUILTIN_MODELS,
DEFAULT_MODEL,
FACE_INDEX,
find_model,
type ModelJson,
} from "$/common/block_models.ts";
import { ID_MASK } from "$/common/constants.ts";
import { type Shape, shape_at } from "$/common/block_shapes.ts";
import type { BlockHitResult } from "$/client/level/client_level.ts";
import { get_state_value } from "$/common/utils.ts";
import { FACE_GROUPS, UNALIGNED_GROUP } from "$/client/workers/chunk_messages.ts";
import { FACE_AXIS, FACE_NORMALS } from "$/client/workers/translucent_sort.ts";
import { Frustum } from "./frustum.ts";
const BREAKING_FACES = [
push_back_face,
push_bottom_face,
push_front_face,
push_left_face,
push_right_face,
push_top_face,
];
// draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities
export class LevelRenderer {
frustum = new Frustum();
@@ -154,8 +155,9 @@ export class LevelRenderer {
flush_batch();
}
// the cracks on the block being broken
render_destroy_progress(game_mode: MultiPlayerGameMode) {
// the cracks on the block being broken, drawn over its model's faces like minecraft's crumbling overlay, so a slab
// or a plant cracks where it is and not on a whole cube around it
render_destroy_progress(level: ClientLevel, game_mode: MultiPlayerGameMode) {
const block = game_mode.destroy_pos;
if (!block) {
return;
@@ -167,20 +169,190 @@ export class LevelRenderer {
return;
}
const value = level.get_block_value(block.x, block.y, block.z);
const info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", value & ID_MASK);
if (!info) {
return;
}
const tex = AssetManager.instance.get<Texture>("bworld:textures");
const region = get_sprite_region(`engine:break_${stage}`);
for (const push_face of BREAKING_FACES) {
push_face(
tex,
block.x,
block.y,
block.z,
region.x,
region.y,
region.width,
region.height,
for (const quad of this.#destroy_quads(info, value)) {
push_decal_quad(tex, quad, block.x, block.y, block.z, region);
}
}
// the edges of the shape of the block being looked at, like minecraft's block outline: thin dark lines that keep
// the same width on screen however far away it is
render_block_outline(level: ClientLevel, hit: BlockHitResult | undefined, camera: Camera) {
if (!hit) {
return;
}
const value = level.get_block_value(hit.x, hit.y, hit.z);
const info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", value & ID_MASK);
if (!info) {
return;
}
const previous = get_current_texture();
flush_batch();
set_current_texture(white_tex!);
const eye = [camera.x, camera.y, camera.z];
for (const edge of shape_edges(shape_at(info, value))) {
push_line(
[hit.x + edge[0], hit.y + edge[1], hit.z + edge[2]],
[hit.x + edge[3], hit.y + edge[4], hit.z + edge[5]],
eye,
);
}
flush_batch();
if (previous) set_current_texture(previous);
}
// the block's model at a value, baked once
#destroy_quads(block: BlockRegistry, value: number): BakedQuad[] {
const key = block.variants ? value : value & ID_MASK;
let quads = this.#baked.get(key);
if (!quads) {
const states: Record<string, number> = {};
for (const state of block.states ?? []) states[state.name] = get_state_value(value, block, state.name)!;
const variant = block_variant(block, states);
const models = Object.fromEntries(EverythingRegistry.entries<ModelJson>("models"));
const model = find_model(variant.model, models) ?? BUILTIN_MODELS[DEFAULT_MODEL];
quads = bake_model(model, variant.textures, variant.y);
this.#baked.set(key, quads);
}
return quads;
}
#baked = new Map<number, BakedQuad[]>();
}
// minecraft's outline is black at 40%
const OUTLINE_COLOR = [0, 0, 0, 0.4] as const;
// half the line's width for each block it is away from the camera, about a pixel on a 1080p screen
const OUTLINE_HALF_WIDTH = 0.0012;
// how far out the outline is from the block's faces, so they don't hide it
const OUTLINE_GROW = 0.002;
// the 12 edges of each box of a shape, grown out a little, as [x1, y1, z1, x2, y2, z2]. edges two boxes share are
// drawn once
export function shape_edges(shape: Shape): number[][] {
const edges = new Map<string, number[]>();
for (const box of shape) {
const min = [box[0] - OUTLINE_GROW, box[1] - OUTLINE_GROW, box[2] - OUTLINE_GROW];
const max = [box[3] + OUTLINE_GROW, box[4] + OUTLINE_GROW, box[5] + OUTLINE_GROW];
// along each axis, from each of the 4 corners of the box's face at the low end of it
for (let axis = 0; axis < 3; axis++) {
const [a, b] = [(axis + 1) % 3, (axis + 2) % 3];
for (const [ea, eb] of [[0, 0], [0, 1], [1, 0], [1, 1]]) {
const from = [0, 0, 0];
from[axis] = min[axis];
from[a] = ea ? max[a] : min[a];
from[b] = eb ? max[b] : min[b];
const to = [...from];
to[axis] = max[axis];
const edge = [...from, ...to];
edges.set(edge.map((v) => v.toFixed(4)).join(","), edge);
}
}
}
return [...edges.values()];
}
// a line from a to b as a thin quad turned to face the eye, as wide on screen at both ends
function push_line(a: number[], b: number[], eye: number[]) {
const direction = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
const length = Math.hypot(direction[0], direction[1], direction[2]);
if (length === 0) return;
const mid = [(a[0] + b[0]) / 2 - eye[0], (a[1] + b[1]) / 2 - eye[1], (a[2] + b[2]) / 2 - eye[2]];
// across the line and across the view
const side = [
direction[1] * mid[2] - direction[2] * mid[1],
direction[2] * mid[0] - direction[0] * mid[2],
direction[0] * mid[1] - direction[1] * mid[0],
];
const side_length = Math.hypot(side[0], side[1], side[2]);
if (side_length === 0) return;
// each end as wide as its distance needs, and a half width longer so lines meet at the corners
const end = (point: number[], sign: number) => {
const distance = Math.hypot(point[0] - eye[0], point[1] - eye[1], point[2] - eye[2]);
const half = OUTLINE_HALF_WIDTH * distance;
const p = point.map((v, i) => v + direction[i] / length * half * sign);
const s = side.map((v) => v / side_length * half);
return [p.map((v, i) => v - s[i]), p.map((v, i) => v + s[i])];
};
const [a0, a1] = end(a, -1);
const [b0, b1] = end(b, 1);
const [r, g, bl, alpha] = OUTLINE_COLOR;
const vertex = (p: number[]) => push_vertex(p[0], p[1], p[2], 0, 0, r, g, bl, alpha);
// both ways round, since which way it faces depends on where the eye is
for (const corners of [[a0, b0, b1, a1], [a1, b1, b0, a0]]) {
vertex(corners[0]);
vertex(corners[1]);
vertex(corners[2]);
vertex(corners[0]);
vertex(corners[2]);
vertex(corners[3]);
}
}
// how far out from the face the cracks are drawn, so they don't fight the block's own face for depth
const DECAL_OFFSET = 1e-3;
// a quad of a block's model with a texture laid over it the way it lies on a full block's face, like minecraft's
// SheetedDecalTextureGenerator: the texture doesn't stretch to the quad, the quad shows the part of it where it is
function push_decal_quad(
texture: Texture,
quad: BakedQuad,
x: number,
y: number,
z: number,
region: { x: number; y: number; width: number; height: number },
) {
const p = quad.positions;
const e1 = [p[3] - p[0], p[4] - p[1], p[5] - p[2]];
const e2 = [p[9] - p[0], p[10] - p[1], p[11] - p[2]];
const normal = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
const length = Math.hypot(normal[0], normal[1], normal[2]) || 1;
const offset = normal.map((n) => n / length * DECAL_OFFSET);
const pad = 0.5;
const corner = (k: number) => {
const [px, py, pz] = [p[k * 3], p[k * 3 + 1], p[k * 3 + 2]];
const [u, v] = decal_uv(quad.face, px, py, pz).map((t) => Math.min(Math.max(t, 0), 1));
push_vertex(
x + px + offset[0],
y + py + offset[1],
z + pz + offset[2],
(region.x + pad + u * (region.width - 2 * pad)) / texture.width,
(region.y + pad + v * (region.height - 2 * pad)) / texture.height,
);
};
corner(0);
corner(1);
corner(2);
corner(0);
corner(2);
corner(3);
}
// where a point on a face is on the texture, 0 to 1, the same way default model uvs wrap a texture around the block
function decal_uv(face: number, x: number, y: number, z: number): [number, number] {
switch (face) {
case FACE_INDEX.top:
return [x, z];
case FACE_INDEX.bottom:
return [x, 1 - z];
case FACE_INDEX.south:
return [x, 1 - y];
case FACE_INDEX.north:
return [1 - x, 1 - y];
case FACE_INDEX.west:
return [z, 1 - y];
default:
return [1 - z, 1 - y];
}
}