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];
}
}
+17 -4
View File
@@ -48,6 +48,9 @@ export interface BlockVariant {
textures?: BlockTextures;
// turns the model around the vertical axis, clockwise seen from above: 0, 90, 180 or 270
y?: number;
// what the player points at and bumps into, as boxes in pixels: [x1, y1, z1, x2, y2, z2]. the model's boxes when
// not set, see common/block_shapes.ts
shape?: number[][];
}
export const DEFAULT_MODEL = "engine:cube";
@@ -142,21 +145,31 @@ export function texture_variables(reference: string, textures: BlockTextures | u
return variables;
}
// the block's model, textures and turn for a value with state bits. each comes from the first variant whose conditions
// the block's model, textures, turn and shape for a value with state bits. each comes from the first variant whose conditions
// match that sets it, so "lit=1" can change the textures and "facing=1" the turn of the same block
export function block_variant(block: BlockRegistry, states?: Record<string, number>): Required<BlockVariant> {
export function block_variant(
block: BlockRegistry,
states?: Record<string, number>,
): Required<Omit<BlockVariant, "shape">> & Pick<BlockVariant, "shape"> {
let model: string | undefined;
let textures: BlockTextures | undefined;
let y: number | undefined;
let shape: number[][] | undefined;
if (block.variants && states) {
for (const [condition, override] of Object.entries(block.variants)) {
if (!variant_matches(condition, states)) continue;
model ??= override.model;
textures ??= override.textures;
y ??= override.y;
shape ??= override.shape;
}
}
return { model: model ?? block.model ?? DEFAULT_MODEL, textures: textures ?? block.textures, y: y ?? 0 };
return {
model: model ?? block.model ?? DEFAULT_MODEL,
textures: textures ?? block.textures,
y: y ?? 0,
shape: shape ?? block.shape,
};
}
// "age=7" or "age=7,facing=2", "" matches everything
@@ -300,7 +313,7 @@ export function bake_model(model: ModelJson, textures: BlockTextures | undefined
}
// turns a point (in block space) by the element's rotation
function element_rotation(element: ModelElementJson): (point: number[]) => number[] {
export function element_rotation(element: ModelElementJson): (point: number[]) => number[] {
const rotation = element.rotation;
if (!rotation || rotation.angle === 0) return (point) => point;
+136
View File
@@ -0,0 +1,136 @@
// a block's shape, like minecraft's VoxelShape: the boxes it's made of. it's what the player points at and what the
// cracks are drawn on when it breaks (minecraft's getShape), and what entities bump into when it has collision
// (getCollisionShape). blocks get theirs from the boxes of their model, or set "shape" like minecraft's Block.box
import { block_variant, element_rotation, find_model, type ModelJson } from "./block_models.ts";
import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts";
import { get_state_value } from "./utils.ts";
// min x y z then max x y z, in block space (0 to 1)
export type Box = readonly [number, number, number, number, number, number];
export type Shape = readonly Box[];
export const FULL_SHAPE: Shape = [[0, 0, 0, 1, 1, 1]];
export const EMPTY_SHAPE: Shape = [];
// thinner than this on some axis is a flat plane, like the cross model's, not a box
const FLAT = 1e-4;
// the boxes of a model's elements, turned like the model is. elements turned by their own rotation take the box
// around them. flat planes (plants) aren't boxes, so a model made only of planes gets one box around all of them
export function model_shape(model: ModelJson, y_rotation = 0): Shape {
const boxes: Box[] = [];
let bounds: Box | undefined;
for (const element of model.elements) {
const rotate = element_rotation(element);
const min = [Infinity, Infinity, Infinity];
const max = [-Infinity, -Infinity, -Infinity];
for (let corner = 0; corner < 8; corner++) {
const point = rotate(
[0, 1, 2].map((axis) => ((corner >> axis) & 1 ? element.to[axis] : element.from[axis]) / 16),
);
for (let axis = 0; axis < 3; axis++) {
min[axis] = Math.min(min[axis], point[axis]);
max[axis] = Math.max(max[axis], point[axis]);
}
}
const box = clamp([...min, ...max]);
bounds = bounds ? clamp(bounds.map((v, i) => (i < 3 ? Math.min : Math.max)(v, box[i]))) : box;
if ([0, 1, 2].every((axis) => box[axis + 3] - box[axis] > FLAT)) boxes.push(box);
}
if (boxes.length === 0 && bounds) boxes.push(bounds);
return boxes.map((box) => turn(box, y_rotation));
}
// boxes in pixels, like a block's "shape" ([x1, y1, z1, x2, y2, z2], 0 to 16), turned like the model is
export function pixel_shape(boxes: number[][], y_rotation = 0): Shape {
return boxes.map((box) => turn(clamp(box.map((v) => v / 16)), y_rotation));
}
// what the block is at a value with state bits: its "shape" when it (or a variant) sets one, otherwise its model's
export function block_shape(block: BlockRegistry, states?: Record<string, number>): Shape {
const variant = block_variant(block, states);
if (variant.shape) return pixel_shape(variant.shape, variant.y);
const model = find_model(variant.model, Object.fromEntries(EverythingRegistry.entries<ModelJson>("models")));
return model ? model_shape(model, variant.y) : FULL_SHAPE;
}
// shapes by block, then by value with state bits, worked out the first time they're asked for
const cache = new WeakMap<BlockRegistry, Map<number, Shape>>();
// the block's shape at a value from the world, see block_shape
export function shape_at(block: BlockRegistry, value: number): Shape {
let shapes = cache.get(block);
if (!shapes) cache.set(block, shapes = new Map());
const key = block.variants ? value : 0;
let shape = shapes.get(key);
if (!shape) {
let states: Record<string, number> | undefined;
if (block.variants && block.states) {
states = {};
for (const state of block.states) states[state.name] = get_state_value(value, block, state.name)!;
}
shape = block_shape(block, states);
shapes.set(key, shape);
}
return shape;
}
// what entities bump into, like getCollisionShape: the shape, or nothing for blocks with "collision": false
export function collision_shape_at(block: BlockRegistry, value: number): Shape {
return block.has_collision ? shape_at(block, value) : EMPTY_SHAPE;
}
// how far along the ray (origin plus direction times distance) it first goes into one of the boxes of a block at
// x, y, z, and the side it went in by as the axis and which way along it the ray was going. undefined if it misses
export function clip_shape(
shape: Shape,
x: number,
y: number,
z: number,
origin: number[],
direction: number[],
max_distance: number,
): { distance: number; axis: number; sign: number } | undefined {
const offset = [x, y, z];
let closest: { distance: number; axis: number; sign: number } | undefined;
for (const box of shape) {
let enter = 0;
let enter_axis = -1;
let leave = closest?.distance ?? max_distance;
for (let axis = 0; axis < 3 && enter <= leave; axis++) {
const min = offset[axis] + box[axis];
const max = offset[axis] + box[axis + 3];
if (Math.abs(direction[axis]) < 1e-9) {
if (origin[axis] < min || origin[axis] > max) enter = Infinity;
continue;
}
const a = (min - origin[axis]) / direction[axis];
const b = (max - origin[axis]) / direction[axis];
if (Math.min(a, b) >= enter) {
enter = Math.min(a, b);
enter_axis = axis;
}
leave = Math.min(leave, Math.max(a, b));
}
if (enter <= leave && enter_axis >= 0) {
closest = { distance: enter, axis: enter_axis, sign: Math.sign(direction[enter_axis]) };
}
}
return closest;
}
function clamp(box: number[]): Box {
const c = box.map((v) => Math.min(Math.max(v, 0), 1));
return [c[0], c[1], c[2], c[3], c[4], c[5]];
}
// clockwise seen from above by 0, 90, 180 or 270 degrees, the same as bake_model turns quads
function turn(box: Box, y_rotation: number): Box {
const turns = ((Math.round(y_rotation / 90) % 4) + 4) % 4;
let [x1, y1, z1, x2, y2, z2] = box;
for (let t = 0; t < turns; t++) {
// a point (x, z) goes to (1 - z, x)
[x1, z1, x2, z2] = [1 - z2, x1, 1 - z1, x2];
}
return [x1, y1, z1, x2, y2, z2];
}
+2
View File
@@ -119,6 +119,8 @@ export interface BlockRegistry {
alpha?: number;
has_collision: boolean;
// boxes in pixels, see BlockVariant.shape
shape?: number[][];
toughness?: number;
requires_tool?: boolean;
tool_to_break?: string;
+18 -1
View File
@@ -55,6 +55,7 @@ export interface BlockJson {
transparent?: boolean;
alpha?: number;
collision?: boolean;
shape?: number[][];
mining?: { toughness: number; tool?: string; requires_tool?: boolean; tier?: number };
drops?: string;
item?: boolean;
@@ -267,6 +268,7 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso
if (block.light_opacity !== undefined) json.light_opacity = block.light_opacity;
if (block.alpha !== undefined) json.alpha = block.alpha;
if (!block.has_collision) json.collision = false;
if (block.shape !== undefined) json.shape = block.shape;
if (block.toughness !== undefined) {
json.mining = { toughness: block.toughness };
if (block.tool_to_break !== undefined) json.mining.tool = block.tool_to_break;
@@ -294,6 +296,7 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it
if (json.name !== undefined) block.name = json.name;
if (json.model !== undefined) block.model = json.model;
if (json.variants !== undefined) block.variants = json.variants;
if (json.shape !== undefined) block.shape = json.shape;
const render_layer = json.render_layer ?? (json.transparent ? "translucent" : undefined);
if (render_layer && render_layer !== "solid") block.render_layer = render_layer;
if (json.cull_same !== undefined) block.cull_same = json.cull_same;
@@ -474,7 +477,7 @@ export function validate_block(json: unknown): Problems {
}
}
if (!is_object(variant)) {
problems.push(`${where} must be { model, textures, y }`);
problems.push(`${where} must be { model, textures, y, shape }`);
continue;
}
if (variant.model !== undefined) problems.push(...validate_id(variant.model, `${where}.model`));
@@ -484,9 +487,11 @@ export function validate_block(json: unknown): Problems {
if (variant.y !== undefined && ![0, 90, 180, 270].includes(variant.y as number)) {
problems.push(`${where}.y must be 0, 90, 180 or 270`);
}
if (variant.shape !== undefined) problems.push(...validate_shape(variant.shape, `${where}.shape`));
}
}
}
if (json.shape !== undefined) problems.push(...validate_shape(json.shape, "shape"));
if (json.render_layer !== undefined && !RENDER_LAYERS.includes(json.render_layer as RenderLayer)) {
problems.push(`render_layer must be one of ${RENDER_LAYERS.join(", ")}`);
}
@@ -549,6 +554,18 @@ export function validate_block(json: unknown): Problems {
return problems;
}
// boxes in pixels: [[x1, y1, z1, x2, y2, z2], ...], each corner from 0 to 16 and the second past the first
function validate_shape(shape: unknown, where: string): Problems {
const is_box = (box: unknown) =>
Array.isArray(box) && box.length === 6 &&
box.every((v) => typeof v === "number" && v >= 0 && v <= 16) &&
box[0] <= box[3] && box[1] <= box[4] && box[2] <= box[5];
if (!Array.isArray(shape) || shape.length === 0 || !shape.every(is_box)) {
return [`${where} must be a list of boxes in pixels, like [[0, 0, 0, 16, 8, 16]]`];
}
return [];
}
export function validate_model(json: unknown): Problems {
if (!is_object(json)) return ["model must be an object"];
const problems = validate_id(json.id, "id");
+41 -16
View File
@@ -1,11 +1,20 @@
// collision against blocks, shared by the client's entities and the server's, so both move things the same way
import { TICK_DELTA } from "./constants.ts";
import { EMPTY_SHAPE, FULL_SHAPE, type Shape } from "./block_shapes.ts";
// how far inside a block face still counts as touching it, so boxes resting exactly on a face don't snag
const EPSILON = 1e-7;
// the two axes that aren't the one being moved along
const OTHER_AXES = [[1, 2], [0, 2], [0, 1]] as const;
// what a body bumps into at a block: its collision shape (see common/block_shapes.ts), or true for a full block and
// false for nothing
export type BlockCollision = (x: number, y: number, z: number) => boolean | Shape;
function shape_of(collision: boolean | Shape): Shape {
return collision === true ? FULL_SHAPE : collision === false ? EMPTY_SHAPE : collision;
}
// something with a box that moves. position is the middle of its feet, velocity is in blocks per second
export interface Body {
x: number;
@@ -36,7 +45,7 @@ export interface Collisions {
export function move_body(
body: Body,
gravity: number,
is_solid: (x: number, y: number, z: number) => boolean,
is_solid: BlockCollision,
step_height = 0,
on_ground = false,
) {
@@ -82,7 +91,7 @@ function sweep(
max: number[],
wanted: number[],
axes: number[],
is_solid: (x: number, y: number, z: number) => boolean,
is_solid: BlockCollision,
) {
const moved = [0, 0, 0];
for (const axis of axes) {
@@ -101,7 +110,7 @@ function step_up(
max: number[],
wanted: number[],
step_height: number,
is_solid: (x: number, y: number, z: number) => boolean,
is_solid: BlockCollision,
) {
const up = sweep(min, max, [0, step_height, 0], [1], is_solid)[1];
const across = sweep(min, max, wanted, horizontal_order(wanted), is_solid);
@@ -109,13 +118,13 @@ function step_up(
return [across[0], up + down, across[2]];
}
// how far the box can go along an axis before it runs into a block
// how far the box can go along an axis before it runs into a block's shape
function clip(
min: number[],
max: number[],
axis: number,
distance: number,
is_solid: (x: number, y: number, z: number) => boolean,
is_solid: BlockCollision,
) {
if (distance === 0) {
return 0;
@@ -132,13 +141,21 @@ function clip(
position[axis] = i;
position[a] = j;
position[b] = k;
if (!is_solid(position[0], position[1], position[2])) {
continue;
}
if (distance > 0 && i >= max[axis] - EPSILON) {
distance = Math.min(distance, i - max[axis]);
} else if (distance < 0 && i + 1 <= min[axis] + EPSILON) {
distance = Math.max(distance, i + 1 - min[axis]);
for (const box of shape_of(is_solid(position[0], position[1], position[2]))) {
// only boxes beside the body on the other two axes are in the way
if (
position[a] + box[a] >= max[a] - EPSILON || position[a] + box[a + 3] <= min[a] + EPSILON ||
position[b] + box[b] >= max[b] - EPSILON || position[b] + box[b + 3] <= min[b] + EPSILON
) {
continue;
}
const box_min = i + box[axis];
const box_max = i + box[axis + 3];
if (distance > 0 && box_min >= max[axis] - EPSILON) {
distance = Math.min(distance, box_min - max[axis]);
} else if (distance < 0 && box_max <= min[axis] + EPSILON) {
distance = Math.max(distance, box_max - min[axis]);
}
}
}
}
@@ -153,7 +170,7 @@ export function back_off_from_edge(
dx: number,
dz: number,
drop: number,
is_solid: (x: number, y: number, z: number) => boolean,
is_solid: BlockCollision,
): [number, number] {
const step = 0.05;
const toward_zero = (d: number) => Math.abs(d) <= step ? 0 : d - Math.sign(d) * step;
@@ -178,7 +195,7 @@ export function box_is_free(
dx: number,
dy: number,
dz: number,
is_blocked: (x: number, y: number, z: number) => boolean,
is_blocked: BlockCollision,
): boolean {
const half = body.width / 2;
const min = [body.x - half + dx, body.y + dy, body.z - half + dz];
@@ -186,11 +203,19 @@ export function box_is_free(
return !overlaps_solid(min, max, is_blocked);
}
function overlaps_solid(min: number[], max: number[], is_solid: (x: number, y: number, z: number) => boolean) {
function overlaps_solid(min: number[], max: number[], is_solid: BlockCollision) {
for (let x = Math.floor(min[0] + EPSILON); x <= Math.floor(max[0] - EPSILON); x++) {
for (let y = Math.floor(min[1] + EPSILON); y <= Math.floor(max[1] - EPSILON); y++) {
for (let z = Math.floor(min[2] + EPSILON); z <= Math.floor(max[2] - EPSILON); z++) {
if (is_solid(x, y, z)) return true;
for (const box of shape_of(is_solid(x, y, z))) {
if (
x + box[0] < max[0] - EPSILON && x + box[3] > min[0] + EPSILON &&
y + box[1] < max[1] - EPSILON && y + box[4] > min[1] + EPSILON &&
z + box[2] < max[2] - EPSILON && z + box[5] > min[2] + EPSILON
) {
return true;
}
}
}
}
}
+9 -4
View File
@@ -1,6 +1,7 @@
import { ID_MASK, STATE_SHIFT } from "./constants.ts";
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "./everything_registry.ts";
import { block_item_texture, cube_face_texture } from "./block_models.ts";
import { FULL_SHAPE, type Shape } from "./block_shapes.ts";
import type { ItemStack } from "./inventory.ts";
import { list_matches } from "./tags.ts";
@@ -163,17 +164,21 @@ export function can_place(
return in_ok && can_stand_on(block, below);
}
// whether an entity's collision box, centered on x and z with its feet at y, overlaps the block at bx, by, bz
// whether an entity's collision box, centered on x and z with its feet at y, overlaps the block at bx, by, bz. only
// the block's boxes count when given its shape, so a slab's empty half doesn't
export function box_overlaps_block(
entity: { x: number; y: number; z: number; width: number; height: number },
bx: number,
by: number,
bz: number,
shape: Shape = FULL_SHAPE,
): boolean {
const half = entity.width / 2;
return entity.x + half > bx && entity.x - half < bx + 1 &&
entity.y + entity.height > by && entity.y < by + 1 &&
entity.z + half > bz && entity.z - half < bz + 1;
return shape.some((box) =>
entity.x + half > bx + box[0] && entity.x - half < bx + box[3] &&
entity.y + entity.height > by + box[1] && entity.y < by + box[4] &&
entity.z + half > bz + box[2] && entity.z - half < bz + box[5]
);
}
// numeric so looking chunks up doesnt allocate a string every time, fine for |x|, |z| < 32768
+2 -1
View File
@@ -52,6 +52,7 @@ there will be holes in the world behind them.
| Field | Default | Meaning |
| ---------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `collision` | `true` | Whether entities bump into it. Plants and water set `false`. |
| `shape` | its model | The boxes players point at and entities bump into, in pixels. See [Shapes](../resources/models.md#shapes). |
| `mining.toughness` | unbreakable | Seconds to break by hand. Without `mining`, a block can't be broken. |
| `mining.tool` | none | The [tool type](../items/tools.md) that breaks it faster, like `pickaxe`, `axe` or `shovel`. |
| `mining.requires_tool` | `false` | Only drops when broken with `mining.tool`. |
@@ -86,7 +87,7 @@ It's only placed when:
- the spot is one it can go into: air or a `replaceable` block, or one of `place_in`,
- the block under the spot is one of `place_on`, when the block has `place_on`,
- and, for blocks with collision, no player or mob is in the way.
- and, for blocks with collision, no player or mob is in the way of its [shape](../resources/models.md#shapes).
A block with `place_on` also pops off (dropping what it drops) when the block under it becomes something else, like a
crop when its farmland is dug up.
+4 -4
View File
@@ -58,10 +58,10 @@ a texture per growth stage:
- A key is a condition on the block's states: `"age=3"`, or `"age=3,facing=1"` when all of them have to match. `""`
matches always.
- A variant sets any of `model`, `textures` and `y`, a turn around the vertical axis of 0, 90, 180 or 270 degrees,
clockwise seen from above.
- **Each of the three comes from the first matching variant that sets it.** So one variant can turn the block and a
later one change its textures, and both apply.
- A variant sets any of `model`, `textures`, `y`, a turn around the vertical axis of 0, 90, 180 or 270 degrees,
clockwise seen from above, and [`shape`](../resources/models.md#shapes).
- **Each of them comes from the first matching variant that sets it.** So one variant can turn the block and a later one
change its textures, and both apply.
- What no matching variant sets comes from the block itself.
## Facing
+34
View File
@@ -77,6 +77,40 @@ every face, since `top` and `bottom` default to `#side`.
Faces are only drawn from the front, so a flat plane that should be seen from both sides needs a face each way.
## Shapes
A block's shape is the boxes it's made of, like Minecraft's `VoxelShape`. It's what players point at, so they can look
past the empty half of a slab, what the cracks are drawn on while it's being broken, and, unless the block sets
`"collision": false`, what entities bump into and stand on. A block that's only half there can't be placed where a
player is standing in its other half, either.
By default it comes from the model: one box per element, turned with the block's `y`. An element turned by its own
`rotation` gets the box around it. Elements that are flat planes aren't boxes, so a model made only of planes, like
`engine:cross` and `engine:crop`, gets one box around all of them, which is what players point at to break the plant.
A block can set its own with `shape`, a list of boxes in pixels like `from` and `to` put together, as Minecraft's
`Block.box` does. That's for a shape simpler than the model, or one that's different from what's drawn, like a flower
pot's plant you can't click on. `shape` is turned with the block's `y` too, and [variants](../blocks/states.md) can set
their own, like a crop that's taller the older it is:
```json
{
"id": "copper_tools:rice",
"model": "engine:crop",
"textures": { "crop": "copper_tools:rice_3" },
"collision": false,
"states": [{ "name": "age", "bits": 2, "default": 0 }],
"shape": [[0, 0, 0, 16, 16, 16]],
"variants": {
"age=0": { "textures": { "crop": "copper_tools:rice_0" }, "shape": [[0, 0, 0, 16, 4, 16]] },
"age=1": { "textures": { "crop": "copper_tools:rice_1" }, "shape": [[0, 0, 0, 16, 8, 16]] },
"age=2": { "textures": { "crop": "copper_tools:rice_2" }, "shape": [[0, 0, 0, 16, 12, 16]] }
}
}
```
Boxes stay inside the block, from 0 to 16, so a shape can't be taller than a block like Minecraft's fences.
## Lighting
Faces flat against the block's edge get smooth lighting and ambient occlusion like a full block's. Anything inside the
@@ -10,6 +10,7 @@
"parts": "farmersdelight:cooking_pot_parts"
},
"render_layer": "cutout",
"shape": [[2, 0, 2, 14, 10, 14]],
"mining": {
"toughness": 2,
"tool": "pickaxe"
@@ -12,7 +12,7 @@
"facing=3": { "y": 270 }
},
"render_layer": "cutout",
"collision": false,
"shape": [[1, 0, 1, 15, 1, 15]],
"mining": {
"toughness": 2,
"tool": "axe"
+4 -1
View File
@@ -7,6 +7,7 @@
import { TICKS_PER_SECOND } from "$/common/constants.ts";
import type { BlockRegistry } from "$/common/everything_registry.ts";
import type { ItemStack } from "$/common/inventory.ts";
import type { Shape } from "$/common/block_shapes.ts";
import { type Collisions, eyes_in_water, in_water, move_body } from "$/common/physics.ts";
import type { EntityData, EntityEvent, EntityInfo } from "$/common/protocol.ts";
import type { ServerPlayer } from "../player.ts";
@@ -62,6 +63,8 @@ export function damage_source(cause: string): DamageSource {
export interface EntityLevel {
readonly current_tick: number;
has_collision(x: number, y: number, z: number): boolean;
// what it bumps into at a block, see common/physics.ts
collision_shape(x: number, y: number, z: number): boolean | Shape;
// water, and other blocks you're in instead of on
is_liquid(x: number, y: number, z: number): boolean;
get_block_info(x: number, y: number, z: number): BlockRegistry | undefined;
@@ -254,7 +257,7 @@ export abstract class Entity {
// falls and moves by its velocity for one tick (see move_body), and counts how far it fell. returns what it hit
move(): Collisions {
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 from_y = this.y;
const collisions = move_body(
this,
+4
View File
@@ -89,6 +89,10 @@ export class EntityManager implements EntityLevel {
return this.#host.world.has_collision(x, y, z);
}
collision_shape(x: number, y: number, z: number) {
return this.#host.world.collision_shape(x, y, z);
}
is_liquid(x: number, y: number, z: number) {
return is_liquid_block(this.#host.world.get_block_info(x, y, z));
}
+11 -8
View File
@@ -23,6 +23,7 @@ import type { WorldgenSetup } from "$/common/generation.ts";
import { MAX_VIEW_DISTANCE, MIN_VIEW_DISTANCE } from "$/common/chunk_streaming.ts";
import { CYCLE_TICKS, format_clock, time_of_day, TIMES_OF_DAY } from "$/common/time.ts";
import {
block_value,
box_overlaps_block,
can_place,
can_stand_on,
@@ -31,6 +32,7 @@ import {
placement_target,
set_state_value,
} from "$/common/utils.ts";
import { type Shape, shape_at } from "$/common/block_shapes.ts";
import { EXHAUSTION } from "./vitals.ts";
import { ModRuntime, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
import {
@@ -1007,10 +1009,10 @@ export class GameServer {
return;
}
// solid blocks can't go where a mob or player is, the one placing it included, like minecraft
if (
EverythingRegistry.get<BlockRegistry>("blocks", held.block_id)?.has_collision &&
this.#occupied(tx, ty, tz)
) {
const state = placed_state(held.block_id, player);
const placing = EverythingRegistry.get<BlockRegistry>("blocks", held.block_id);
const value = state === undefined ? default_block_value(0, placing) : block_value(0, state);
if (placing?.has_collision && this.#occupied(tx, ty, tz, shape_at(placing, value))) {
this.#correct(player, tx, ty, tz);
return;
}
@@ -1028,22 +1030,23 @@ export class GameServer {
return;
}
this.set_block(tx, ty, tz, held.block_id, player, placed_state(held.block_id, player));
this.set_block(tx, ty, tz, held.block_id, player, state);
held_slot.amount = held_slot.amount! - 1;
this.mods.after.block_place.emit(place);
}
// whether a mob's or player's collision box overlaps the block at x, y, z
#occupied(x: number, y: number, z: number) {
// whether a mob's or player's collision box overlaps a block with that shape at x, y, z
#occupied(x: number, y: number, z: number, shape: Shape) {
return this.players().some((player) =>
box_overlaps_block(
{ x: player.x, y: player.y, z: player.z, width: PLAYER_WIDTH, height: player.height },
x,
y,
z,
shape,
)
) || this.entities.entities_near(x + 0.5, y, z + 0.5, 3).some((entity) =>
entity instanceof Mob && box_overlaps_block(entity, x, y, z)
entity instanceof Mob && box_overlaps_block(entity, x, y, z, shape)
);
}
+9
View File
@@ -9,6 +9,7 @@ import { generate_raw_chunk, RawChunk, WorldgenSetup } from "$/common/generation
import { AIR_ID, BlockChange } from "$/common/protocol.ts";
import { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
import { LruMap } from "./lru.ts";
import { collision_shape_at, EMPTY_SHAPE, type Shape } from "$/common/block_shapes.ts";
import { CYCLE_TICKS } from "$/common/time.ts";
import { encode_level_chunk } from "$/common/chunk_streaming.ts";
import type { ItemData } from "$/common/inventory.ts";
@@ -158,6 +159,14 @@ export class ServerWorld {
return this.get_block_info(x, y, z)?.has_collision ?? false;
}
// what entities bump into there, see common/physics.ts
collision_shape(x: number, y: number, z: number): Shape {
const value = this.get_block_value(x, y, z);
const nid = value & ID_MASK;
const block = nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
return block ? collision_shape_at(block, value) : EMPTY_SHAPE;
}
get_block_info(x: number, y: number, z: number): BlockRegistry | undefined {
const nid = this.get_block_nid(x, y, z);
return nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
+120
View File
@@ -0,0 +1,120 @@
import { assert, assertAlmostEquals, assertEquals } from "@std/assert";
import { BUILTIN_MODELS, type ModelJson } from "$/common/block_models.ts";
import {
block_shape,
clip_shape,
collision_shape_at,
EMPTY_SHAPE,
FULL_SHAPE,
model_shape,
type Shape,
} from "$/common/block_shapes.ts";
import { block_from_json, validate_block } from "$/common/mod_data.ts";
import { move_body } from "$/common/physics.ts";
import { box_overlaps_block } from "$/common/utils.ts";
const slab: ModelJson = {
id: "test:slab",
elements: [{ from: [0, 0, 0], to: [16, 8, 16], faces: { top: { texture: "#side" } } }],
};
const SLAB: Shape = [[0, 0, 0, 1, 0.5, 1]];
Deno.test("a model's shape is the boxes of its elements", () => {
assertEquals(model_shape(BUILTIN_MODELS["engine:cube"]), FULL_SHAPE);
assertEquals(model_shape(slab), SLAB);
const stairs: ModelJson = {
id: "test:stairs",
elements: [
{ from: [0, 0, 0], to: [16, 8, 16], faces: {} },
{ from: [0, 8, 8], to: [16, 16, 16], faces: {} },
],
};
assertEquals(model_shape(stairs), [[0, 0, 0, 1, 0.5, 1], [0, 0.5, 0.5, 1, 1, 1]]);
// turned a quarter clockwise seen from above, the back half goes from south to west
assertEquals(model_shape(stairs, 90)[1], [0, 0.5, 0, 0.5, 1, 1]);
});
Deno.test("models made of planes get one box around them, so plants can still be pointed at", () => {
assertEquals(model_shape(BUILTIN_MODELS["engine:crop"]), [[0, 0, 0, 1, 1, 1]]);
const [cross] = model_shape(BUILTIN_MODELS["engine:cross"]);
assertEquals(cross[1], 0);
assertEquals(cross[4], 1);
assert(cross[0] < 0.1 && cross[3] > 0.9);
});
Deno.test("a block's shape follows its model, or its own shape in pixels, turned with the variant", () => {
const { block } = block_from_json({
id: "test:half",
textures: "test:stone",
shape: [[0, 0, 0, 16, 8, 8]],
states: [{ name: "facing", bits: 2, default: 0 }],
variants: { "facing=1": { y: 90 } },
});
assertEquals(block_shape(block, { facing: 0 }), [[0, 0, 0, 1, 0.5, 0.5]]);
assertEquals(block_shape(block, { facing: 1 }), [[0.5, 0, 0, 1, 0.5, 1]]);
const { block: plant } = block_from_json({
id: "test:plant",
textures: { cross: "test:flower" },
model: "engine:cross",
collision: false,
});
assertEquals(collision_shape_at(plant, 0), EMPTY_SHAPE);
});
Deno.test("shapes must be boxes in pixels", () => {
const block = { id: "test:a", textures: "test:a" };
assertEquals(validate_block({ ...block, shape: [[0, 0, 0, 16, 8, 16]] }), []);
assertEquals(validate_block({ ...block, shape: [[0, 0, 0, 16, 8]] }).length, 1);
assertEquals(validate_block({ ...block, shape: [[0, 8, 0, 16, 0, 16]] }).length, 1);
assertEquals(validate_block({ ...block, shape: [] }).length, 1);
});
Deno.test("bodies land on a slab's top and walk under nothing where its other half is empty", () => {
const slab_at_origin = (x: number, y: number, z: number) => y === -1 || (x === 0 && y === 0 && z === 0 && SLAB);
const falling = { x: 0.5, y: 2, z: 0.5, vx: 0, vy: 0, vz: 0, width: 0.6, height: 1.8 };
for (let i = 0; i < 40; i++) move_body(falling, -32, slab_at_origin);
assertAlmostEquals(falling.y, 0.5, 1e-6);
// walking into it steps up onto it, it's under the step height
const walking = { x: -1, y: 0, z: 0.5, vx: 4, vy: 0, vz: 0, width: 0.6, height: 1.8 };
for (let i = 0; i < 10; i++) {
walking.vx = 4;
move_body(walking, -32, slab_at_origin, 0.6, true);
}
assert(walking.x > 0.5);
assertAlmostEquals(walking.y, 0.5, 1e-6);
// a slab on the ceiling leaves room for its empty bottom half
const upper: Shape = [[0, 0.5, 0, 1, 1, 1]];
const ceiling = (x: number, y: number, z: number) => y === -1 || (x === 0 && y === 1 && z === 0 && upper);
const jumping = { x: 0.5, y: 0, z: 0.5, vx: 0, vy: 10, vz: 0, width: 0.6, height: 1 };
move_body(jumping, 0, ceiling);
assertAlmostEquals(jumping.y, 0.5, 1e-6);
});
Deno.test("a ray goes into a block only where its boxes are", () => {
// level with the slab's empty top half, it misses
assertEquals(clip_shape(SLAB, 0, 0, 0, [-1, 0.75, 0.5], [1, 0, 0], 5), undefined);
// looking down at it, it hits the top 0.5 below the eye, on the top face
const hit = clip_shape(SLAB, 0, 0, 0, [0.5, 1, 0.5], [0, -1, 0], 5)!;
assertAlmostEquals(hit.distance, 0.5);
assertEquals([hit.axis, hit.sign], [1, -1]);
// out of reach
assertEquals(clip_shape(SLAB, 0, 0, 0, [0.5, 10, 0.5], [0, -1, 0], 5), undefined);
});
Deno.test("only a placed block's boxes are in the way of whoever stands there", () => {
const player = { x: 0.5, y: 0.6, z: 0.5, width: 0.6, height: 1.8 };
assert(box_overlaps_block(player, 0, 0, 0));
assert(!box_overlaps_block(player, 0, 0, 0, SLAB));
});
Deno.test("the outline is the edges of the shape's boxes, a little outside them", async () => {
const { shape_edges } = await import("$/client/rendering/level_renderer.ts");
const cube = shape_edges(FULL_SHAPE);
assertEquals(cube.length, 12);
assert(cube.every((edge) => edge.every((v) => v < 0 || v > 1)));
assertEquals(shape_edges(SLAB).length, 12);
// edges two boxes share are drawn once
assertEquals(shape_edges([...SLAB, ...SLAB]).length, 12);
});
+7 -7
View File
@@ -12,7 +12,7 @@ function setup(ceiling = Infinity, world?: { solid: Blocks; water: Blocks }) {
const sent: { y: number; swimming?: boolean }[] = [];
const client = {
level: {
has_collision: world?.solid ?? ((_x: number, y: number) => y < 0 || y >= ceiling),
collision_shape: world?.solid ?? ((_x: number, y: number) => y < 0 || y >= ceiling),
is_liquid: world?.water ?? (() => false),
},
screen: undefined,
@@ -190,9 +190,9 @@ Deno.test("sprinting starts going forward and keeps going until it stops, sneaks
// running into a wall stops it, running along one doesn't
for (const [yaw, stops] of [[0, true], [Math.PI / 2, false]] as const) {
const { player } = setup();
const level = player.level as unknown as { has_collision: (x: number, y: number, z: number) => boolean };
const level = player.level as unknown as { collision_shape: (x: number, y: number, z: number) => boolean };
// a wall on the -z side
level.has_collision = (_x, y, z) => y < 0 || z < -2;
level.collision_shape = (_x, y, z) => y < 0 || z < -2;
player.set_position(0.5, 0, -1);
player.yaw = yaw;
run(player, 1, () => false);
@@ -223,8 +223,8 @@ Deno.test("sneaking doesn't walk off edges, from any direction, but still jumps
for (const [key, yaw] of [["KeyW", 0], ["KeyW", Math.PI / 4], ["KeyD", 0], ["KeyS", 1], ["KeyA", 2.5]] as const) {
// a 3x3 platform with nothing around it
const { player } = setup();
const level = player.level as unknown as { has_collision: (x: number, y: number, z: number) => boolean };
level.has_collision = (x, y, z) => y === -1 && x >= 0 && x < 3 && z >= 0 && z < 3;
const level = player.level as unknown as { collision_shape: (x: number, y: number, z: number) => boolean };
level.collision_shape = (x, y, z) => y === -1 && x >= 0 && x < 3 && z >= 0 && z < 3;
player.set_position(1.5, 0, 1.5);
player.yaw = yaw;
run(player, 1, () => false);
@@ -244,8 +244,8 @@ Deno.test("sneaking doesn't walk off edges, from any direction, but still jumps
Deno.test("stepping from the edge of a block onto the one diagonal to it doesn't fall between them", () => {
// floor only at (0, 0) and (1, 1)
const { player } = setup();
const level = player.level as unknown as { has_collision: (x: number, y: number, z: number) => boolean };
level.has_collision = (x, y, z) => y === -1 && ((x === 0 && z === 0) || (x === 1 && z === 1));
const level = player.level as unknown as { collision_shape: (x: number, y: number, z: number) => boolean };
level.collision_shape = (x, y, z) => y === -1 && ((x === 0 && z === 0) || (x === 1 && z === 1));
// on the +x edge of the first block, hanging over it, then walking diagonally to the other
player.set_position(1, 0, 0.3);
run(player, 1, () => false);