diff --git a/client/game_mode.ts b/client/game_mode.ts index 41d7b61..b8ea9d0 100644 --- a/client/game_mode.ts +++ b/client/game_mode.ts @@ -5,7 +5,7 @@ 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, default_block_value, placement_target } from "$/common/utils.ts"; -import { shape_at } from "$/common/block_shapes.ts"; +import { collision_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"; @@ -119,7 +119,7 @@ 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, block: BlockRegistry) { - const shape = shape_at(block, default_block_value(0, block)); + const shape = collision_shape_at(block, default_block_value(0, block)); for (const entity of this.client.level.entities.values()) { const json = entity instanceof RemoteEntity ? EverythingRegistry.get("entities", entity.type) diff --git a/client/rendering/item_renderer.ts b/client/rendering/item_renderer.ts index ceadbed..41626b4 100644 --- a/client/rendering/item_renderer.ts +++ b/client/rendering/item_renderer.ts @@ -5,7 +5,17 @@ import { get_sprite_region } from "$/client/sprites.ts"; import type { ItemEntity } from "$/client/entity/item_entity.ts"; import type { ItemStack } from "$/common/inventory.ts"; import { light_color, push_vertex, Texture } from "$/client/renderer/mod.ts"; -import { block_item_texture, block_variant, cube_face_texture, cube_face_tint } from "$/common/block_models.ts"; +import { + type BakedQuad, + block_item_quads, + block_item_texture, + block_variant, + cube_face_texture, + cube_face_tint, + ITEM_FACE_SHADE, + item_tint, + type ModelJson, +} from "$/common/block_models.ts"; import { item_model } from "./item_model.ts"; import { get_state_value, item_texture } from "$/common/utils.ts"; import { ID_MASK, TEXTURE_SIZE } from "$/common/constants.ts"; @@ -174,10 +184,46 @@ export function item_block(item: ItemStack): BlockRegistry | undefined { return block && block_item_texture(block) === undefined ? block : undefined; } -// an item's model: a cube for blocks, its sprite made 3d for everything else (see item_model.ts). tint multiplies its -// colors, like the light it's in +// a block's item_model quads, baked the first time they're drawn +export function item_model_quads(block: BlockRegistry): BakedQuad[] | undefined { + if (block.item_model === undefined) return undefined; + let quads = baked_items.get(block); + if (!quads) { + quads = block_item_quads(block, Object.fromEntries(EverythingRegistry.entries("models"))) ?? []; + baked_items.set(block, quads); + } + return quads; +} +const baked_items = new WeakMap(); + +// an item's model: its block's item_model or a cube for 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]) { const block = item_block(item); + const model = block && item_model_quads(block); + if (block && model) { + for (const quad of model) { + const region = get_sprite_region(quad.texture); + const [r, g, b] = item_tint(block, quad.variables); + const shade = quad.shade ? ITEM_FACE_SHADE[quad.face] : 1; + 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( + px, + py, + pz, + sprite_u(atlas, region, quad.uvs[i * 2]), + sprite_v(atlas, region, quad.uvs[i * 2 + 1]), + shade * r * tr, + shade * g * tg, + shade * b * tb, + 1, + ); + } + } + return; + } if (block) { for (const face of CUBE_FACES) { const region = get_sprite_region(cube_face_texture(block, face.texture)); @@ -201,6 +247,17 @@ export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransf } } +// where a model's uv in pixels (0-16) is in the atlas, kept off the sprite's edge +export function sprite_u(atlas: Texture, region: SpriteRegion, pixels: number) { + const t = Math.min(Math.max(pixels / TEXTURE_SIZE * region.width, UV_PAD), region.width - UV_PAD); + return (region.x + t) / atlas.width; +} + +export function sprite_v(atlas: Texture, region: SpriteRegion, pixels: number) { + const t = Math.min(Math.max(pixels / TEXTURE_SIZE * region.height, UV_PAD), region.height - UV_PAD); + return (region.y + t) / atlas.height; +} + function push_textured_quad(atlas: Texture, region: SpriteRegion, corners: number[][], color: number[]) { const u0 = (region.x + UV_PAD) / atlas.width; const v0 = (region.y + UV_PAD) / atlas.height; diff --git a/client/rendering/level_renderer.ts b/client/rendering/level_renderer.ts index c941f19..5701f6f 100644 --- a/client/rendering/level_renderer.ts +++ b/client/rendering/level_renderer.ts @@ -26,20 +26,10 @@ import { white_tex, } from "$/client/renderer/mod.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 { bake_block, type BakedQuad, FACE_INDEX, looks_by_state, 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"; @@ -211,15 +201,10 @@ export class LevelRenderer { // the block's model at a value, baked once #destroy_quads(block: BlockRegistry, value: number): BakedQuad[] { - const key = block.variants ? value : value & ID_MASK; + const key = looks_by_state(block) ? value : value & ID_MASK; let quads = this.#baked.get(key); if (!quads) { - const states: Record = {}; - 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("models")); - const model = find_model(variant.model, models) ?? BUILTIN_MODELS[DEFAULT_MODEL]; - quads = bake_model(model, variant.textures, variant.y); + quads = bake_block(block, value, Object.fromEntries(EverythingRegistry.entries("models"))); this.#baked.set(key, quads); } return quads; diff --git a/client/rendering/render_utils.ts b/client/rendering/render_utils.ts index 297cebf..42a3c16 100644 --- a/client/rendering/render_utils.ts +++ b/client/rendering/render_utils.ts @@ -4,12 +4,24 @@ import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everyt import { AssetManager } from "$/client/assets.ts"; import { ItemStack } from "$/common/inventory.ts"; import { item_texture } from "$/common/utils.ts"; -import { block_item_texture, cube_face_texture, cube_face_tint } from "$/common/block_models.ts"; +import { + type BakedQuad, + block_item_texture, + cube_face_texture, + cube_face_tint, + ITEM_FACE_SHADE, + item_tint, +} from "$/common/block_models.ts"; +import { item_model_quads, sprite_u, sprite_v } from "./item_renderer.ts"; import { draw_rect, draw_text, draw_texture_region, draw_texture_region_skewed, + flush_batch, + get_current_texture, + push_vertex, + set_current_texture, Texture, } from "$/client/renderer/mod.ts"; @@ -75,7 +87,10 @@ export function draw_item(item: ItemStack, x: number, y: number) { ? EverythingRegistry.get("blocks", item_info.block_id) : undefined; // blocks that aren't cubes, like plants, show a flat sprite - if (block_info && block_item_texture(block_info) === undefined) { + const model = block_info && item_model_quads(block_info); + if (block_info && model) { + draw_item_model(block_info, model, x, y); + } else if (block_info && block_item_texture(block_info) === undefined) { draw_item_block(block_info, x, y); } else { draw_item_item(item, item_info, x, y); @@ -129,6 +144,71 @@ function draw_item_item(item: ItemStack, item_info: ItemRegistry, x: number, y: ); } +// where the corners of the cube icon are, so models are drawn at the same size and angle: seen from above the +// north west corner, west on the left and north on the right +function item_projection(x: number, y: number) { + const size = (SLOT_SIZE - 4 * 2) / 2; + const cx = x + SLOT_SIZE / 2; + const cy = y + SLOT_SIZE / 2 - 10; + return (px: number, py: number, pz: number) => [ + cx + (px - pz) * size, + cy + size / 2 - (px + pz) * size / 2 + (1 - py) * size, + ]; +} + +// toward whoever looks at an icon, see item_projection +const ICON_VIEW = [-1, 1, -1]; + +// a block's item_model in a slot: its faces that face the viewer, back to front +function draw_item_model(block_info: BlockRegistry, quads: BakedQuad[], x: number, y: number) { + const atlas = AssetManager.instance.get("bworld:textures"); + if (get_current_texture() !== atlas.tex) { + flush_batch(); + set_current_texture(atlas.tex); + } + const project = item_projection(x, y); + const toward_viewer = (p: number[]) => p[0] * ICON_VIEW[0] + p[1] * ICON_VIEW[1] + p[2] * ICON_VIEW[2]; + const visible = quads + .filter((quad) => { + 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], + ]; + return toward_viewer(normal) > 1e-6; + }) + .map((quad) => { + const p = quad.positions; + const center = [0, 1, 2].map((axis) => (p[axis] + p[3 + axis] + p[6 + axis] + p[9 + axis]) / 4); + return { quad, depth: toward_viewer(center) }; + }) + .sort((a, b) => a.depth - b.depth); + + for (const { quad } of visible) { + const region = get_sprite_region(quad.texture); + const [r, g, b] = item_tint(block_info, quad.variables); + const shade = quad.shade ? ITEM_FACE_SHADE[quad.face] : 1; + for (const i of [0, 1, 2, 0, 2, 3]) { + const p = quad.positions; + const [sx, sy] = project(p[i * 3], p[i * 3 + 1], p[i * 3 + 2]); + push_vertex( + sx, + sy, + 0, + sprite_u(atlas, region, quad.uvs[i * 2]), + sprite_v(atlas, region, quad.uvs[i * 2 + 1]), + shade * r, + shade * g, + shade * b, + 1, + ); + } + } +} + function draw_item_block(block_info: BlockRegistry, x: number, y: number) { const top_texture = cube_face_texture(block_info, "top"); const front_texture = cube_face_texture(block_info, "front"); diff --git a/client/workers/chunk_worker.ts b/client/workers/chunk_worker.ts index 15773ce..5e7442a 100644 --- a/client/workers/chunk_worker.ts +++ b/client/workers/chunk_worker.ts @@ -25,13 +25,12 @@ import { type ToChunkWorker, UNALIGNED_GROUP, } from "./chunk_messages.ts"; -import { get_state_value } from "$/common/utils.ts"; import { - bake_model, - block_variant, + bake_block, FACE_CORNERS, - find_model, + is_full_cube, is_tinted, + looks_by_state, type ModelJson, } from "$/common/block_models.ts"; import { @@ -88,7 +87,7 @@ let blocks_registry: BlockRegistry[] = []; const TABLE_SIZE = ID_MASK + 1; const block_layers = new Uint8Array(TABLE_SIZE); const block_cull_same = new Uint8Array(TABLE_SIZE); -// darkens the corners it touches (minecraft's ambient occlusion), blocks with a full collision box do +// darkens the corners it touches (minecraft's ambient occlusion), full cubes with collision do const block_occludes = new Uint8Array(TABLE_SIZE); // light can come around a corner past it const block_lets_light_by = new Uint8Array(TABLE_SIZE); @@ -259,7 +258,7 @@ function build_block_tables() { const opacity = block_light_opacity(block); block_layers[nid] = layer; block_cull_same[nid] = (block.cull_same ?? layer === TRANSLUCENT) ? 1 : 0; - block_occludes[nid] = block.has_collision && layer !== TRANSLUCENT ? 1 : 0; + block_occludes[nid] = block.has_collision && layer !== TRANSLUCENT && is_full_cube(block) ? 1 : 0; block_lets_light_by[nid] = layer !== SOLID || opacity === 0 ? 1 : 0; light_tables.opacity[nid] = opacity; light_tables.emission[nid] = block_light_emission(block); @@ -429,19 +428,11 @@ function atlas_v(sprite: SpriteRegion, v: number) { function block_quads(value: number): MeshQuad[] { const nid = value & ID_MASK; const block = blocks_registry[nid]; - const key = block.variants ? value : nid; + const key = looks_by_state(block) ? value : nid; let quads = baked.get(key); if (quads) return quads; - let states: Record | undefined; - if (block.variants && block.states) { - states = {}; - for (const state of block.states) states[state.name] = get_state_value(value, block, state.name)!; - } - const variant = block_variant(block, states); - const model = find_model(variant.model, models) ?? find_model("engine:cube", models)!; - - quads = bake_model(model, variant.textures, variant.y).map((quad) => ({ + quads = bake_block(block, value, models).map((quad) => ({ positions: quad.positions, uvs: quad.uvs, face: quad.face, diff --git a/common/block_models.ts b/common/block_models.ts index 39215d4..a00c80b 100644 --- a/common/block_models.ts +++ b/common/block_models.ts @@ -3,6 +3,7 @@ // into quads in block space (0 to 1) that the chunk mesher and the item renderers draw import type { BlockRegistry, BlockTextures } from "./everything_registry.ts"; import { tint_without_biome } from "./worldgen/biome_colors.ts"; +import { get_state_value } from "./utils.ts"; export type ModelFace = "top" | "bottom" | "north" | "south" | "west" | "east"; export const MODEL_FACES: ModelFace[] = ["top", "bottom", "north", "south", "west", "east"]; @@ -51,6 +52,30 @@ export interface BlockVariant { // 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[][]; + // what entities bump into, when it isn't the shape. can go up to 24 pixels high, like a fence's + collision_shape?: number[][]; +} + +// one piece of a block made of pieces, like minecraft's multipart blockstates: a fence is a post, and a bar for each +// side it connects on. every part whose "when" matches is drawn, and adds its shape +export interface BlockPart { + // a condition on the block's states like a variant's key, "north=1". always when not set + when?: string; + model: string; + // the block's textures when not set + textures?: BlockTextures; + y?: number; + shape?: number[][]; + collision_shape?: number[][]; +} + +// a model with everything it's drawn with, a variant or a part +export interface PlacedModel { + model: string; + textures: BlockTextures; + y: number; + shape?: number[][]; + collision_shape?: number[][]; } export const DEFAULT_MODEL = "engine:cube"; @@ -147,14 +172,12 @@ export function texture_variables(reference: string, textures: BlockTextures | u // 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, -): Required> & Pick { +export function block_variant(block: BlockRegistry, states?: Record): PlacedModel { let model: string | undefined; let textures: BlockTextures | undefined; let y: number | undefined; let shape: number[][] | undefined; + let collision_shape: number[][] | undefined; if (block.variants && states) { for (const [condition, override] of Object.entries(block.variants)) { if (!variant_matches(condition, states)) continue; @@ -162,6 +185,7 @@ export function block_variant( textures ??= override.textures; y ??= override.y; shape ??= override.shape; + collision_shape ??= override.collision_shape; } } return { @@ -169,9 +193,55 @@ export function block_variant( textures: textures ?? block.textures, y: y ?? 0, shape: shape ?? block.shape, + collision_shape: collision_shape ?? block.collision_shape, }; } +// what a block is drawn with at a value with state bits: every matching part for a block made of parts, or its variant. +// parts take the variant's textures when they don't set their own +export function block_parts(block: BlockRegistry, states?: Record): PlacedModel[] { + const variant = block_variant(block, states); + if (!block.parts) return [variant]; + return block.parts + .filter((part) => variant_matches(part.when ?? "", states ?? {})) + .map((part) => ({ + model: part.model, + textures: part.textures ?? variant.textures, + y: part.y ?? 0, + shape: part.shape, + collision_shape: part.collision_shape, + })); +} + +// whether it's a full cube in every state, so it hides what's behind it from light like minecraft's solid render +// shape. slabs, fences and pots aren't, even with collision +export function is_full_cube(block: BlockRegistry) { + const cube = (model: string | undefined) => (model ?? DEFAULT_MODEL) === DEFAULT_MODEL; + return !block.parts && !block.shape && cube(block.model) && + Object.values(block.variants ?? {}).every((variant) => !variant.shape && cube(variant.model ?? block.model)); +} + +// whether how the block looks depends on its states, so it has to be worked out per value and not per block +export function looks_by_state(block: BlockRegistry) { + return block.variants !== undefined || block.parts !== undefined; +} + +// the states of a value with state bits, by name +export function states_of(block: BlockRegistry, value: number): Record { + const states: Record = {}; + for (const state of block.states ?? []) states[state.name] = get_state_value(value, block, state.name)!; + return states; +} + +// every quad of the block at a value with state bits, its parts' quads together +export function bake_block(block: BlockRegistry, value: number, models: Record): BakedQuad[] { + const states = looks_by_state(block) ? states_of(block, value) : undefined; + return block_parts(block, states).flatMap((part) => { + const model = find_model(part.model, models) ?? BUILTIN_MODELS[DEFAULT_MODEL]; + return bake_model(model, part.textures, part.y); + }); +} + // "age=7" or "age=7,facing=2", "" matches everything export function variant_matches(condition: string, states: Record) { if (condition === "") return true; @@ -181,10 +251,12 @@ export function variant_matches(condition: string, states: Record> 16, (color >> 8) & 0xff, color & 0xff].map((c) => c / 255); } +// the quads of a block's item_model with the block's textures, for its item in inventories, hands and on the ground. +// undefined for blocks without one +export function block_item_quads(block: BlockRegistry, models: Record): BakedQuad[] | undefined { + if (block.item_model === undefined) return undefined; + const model = find_model(block.item_model, models); + return model ? bake_model(model, block.textures) : undefined; +} + +// how much darker each side of an item's model is drawn, like the mesher's: top, bottom, south, north, west, east +export const ITEM_FACE_SHADE = [1.0, 0.5, 0.8, 0.8, 0.6, 0.6]; + // whether a face that got its texture through these variables is drawn in the block's tint export function is_tinted(block: BlockRegistry, variables: string[]) { if (!block.tint) return false; diff --git a/common/block_shapes.ts b/common/block_shapes.ts index 7838914..3fe60bc 100644 --- a/common/block_shapes.ts +++ b/common/block_shapes.ts @@ -1,9 +1,16 @@ // 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 { + block_parts, + element_rotation, + find_model, + looks_by_state, + type ModelJson, + states_of, +} from "./block_models.ts"; import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts"; -import { get_state_value } from "./utils.ts"; +import { STATE_SHIFT } from "./constants.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]; @@ -41,43 +48,70 @@ export function model_shape(model: ModelJson, y_rotation = 0): Shape { 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)); +// boxes in pixels, like a block's "shape" ([x1, y1, z1, x2, y2, z2], 0 to 16), turned like the model is. a collision +// shape can go up to 24 pixels high, like minecraft's fences, so nothing jumps over them +export function pixel_shape(boxes: number[][], y_rotation = 0, top = 1): Shape { + return boxes.map((box) => turn(clamp(box.map((v) => v / 16), top), 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 +// how high a collision shape can go, in blocks +export const COLLISION_TOP = 1.5; + +// what the block is at a value with state bits: each part's (or the variant's) "shape" when it sets one, otherwise +// its model's boxes export function block_shape(block: BlockRegistry, states?: Record): 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("models"))); - return model ? model_shape(model, variant.y) : FULL_SHAPE; + const models = Object.fromEntries(EverythingRegistry.entries("models")); + return block_parts(block, states).flatMap((part) => { + if (part.shape) return pixel_shape(part.shape, part.y); + const model = find_model(part.model, models); + return model ? model_shape(model, part.y) : FULL_SHAPE; + }); +} + +// what entities bump into, like getCollisionShape: each part's "collision_shape" when it sets one, otherwise its shape +export function block_collision_shape(block: BlockRegistry, states?: Record): Shape { + if (!block.has_collision) return EMPTY_SHAPE; + const parts = block_parts(block, states); + if (parts.every((part) => !part.collision_shape)) return block_shape(block, states); + const models = Object.fromEntries(EverythingRegistry.entries("models")); + return parts.flatMap((part) => { + if (part.collision_shape) return pixel_shape(part.collision_shape, part.y, COLLISION_TOP); + if (part.shape) return pixel_shape(part.shape, part.y); + const model = find_model(part.model, models); + return model ? model_shape(model, part.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>(); +const shapes_cache = new WeakMap>(); +const collision_cache = new WeakMap>(); -// the block's shape at a value from the world, see block_shape -export function shape_at(block: BlockRegistry, value: number): Shape { +function cached( + cache: WeakMap>, + block: BlockRegistry, + value: number, + make: (block: BlockRegistry, states?: Record) => Shape, +): Shape { let shapes = cache.get(block); if (!shapes) cache.set(block, shapes = new Map()); - const key = block.variants ? value : 0; + const by_state = looks_by_state(block); + const key = by_state ? value >>> STATE_SHIFT : 0; let shape = shapes.get(key); if (!shape) { - let states: Record | 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); + shape = make(block, by_state ? states_of(block, value) : undefined); shapes.set(key, shape); } return shape; } -// what entities bump into, like getCollisionShape: the shape, or nothing for blocks with "collision": false +// the block's shape at a value from the world, see block_shape +export function shape_at(block: BlockRegistry, value: number): Shape { + return cached(shapes_cache, block, value, block_shape); +} + +// what entities bump into at a value from the world, see block_collision_shape. nothing for "collision": false export function collision_shape_at(block: BlockRegistry, value: number): Shape { - return block.has_collision ? shape_at(block, value) : EMPTY_SHAPE; + return cached(collision_cache, block, value, block_collision_shape); } // how far along the ray (origin plus direction times distance) it first goes into one of the boxes of a block at @@ -119,8 +153,24 @@ export function clip_shape( return closest; } -function clamp(box: number[]): Box { - const c = box.map((v) => Math.min(Math.max(v, 0), 1)); +// whether the shape's boxes cover the whole of one of the block's sides, like minecraft's Block.isFaceFull. checked +// pixel by pixel, which is as fine as shapes in pixels get +export function covers_face(shape: Shape, face: "west" | "east" | "bottom" | "top" | "north" | "south"): boolean { + const axis = face === "west" || face === "east" ? 0 : face === "bottom" || face === "top" ? 1 : 2; + const high = face === "east" || face === "top" || face === "south"; + const [a, b] = [(axis + 1) % 3, (axis + 2) % 3]; + const touching = shape.filter((box) => high ? box[axis + 3] >= 1 - FLAT && box[axis] < 1 : box[axis] <= FLAT); + for (let i = 0; i < 16; i++) { + for (let j = 0; j < 16; j++) { + const [u, v] = [(i + 0.5) / 16, (j + 0.5) / 16]; + if (!touching.some((box) => box[a] <= u && u <= box[a + 3] && box[b] <= v && v <= box[b + 3])) return false; + } + } + return true; +} + +function clamp(box: number[], top = 1): Box { + const c = box.map((v, i) => Math.min(Math.max(v, 0), i % 3 === 1 ? top : 1)); return [c[0], c[1], c[2], c[3], c[4], c[5]]; } diff --git a/common/everything_registry.ts b/common/everything_registry.ts index f6248b2..2ca8250 100644 --- a/common/everything_registry.ts +++ b/common/everything_registry.ts @@ -1,6 +1,6 @@ import type { TintColor } from "./worldgen/biome_colors.ts"; import type { ItemStack } from "./inventory.ts"; -import type { BlockVariant } from "./block_models.ts"; +import type { BlockPart, BlockVariant } from "./block_models.ts"; export class EverythingRegistry { static #key_to_id = new Map>(); @@ -119,8 +119,13 @@ export interface BlockRegistry { alpha?: number; has_collision: boolean; - // boxes in pixels, see BlockVariant.shape + // boxes in pixels, see BlockVariant.shape and collision_shape shape?: number[][]; + collision_shape?: number[][]; + // made of pieces instead of one model, see BlockPart + parts?: BlockPart[]; + // the model its item is drawn with, with the block's textures, like minecraft's fence_inventory + item_model?: string; toughness?: number; requires_tool?: boolean; tool_to_break?: string; diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index 7c74efa..c69e971 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -49,6 +49,9 @@ export interface BlockComponent

{ on_second?(block: BlockRef, params: P, dt: number): void; // every morning at 06:00, for every block with data in the world, near a player or not. day is ServerWorld.day on_new_day?(block: BlockRef, params: P, day: number): void; + // a block next to it (on any of the 6 sides) was placed, broken or changed its states, like minecraft's + // updateShape. neighbor is where, and what's there now + on_neighbor_change?(block: BlockRef, params: P, neighbor: Position & { readonly id: Id }): void; } // deno-lint-ignore no-explicit-any @@ -199,6 +202,9 @@ export interface ServerWorld { break_block(x: number, y: number, z: number): boolean; get_state(x: number, y: number, z: number, name: string): number | undefined; set_state(x: number, y: number, z: number, name: string, value: number): boolean; + // whether the block's side is a full square things can attach to, like minecraft's isFaceSturdy: its collision + // shape covers the whole face. false for air, plants, water and the sides of a slab + is_face_sturdy(x: number, y: number, z: number, face: Face): boolean; get_block_data(x: number, y: number, z: number): T | undefined; // the item a block with item_display shows on top of it, like a block entity renderer: saved with the block's data // and synced to players. undefined shows nothing. it goes away with the block, without dropping diff --git a/common/mod_data.ts b/common/mod_data.ts index 1ee9857..2315606 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -11,7 +11,7 @@ import { type ToolProperties, type WornProperties, } from "./everything_registry.ts"; -import { type BlockVariant, MODEL_FACES, type ModelFace } from "./block_models.ts"; +import { type BlockPart, type BlockVariant, MODEL_FACES, type ModelFace } from "./block_models.ts"; import { expand_items, list_matches } from "./tags.ts"; export const FORMAT_VERSION = 1; @@ -56,6 +56,9 @@ export interface BlockJson { alpha?: number; collision?: boolean; shape?: number[][]; + collision_shape?: number[][]; + parts?: BlockPart[]; + item_model?: string; mining?: { toughness: number; tool?: string; requires_tool?: boolean; tier?: number }; drops?: string; item?: boolean; @@ -269,6 +272,9 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso 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.collision_shape !== undefined) json.collision_shape = block.collision_shape; + if (block.parts !== undefined) json.parts = block.parts; + if (block.item_model !== undefined) json.item_model = block.item_model; if (block.toughness !== undefined) { json.mining = { toughness: block.toughness }; if (block.tool_to_break !== undefined) json.mining.tool = block.tool_to_break; @@ -297,6 +303,9 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it if (json.model !== undefined) block.model = json.model; if (json.variants !== undefined) block.variants = json.variants; if (json.shape !== undefined) block.shape = json.shape; + if (json.collision_shape !== undefined) block.collision_shape = json.collision_shape; + if (json.parts !== undefined) block.parts = json.parts; + if (json.item_model !== undefined) block.item_model = json.item_model; 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; @@ -452,7 +461,7 @@ export function validate_block(json: unknown): Problems { if (!is_object(json)) return ["block must be an object"]; const problems = validate_id(json.id, "id"); if (json.model !== undefined) problems.push(...validate_id(json.model, "model")); - const is_cube = json.model === undefined || json.model === "engine:cube"; + const is_cube = json.parts === undefined && (json.model === undefined || json.model === "engine:cube"); const textures = json.textures; if (is_cube) { const texture_ok = typeof textures === "string" || @@ -488,10 +497,53 @@ export function validate_block(json: unknown): Problems { problems.push(`${where}.y must be 0, 90, 180 or 270`); } if (variant.shape !== undefined) problems.push(...validate_shape(variant.shape, `${where}.shape`)); + if (variant.collision_shape !== undefined) { + problems.push(...validate_shape(variant.collision_shape, `${where}.collision_shape`, 24)); + } } } } if (json.shape !== undefined) problems.push(...validate_shape(json.shape, "shape")); + if (json.collision_shape !== undefined) { + problems.push(...validate_shape(json.collision_shape, "collision_shape", 24)); + } + if (json.item_model !== undefined) problems.push(...validate_id(json.item_model, "item_model")); + if (json.parts !== undefined) { + if (!Array.isArray(json.parts) || json.parts.length === 0) { + problems.push("parts must be a list of { when, model, y }"); + } else { + const names = new Set(Array.isArray(json.states) ? json.states.map((s) => is_object(s) ? s.name : "") : []); + json.parts.forEach((part, i) => { + const where = `parts[${i}]`; + if (!is_object(part)) { + problems.push(`${where} must be { when, model, y }`); + return; + } + problems.push(...validate_id(part.model, `${where}.model`)); + if (part.when !== undefined) { + const parts = typeof part.when === "string" ? part.when.split(",") : [undefined]; + for (const condition of part.when === "" ? [] : parts) { + const [name, value] = (condition ?? "").split("=").map((p) => p.trim()); + if (!names.has(name) || !/^\d+$/.test(value ?? "")) { + problems.push( + `${where}.when: "${condition}" must be a state of this block and a number, like north=1`, + ); + } + } + } + if (part.textures !== undefined) { + problems.push(...validate_textures(part.textures, `${where}.textures`)); + } + if (part.y !== undefined && ![0, 90, 180, 270].includes(part.y as number)) { + problems.push(`${where}.y must be 0, 90, 180 or 270`); + } + if (part.shape !== undefined) problems.push(...validate_shape(part.shape, `${where}.shape`)); + if (part.collision_shape !== undefined) { + problems.push(...validate_shape(part.collision_shape, `${where}.collision_shape`, 24)); + } + }); + } + } if (json.render_layer !== undefined && !RENDER_LAYERS.includes(json.render_layer as RenderLayer)) { problems.push(`render_layer must be one of ${RENDER_LAYERS.join(", ")}`); } @@ -554,14 +606,15 @@ 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 { +// boxes in pixels: [[x1, y1, z1, x2, y2, z2], ...], each corner from 0 to 16 (y to top) and the second past the first +function validate_shape(shape: unknown, where: string, top = 16): Problems { const is_box = (box: unknown) => Array.isArray(box) && box.length === 6 && - box.every((v) => typeof v === "number" && v >= 0 && v <= 16) && + box.every((v, i) => typeof v === "number" && v >= 0 && v <= (i % 3 === 1 ? top : 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]]`]; + const most = top === 16 ? "" : `, up to ${top} high`; + return [`${where} must be a list of boxes in pixels${most}, like [[0, 0, 0, 16, 8, 16]]`]; } return []; } diff --git a/common/physics.ts b/common/physics.ts index 0bbeb7a..5e95d94 100644 --- a/common/physics.ts +++ b/common/physics.ts @@ -1,6 +1,6 @@ // 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"; +import { COLLISION_TOP, 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; @@ -15,6 +15,12 @@ function shape_of(collision: boolean | Shape): Shape { return collision === true ? FULL_SHAPE : collision === false ? EMPTY_SHAPE : collision; } +// the lowest block whose shape can reach up to a box starting at min along an axis: on y that's one more below, +// since a collision shape can be taller than its block, like a fence's +function lowest(axis: number, min: number) { + return Math.floor(min + EPSILON) - (axis === 1 ? Math.ceil(COLLISION_TOP) - 1 : 0); +} + // something with a box that moves. position is the middle of its feet, velocity is in blocks per second export interface Body { x: number; @@ -131,13 +137,13 @@ function clip( } const [a, b] = OTHER_AXES[axis]; - const from = Math.floor(Math.min(min[axis], min[axis] + distance)); + const from = lowest(axis, Math.min(min[axis], min[axis] + distance) - EPSILON); const to = Math.floor(Math.max(max[axis], max[axis] + distance)); const position = [0, 0, 0]; for (let i = from; i <= to; i++) { - for (let j = Math.floor(min[a] + EPSILON); j <= Math.floor(max[a] - EPSILON); j++) { - for (let k = Math.floor(min[b] + EPSILON); k <= Math.floor(max[b] - EPSILON); k++) { + for (let j = lowest(a, min[a]); j <= Math.floor(max[a] - EPSILON); j++) { + for (let k = lowest(b, min[b]); k <= Math.floor(max[b] - EPSILON); k++) { position[axis] = i; position[a] = j; position[b] = k; @@ -204,9 +210,9 @@ export function box_is_free( } 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++) { + for (let x = lowest(0, min[0]); x <= Math.floor(max[0] - EPSILON); x++) { + for (let y = lowest(1, min[1]); y <= Math.floor(max[1] - EPSILON); y++) { + for (let z = lowest(2, min[2]); z <= Math.floor(max[2] - EPSILON); z++) { for (const box of shape_of(is_solid(x, y, z))) { if ( x + box[0] < max[0] - EPSILON && x + box[3] > min[0] + EPSILON && diff --git a/docs/modding/blocks/components.md b/docs/modding/blocks/components.md index 3697e26..366b228 100644 --- a/docs/modding/blocks/components.md +++ b/docs/modding/blocks/components.md @@ -59,19 +59,30 @@ component. ## Handlers -| Handler | Called when | Returns | -| ------------------------------------ | ----------------------------------------------------------------- | -------------------------- | -| `on_create(block, params)` | The block is placed or set, by a player or a script. | | -| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | | -| `on_click(block, params, player)` | A player starts hitting it. | | -| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something | -| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | | -| `on_second(block, params, dt)` | Every second, near a player. | | -| `on_new_day(block, params, day)` | Every morning at 06:00, anywhere in the world. | | +| Handler | Called when | Returns | +| --------------------------------------------- | ---------------------------------------------------------------------- | -------------------------- | +| `on_create(block, params)` | The block is placed or set, by a player or a script. | | +| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | | +| `on_click(block, params, player)` | A player starts hitting it. | | +| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something | +| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | | +| `on_second(block, params, dt)` | Every second, near a player. | | +| `on_new_day(block, params, day)` | Every morning at 06:00, anywhere in the world. | | +| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | | `block` is `{ id, x, y, z, data }`, where `data` is the block's [tile data](tiledata.md). `params` is what the block's JSON lists for this component, and `dt` is in seconds. +### Neighbors + +`on_neighbor_change` is how a block keeps up with what's around it, like Minecraft's `updateShape`: `neighbor` is +`{ x, y, z, id }` of the block that changed. A fence sets its `north`, `east`, `south` and `west` states from it. +Setting a state to what it already is changes nothing and tells no one, so blocks answering each other this way settle. + +`ctx.world.is_face_sturdy(x, y, z, face)` says whether a block's side is something to attach to, like Minecraft's +`isFaceSturdy`: its [collision shape](../resources/models.md#collision-shapes) covers the whole side. Stone's sides are, +a slab's sides and plants aren't. + ### Interacting When a player right clicks a block, every component's `on_interact` runs. If any of them returns `true`, the click was @@ -96,16 +107,17 @@ catch up. If it's further behind than that, it skips the rest and logs a warning `mods/bworld/scripts/server.ts` registers these, and any mod that depends on `bworld` can use them: -| Component | Params | What it does | -| ----------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. | -| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. | -| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. | -| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. | -| `bworld:farmland` | none | Watered with the watering can, dries out every morning. | -| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. | -| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. | -| `bworld:water_source` | none | Refills the watering can. | -| `bworld:fishable` | none | Can be fished in with the fishing rod. | +| Component | Params | What it does | +| ----------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. | +| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. | +| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. | +| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. | +| `bworld:farmland` | none | Watered with the watering can, dries out every morning. | +| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. | +| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. | +| `bworld:water_source` | none | Refills the watering can. | +| `bworld:fishable` | none | Can be fished in with the fishing rod. | +| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. | Item components work the same way, see [Items](../items/index.md#item-components). diff --git a/docs/modding/blocks/index.md b/docs/modding/blocks/index.md index 522151e..3bf893a 100644 --- a/docs/modding/blocks/index.md +++ b/docs/modding/blocks/index.md @@ -37,6 +37,8 @@ of tier 1 (stone or copper) or better. | `textures` | required | One texture id for every side, `{ "top", "bottom", "side" }`, or `{ "front", "side" }` (optionally with `top` and `bottom`) for a block that faces a way. With another `model`, the model's texture variables. | | `model` | `engine:cube` | The [block model](../resources/models.md). | | `variants` | none | Other models, textures or rotations for some [states](states.md). | +| `parts` | none | Models drawn together depending on [states](states.md), like a fence's post and bars. See [Parts](../resources/models.md#parts). | +| `item_model` | none | The model its item is drawn with. See [Item Models](../resources/models.md#item-models). | | `render_layer` | `solid` | `solid`; `cutout` for texels that are fully opaque or fully clear, like leaves; `translucent` for blended ones, like water and glass. | | `cull_same` | see meaning | Hide the faces between two of this block. `true` for translucent blocks, `false` otherwise. | | `alpha` | `1` | Opacity, for translucent blocks. | @@ -53,6 +55,7 @@ there will be holes in the world behind them. | ---------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `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). | +| `collision_shape` | `shape` | What entities bump into when it's different, up to 24 pixels high. See [Collision Shapes](../resources/models.md#collision-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`. | diff --git a/docs/modding/resources/models.md b/docs/modding/resources/models.md index 530bbcc..d4c697e 100644 --- a/docs/modding/resources/models.md +++ b/docs/modding/resources/models.md @@ -15,7 +15,7 @@ Blocks that aren't full cubes should use the `cutout` or `translucent` [render l `solid` blocks hide their neighbors' faces. They usually want `"collision": false` too. In inventories, a block with a full cube model is drawn as a cube. Any other block is drawn flat, as its first texture, -like Minecraft's plants. +like Minecraft's plants, unless it sets an [`item_model`](#item-models). ## Texture Variables @@ -109,7 +109,47 @@ their own, like a crop that's taller the older it is: } ``` -Boxes stay inside the block, from 0 to 16, so a shape can't be taller than a block like Minecraft's fences. +Boxes stay inside the block, from 0 to 16. + +### Collision Shapes + +What entities bump into is the shape, unless the block sets `collision_shape`, like Minecraft's `getCollisionShape`. +It's in pixels like `shape`, and is the only shape that can go higher than the block: up to 24 pixels, so a fence is too +tall to jump over while players still point at a block-high post. Variants and [parts](#parts) can set their own. + +## Parts + +A block can be made of pieces instead of one model, like Minecraft's multipart blockstates. Each of `parts` is a model +that's drawn when its `when` matches the block's [states](../blocks/states.md) (always, without one), turned by its `y`. +Its `shape` and `collision_shape` are added to the block's when it's drawn. A fence is a post, and a bar for each side +it joins, `blocks/oak_fence.json`: + +```json +"states": [ + { "name": "north", "bits": 1, "default": 0 }, + { "name": "east", "bits": 1, "default": 0 }, + { "name": "south", "bits": 1, "default": 0 }, + { "name": "west", "bits": 1, "default": 0 } +], +"parts": [ + { "model": "bworld:fence_post", "shape": [[6, 0, 6, 10, 16, 10]], "collision_shape": [[6, 0, 6, 10, 24, 10]] }, + { "when": "north=1", "model": "bworld:fence_side", "shape": [[7, 0, 0, 9, 16, 9]], "collision_shape": [[7, 0, 0, 9, 24, 9]] }, + { "when": "east=1", "model": "bworld:fence_side", "y": 90, "shape": [[7, 0, 0, 9, 16, 9]], "collision_shape": [[7, 0, 0, 9, 24, 9]] }, + ... +] +``` + +The side model is the bars on the north side, and `y` turns it to the others. Parts use the block's `textures` unless +they set their own, so one pair of models serves every kind of wood. Parts replace `model` and `variants`' models. + +What sets the states is up to the block's [components](../blocks/components.md): the fences' `bworld:fence` sets them +from what's beside it, every time something next to it changes. + +## Item Models + +`item_model` draws a block's item with another model, filled in with the block's textures, like Minecraft's +`fence_inventory`. Fences use `bworld:fence_inventory`, two posts and the bars between them, since a single post +wouldn't look like a fence. It's drawn in slots, in hands and on the ground. ## Lighting diff --git a/mods/bworld/blocks/acacia_fence.json b/mods/bworld/blocks/acacia_fence.json new file mode 100644 index 0000000..7389396 --- /dev/null +++ b/mods/bworld/blocks/acacia_fence.json @@ -0,0 +1,99 @@ +{ + "format_version": 1, + "block": { + "id": "bworld:acacia_fence", + "name": "Acacia Fence", + "textures": { + "side": "bworld:acacia_fence_side", + "top": "bworld:acacia_fence_top" + }, + "item_model": "bworld:fence_inventory", + "render_layer": "cutout", + "states": [ + { + "name": "north", + "bits": 1, + "default": 0 + }, + { + "name": "east", + "bits": 1, + "default": 0 + }, + { + "name": "south", + "bits": 1, + "default": 0 + }, + { + "name": "west", + "bits": 1, + "default": 0 + } + ], + "parts": [ + { + "model": "bworld:fence_post", + "shape": [ + [6, 0, 6, 10, 16, 10] + ], + "collision_shape": [ + [6, 0, 6, 10, 24, 10] + ] + }, + { + "when": "north=1", + "model": "bworld:fence_side", + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "east=1", + "model": "bworld:fence_side", + "y": 90, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "south=1", + "model": "bworld:fence_side", + "y": 180, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "west=1", + "model": "bworld:fence_side", + "y": 270, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + } + ], + "mining": { + "toughness": 3, + "tool": "axe" + }, + "drops": "bworld:acacia_fence", + "components": { + "bworld:fence": { + "connects_to": "#bworld:wooden_fences" + } + } + } +} diff --git a/mods/bworld/blocks/birch_fence.json b/mods/bworld/blocks/birch_fence.json new file mode 100644 index 0000000..7444ec8 --- /dev/null +++ b/mods/bworld/blocks/birch_fence.json @@ -0,0 +1,99 @@ +{ + "format_version": 1, + "block": { + "id": "bworld:birch_fence", + "name": "Birch Fence", + "textures": { + "side": "bworld:birch_fence_side", + "top": "bworld:birch_fence_top" + }, + "item_model": "bworld:fence_inventory", + "render_layer": "cutout", + "states": [ + { + "name": "north", + "bits": 1, + "default": 0 + }, + { + "name": "east", + "bits": 1, + "default": 0 + }, + { + "name": "south", + "bits": 1, + "default": 0 + }, + { + "name": "west", + "bits": 1, + "default": 0 + } + ], + "parts": [ + { + "model": "bworld:fence_post", + "shape": [ + [6, 0, 6, 10, 16, 10] + ], + "collision_shape": [ + [6, 0, 6, 10, 24, 10] + ] + }, + { + "when": "north=1", + "model": "bworld:fence_side", + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "east=1", + "model": "bworld:fence_side", + "y": 90, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "south=1", + "model": "bworld:fence_side", + "y": 180, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "west=1", + "model": "bworld:fence_side", + "y": 270, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + } + ], + "mining": { + "toughness": 3, + "tool": "axe" + }, + "drops": "bworld:birch_fence", + "components": { + "bworld:fence": { + "connects_to": "#bworld:wooden_fences" + } + } + } +} diff --git a/mods/bworld/blocks/cherry_fence.json b/mods/bworld/blocks/cherry_fence.json new file mode 100644 index 0000000..323a895 --- /dev/null +++ b/mods/bworld/blocks/cherry_fence.json @@ -0,0 +1,99 @@ +{ + "format_version": 1, + "block": { + "id": "bworld:cherry_fence", + "name": "Cherry Fence", + "textures": { + "side": "bworld:cherry_fence_side", + "top": "bworld:cherry_fence_top" + }, + "item_model": "bworld:fence_inventory", + "render_layer": "cutout", + "states": [ + { + "name": "north", + "bits": 1, + "default": 0 + }, + { + "name": "east", + "bits": 1, + "default": 0 + }, + { + "name": "south", + "bits": 1, + "default": 0 + }, + { + "name": "west", + "bits": 1, + "default": 0 + } + ], + "parts": [ + { + "model": "bworld:fence_post", + "shape": [ + [6, 0, 6, 10, 16, 10] + ], + "collision_shape": [ + [6, 0, 6, 10, 24, 10] + ] + }, + { + "when": "north=1", + "model": "bworld:fence_side", + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "east=1", + "model": "bworld:fence_side", + "y": 90, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "south=1", + "model": "bworld:fence_side", + "y": 180, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "west=1", + "model": "bworld:fence_side", + "y": 270, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + } + ], + "mining": { + "toughness": 3, + "tool": "axe" + }, + "drops": "bworld:cherry_fence", + "components": { + "bworld:fence": { + "connects_to": "#bworld:wooden_fences" + } + } + } +} diff --git a/mods/bworld/blocks/dark_oak_fence.json b/mods/bworld/blocks/dark_oak_fence.json new file mode 100644 index 0000000..6effa16 --- /dev/null +++ b/mods/bworld/blocks/dark_oak_fence.json @@ -0,0 +1,99 @@ +{ + "format_version": 1, + "block": { + "id": "bworld:dark_oak_fence", + "name": "Dark Oak Fence", + "textures": { + "side": "bworld:dark_oak_fence_side", + "top": "bworld:dark_oak_fence_top" + }, + "item_model": "bworld:fence_inventory", + "render_layer": "cutout", + "states": [ + { + "name": "north", + "bits": 1, + "default": 0 + }, + { + "name": "east", + "bits": 1, + "default": 0 + }, + { + "name": "south", + "bits": 1, + "default": 0 + }, + { + "name": "west", + "bits": 1, + "default": 0 + } + ], + "parts": [ + { + "model": "bworld:fence_post", + "shape": [ + [6, 0, 6, 10, 16, 10] + ], + "collision_shape": [ + [6, 0, 6, 10, 24, 10] + ] + }, + { + "when": "north=1", + "model": "bworld:fence_side", + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "east=1", + "model": "bworld:fence_side", + "y": 90, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "south=1", + "model": "bworld:fence_side", + "y": 180, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "west=1", + "model": "bworld:fence_side", + "y": 270, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + } + ], + "mining": { + "toughness": 3, + "tool": "axe" + }, + "drops": "bworld:dark_oak_fence", + "components": { + "bworld:fence": { + "connects_to": "#bworld:wooden_fences" + } + } + } +} diff --git a/mods/bworld/blocks/jungle_fence.json b/mods/bworld/blocks/jungle_fence.json new file mode 100644 index 0000000..a9bb990 --- /dev/null +++ b/mods/bworld/blocks/jungle_fence.json @@ -0,0 +1,99 @@ +{ + "format_version": 1, + "block": { + "id": "bworld:jungle_fence", + "name": "Jungle Fence", + "textures": { + "side": "bworld:jungle_fence_side", + "top": "bworld:jungle_fence_top" + }, + "item_model": "bworld:fence_inventory", + "render_layer": "cutout", + "states": [ + { + "name": "north", + "bits": 1, + "default": 0 + }, + { + "name": "east", + "bits": 1, + "default": 0 + }, + { + "name": "south", + "bits": 1, + "default": 0 + }, + { + "name": "west", + "bits": 1, + "default": 0 + } + ], + "parts": [ + { + "model": "bworld:fence_post", + "shape": [ + [6, 0, 6, 10, 16, 10] + ], + "collision_shape": [ + [6, 0, 6, 10, 24, 10] + ] + }, + { + "when": "north=1", + "model": "bworld:fence_side", + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "east=1", + "model": "bworld:fence_side", + "y": 90, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "south=1", + "model": "bworld:fence_side", + "y": 180, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "west=1", + "model": "bworld:fence_side", + "y": 270, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + } + ], + "mining": { + "toughness": 3, + "tool": "axe" + }, + "drops": "bworld:jungle_fence", + "components": { + "bworld:fence": { + "connects_to": "#bworld:wooden_fences" + } + } + } +} diff --git a/mods/bworld/blocks/oak_fence.json b/mods/bworld/blocks/oak_fence.json new file mode 100644 index 0000000..a61ea20 --- /dev/null +++ b/mods/bworld/blocks/oak_fence.json @@ -0,0 +1,99 @@ +{ + "format_version": 1, + "block": { + "id": "bworld:oak_fence", + "name": "Oak Fence", + "textures": { + "side": "bworld:oak_fence_side", + "top": "bworld:oak_fence_top" + }, + "item_model": "bworld:fence_inventory", + "render_layer": "cutout", + "states": [ + { + "name": "north", + "bits": 1, + "default": 0 + }, + { + "name": "east", + "bits": 1, + "default": 0 + }, + { + "name": "south", + "bits": 1, + "default": 0 + }, + { + "name": "west", + "bits": 1, + "default": 0 + } + ], + "parts": [ + { + "model": "bworld:fence_post", + "shape": [ + [6, 0, 6, 10, 16, 10] + ], + "collision_shape": [ + [6, 0, 6, 10, 24, 10] + ] + }, + { + "when": "north=1", + "model": "bworld:fence_side", + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "east=1", + "model": "bworld:fence_side", + "y": 90, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "south=1", + "model": "bworld:fence_side", + "y": 180, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "west=1", + "model": "bworld:fence_side", + "y": 270, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + } + ], + "mining": { + "toughness": 3, + "tool": "axe" + }, + "drops": "bworld:oak_fence", + "components": { + "bworld:fence": { + "connects_to": "#bworld:wooden_fences" + } + } + } +} diff --git a/mods/bworld/blocks/spruce_fence.json b/mods/bworld/blocks/spruce_fence.json new file mode 100644 index 0000000..3d58b4d --- /dev/null +++ b/mods/bworld/blocks/spruce_fence.json @@ -0,0 +1,99 @@ +{ + "format_version": 1, + "block": { + "id": "bworld:spruce_fence", + "name": "Spruce Fence", + "textures": { + "side": "bworld:spruce_fence_side", + "top": "bworld:spruce_fence_top" + }, + "item_model": "bworld:fence_inventory", + "render_layer": "cutout", + "states": [ + { + "name": "north", + "bits": 1, + "default": 0 + }, + { + "name": "east", + "bits": 1, + "default": 0 + }, + { + "name": "south", + "bits": 1, + "default": 0 + }, + { + "name": "west", + "bits": 1, + "default": 0 + } + ], + "parts": [ + { + "model": "bworld:fence_post", + "shape": [ + [6, 0, 6, 10, 16, 10] + ], + "collision_shape": [ + [6, 0, 6, 10, 24, 10] + ] + }, + { + "when": "north=1", + "model": "bworld:fence_side", + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "east=1", + "model": "bworld:fence_side", + "y": 90, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "south=1", + "model": "bworld:fence_side", + "y": 180, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + }, + { + "when": "west=1", + "model": "bworld:fence_side", + "y": 270, + "shape": [ + [7, 0, 0, 9, 16, 9] + ], + "collision_shape": [ + [7, 0, 0, 9, 24, 9] + ] + } + ], + "mining": { + "toughness": 3, + "tool": "axe" + }, + "drops": "bworld:spruce_fence", + "components": { + "bworld:fence": { + "connects_to": "#bworld:wooden_fences" + } + } + } +} diff --git a/mods/bworld/models/fence_inventory.json b/mods/bworld/models/fence_inventory.json new file mode 100644 index 0000000..b83cc05 --- /dev/null +++ b/mods/bworld/models/fence_inventory.json @@ -0,0 +1,128 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:fence_inventory", + "elements": [ + { + "from": [6, 0, 0], + "to": [10, 16, 4], + "faces": { + "north": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "south": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "east": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "west": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "top": { + "texture": "#top", + "uv": [6, 6, 10, 10] + }, + "bottom": { + "texture": "#top", + "uv": [6, 6, 10, 10] + } + } + }, + { + "from": [6, 0, 12], + "to": [10, 16, 16], + "faces": { + "north": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "south": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "east": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "west": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "top": { + "texture": "#top", + "uv": [6, 6, 10, 10] + }, + "bottom": { + "texture": "#top", + "uv": [6, 6, 10, 10] + } + } + }, + { + "from": [7, 12, 0], + "to": [9, 15, 16], + "faces": { + "north": { + "texture": "#side", + "uv": [7, 1, 9, 4] + }, + "south": { + "texture": "#side", + "uv": [7, 1, 9, 4] + }, + "east": { + "texture": "#side", + "uv": [0, 1, 16, 4] + }, + "west": { + "texture": "#side", + "uv": [0, 1, 16, 4] + }, + "top": { + "texture": "#top", + "uv": [7, 0, 9, 16] + }, + "bottom": { + "texture": "#top", + "uv": [7, 0, 9, 16] + } + } + }, + { + "from": [7, 6, 0], + "to": [9, 9, 16], + "faces": { + "north": { + "texture": "#side", + "uv": [7, 7, 9, 10] + }, + "south": { + "texture": "#side", + "uv": [7, 7, 9, 10] + }, + "east": { + "texture": "#side", + "uv": [0, 7, 16, 10] + }, + "west": { + "texture": "#side", + "uv": [0, 7, 16, 10] + }, + "top": { + "texture": "#top", + "uv": [7, 0, 9, 16] + }, + "bottom": { + "texture": "#top", + "uv": [7, 0, 9, 16] + } + } + } + ] + } +} diff --git a/mods/bworld/models/fence_post.json b/mods/bworld/models/fence_post.json new file mode 100644 index 0000000..c4b0925 --- /dev/null +++ b/mods/bworld/models/fence_post.json @@ -0,0 +1,40 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:fence_post", + "elements": [ + { + "from": [6, 0, 6], + "to": [10, 16, 10], + "faces": { + "north": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "east": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "south": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "west": { + "texture": "#side", + "uv": [6, 0, 10, 16] + }, + "top": { + "texture": "#top", + "uv": [6, 6, 10, 10], + "cullface": "top" + }, + "bottom": { + "texture": "#top", + "uv": [6, 6, 10, 10], + "cullface": "bottom" + } + } + } + ] + } +} diff --git a/mods/bworld/models/fence_side.json b/mods/bworld/models/fence_side.json new file mode 100644 index 0000000..4074091 --- /dev/null +++ b/mods/bworld/models/fence_side.json @@ -0,0 +1,62 @@ +{ + "format_version": 1, + "model": { + "id": "bworld:fence_side", + "elements": [ + { + "from": [7, 12, 0], + "to": [9, 15, 9], + "faces": { + "north": { + "texture": "#side", + "uv": [7, 1, 9, 4], + "cullface": "north" + }, + "east": { + "texture": "#side", + "uv": [7, 1, 16, 4] + }, + "west": { + "texture": "#side", + "uv": [0, 1, 9, 4] + }, + "top": { + "texture": "#top", + "uv": [7, 0, 9, 9] + }, + "bottom": { + "texture": "#top", + "uv": [7, 0, 9, 9] + } + } + }, + { + "from": [7, 6, 0], + "to": [9, 9, 9], + "faces": { + "north": { + "texture": "#side", + "uv": [7, 7, 9, 10], + "cullface": "north" + }, + "east": { + "texture": "#side", + "uv": [7, 7, 16, 10] + }, + "west": { + "texture": "#side", + "uv": [0, 7, 9, 10] + }, + "top": { + "texture": "#top", + "uv": [7, 0, 9, 9] + }, + "bottom": { + "texture": "#top", + "uv": [7, 0, 9, 9] + } + } + } + ] + } +} diff --git a/mods/bworld/recipes/crafting_acacia_fence.json b/mods/bworld/recipes/crafting_acacia_fence.json new file mode 100644 index 0000000..2ae94d7 --- /dev/null +++ b/mods/bworld/recipes/crafting_acacia_fence.json @@ -0,0 +1,18 @@ +{ + "format_version": 1, + "recipe": { + "type": "shaped", + "pattern": [ + "PSP", + "PSP" + ], + "key": { + "P": "bworld:acacia_planks", + "S": "bworld:stick" + }, + "result": { + "id": "bworld:acacia_fence", + "count": 3 + } + } +} diff --git a/mods/bworld/recipes/crafting_birch_fence.json b/mods/bworld/recipes/crafting_birch_fence.json new file mode 100644 index 0000000..11a3a17 --- /dev/null +++ b/mods/bworld/recipes/crafting_birch_fence.json @@ -0,0 +1,18 @@ +{ + "format_version": 1, + "recipe": { + "type": "shaped", + "pattern": [ + "PSP", + "PSP" + ], + "key": { + "P": "bworld:birch_planks", + "S": "bworld:stick" + }, + "result": { + "id": "bworld:birch_fence", + "count": 3 + } + } +} diff --git a/mods/bworld/recipes/crafting_cherry_fence.json b/mods/bworld/recipes/crafting_cherry_fence.json new file mode 100644 index 0000000..b2ca249 --- /dev/null +++ b/mods/bworld/recipes/crafting_cherry_fence.json @@ -0,0 +1,18 @@ +{ + "format_version": 1, + "recipe": { + "type": "shaped", + "pattern": [ + "PSP", + "PSP" + ], + "key": { + "P": "bworld:cherry_planks", + "S": "bworld:stick" + }, + "result": { + "id": "bworld:cherry_fence", + "count": 3 + } + } +} diff --git a/mods/bworld/recipes/crafting_dark_oak_fence.json b/mods/bworld/recipes/crafting_dark_oak_fence.json new file mode 100644 index 0000000..b78106b --- /dev/null +++ b/mods/bworld/recipes/crafting_dark_oak_fence.json @@ -0,0 +1,18 @@ +{ + "format_version": 1, + "recipe": { + "type": "shaped", + "pattern": [ + "PSP", + "PSP" + ], + "key": { + "P": "bworld:dark_oak_planks", + "S": "bworld:stick" + }, + "result": { + "id": "bworld:dark_oak_fence", + "count": 3 + } + } +} diff --git a/mods/bworld/recipes/crafting_jungle_fence.json b/mods/bworld/recipes/crafting_jungle_fence.json new file mode 100644 index 0000000..3165933 --- /dev/null +++ b/mods/bworld/recipes/crafting_jungle_fence.json @@ -0,0 +1,18 @@ +{ + "format_version": 1, + "recipe": { + "type": "shaped", + "pattern": [ + "PSP", + "PSP" + ], + "key": { + "P": "bworld:jungle_planks", + "S": "bworld:stick" + }, + "result": { + "id": "bworld:jungle_fence", + "count": 3 + } + } +} diff --git a/mods/bworld/recipes/crafting_oak_fence.json b/mods/bworld/recipes/crafting_oak_fence.json new file mode 100644 index 0000000..3f67371 --- /dev/null +++ b/mods/bworld/recipes/crafting_oak_fence.json @@ -0,0 +1,18 @@ +{ + "format_version": 1, + "recipe": { + "type": "shaped", + "pattern": [ + "PSP", + "PSP" + ], + "key": { + "P": "bworld:planks", + "S": "bworld:stick" + }, + "result": { + "id": "bworld:oak_fence", + "count": 3 + } + } +} diff --git a/mods/bworld/recipes/crafting_spruce_fence.json b/mods/bworld/recipes/crafting_spruce_fence.json new file mode 100644 index 0000000..a8c964c --- /dev/null +++ b/mods/bworld/recipes/crafting_spruce_fence.json @@ -0,0 +1,18 @@ +{ + "format_version": 1, + "recipe": { + "type": "shaped", + "pattern": [ + "PSP", + "PSP" + ], + "key": { + "P": "bworld:spruce_planks", + "S": "bworld:stick" + }, + "result": { + "id": "bworld:spruce_fence", + "count": 3 + } + } +} diff --git a/mods/bworld/scripts/server.ts b/mods/bworld/scripts/server.ts index 1c4f8b0..e4dee35 100644 --- a/mods/bworld/scripts/server.ts +++ b/mods/bworld/scripts/server.ts @@ -8,6 +8,7 @@ export function setup(ctx: ServerContext) { register_storage(ctx); register_furnace(ctx); register_smithing_table(ctx); + register_fence(ctx); register_farming(ctx); register_fishing(ctx); register_curios(ctx); @@ -28,6 +29,35 @@ function register_hoeable(ctx: ServerContext) { }); } +// the sides a fence connects on, and the face of the block there it connects to +const FENCE_SIDES = [ + { state: "north", dx: 0, dz: -1, face: "south" }, + { state: "east", dx: 1, dz: 0, face: "west" }, + { state: "south", dx: 0, dz: 1, face: "north" }, + { state: "west", dx: -1, dz: 0, face: "east" }, +] as const; + +// a fence joins the fences beside it and the full sides of solid blocks, like minecraft's FenceBlock.connectsTo. +// "connects_to" is the tag of fences it joins, so wooden fences don't join other kinds. leaves are full blocks but +// fences don't join them, like minecraft +function register_fence(ctx: ServerContext) { + const connect = (block: BlockRef, params: { connects_to: string }) => { + for (const side of FENCE_SIDES) { + const [x, y, z] = [block.x + side.dx, block.y, block.z + side.dz]; + const id = ctx.world.get_block(x, y, z); + const joins = id !== undefined && ( + ctx.tags.has("blocks", params.connects_to, id) || + (!ctx.tags.has("blocks", "bworld:leaves", id) && ctx.world.is_face_sturdy(x, y, z, side.face)) + ); + ctx.world.set_state(block.x, block.y, block.z, side.state, joins ? 1 : 0); + } + }; + ctx.components.register_block<{ connects_to: string }>("bworld:fence", { + on_create: connect, + on_neighbor_change: connect, + }); +} + // the container a block keeps its items in, made the first time it's needed. blocks placed before tile data // existed don't have one yet function block_container(ctx: ServerContext, block: BlockRef, size: number): Container { diff --git a/mods/bworld/tags/blocks/bworld/wooden_fences.json b/mods/bworld/tags/blocks/bworld/wooden_fences.json new file mode 100644 index 0000000..cb6ee24 --- /dev/null +++ b/mods/bworld/tags/blocks/bworld/wooden_fences.json @@ -0,0 +1,14 @@ +{ + "format_version": 1, + "tag": { + "values": [ + "bworld:oak_fence", + "bworld:spruce_fence", + "bworld:birch_fence", + "bworld:jungle_fence", + "bworld:acacia_fence", + "bworld:dark_oak_fence", + "bworld:cherry_fence" + ] + } +} diff --git a/mods/bworld/tags/items/bworld/wooden_fences.json b/mods/bworld/tags/items/bworld/wooden_fences.json new file mode 100644 index 0000000..cb6ee24 --- /dev/null +++ b/mods/bworld/tags/items/bworld/wooden_fences.json @@ -0,0 +1,14 @@ +{ + "format_version": 1, + "tag": { + "values": [ + "bworld:oak_fence", + "bworld:spruce_fence", + "bworld:birch_fence", + "bworld:jungle_fence", + "bworld:acacia_fence", + "bworld:dark_oak_fence", + "bworld:cherry_fence" + ] + } +} diff --git a/mods/bworld/textures/acacia_fence_side.png b/mods/bworld/textures/acacia_fence_side.png new file mode 100644 index 0000000..6a61db5 Binary files /dev/null and b/mods/bworld/textures/acacia_fence_side.png differ diff --git a/mods/bworld/textures/acacia_fence_top.png b/mods/bworld/textures/acacia_fence_top.png new file mode 100644 index 0000000..5cef987 Binary files /dev/null and b/mods/bworld/textures/acacia_fence_top.png differ diff --git a/mods/bworld/textures/birch_fence.png b/mods/bworld/textures/birch_fence.png new file mode 100644 index 0000000..fc8a0e6 Binary files /dev/null and b/mods/bworld/textures/birch_fence.png differ diff --git a/mods/bworld/textures/birch_fence_gate.png b/mods/bworld/textures/birch_fence_gate.png new file mode 100644 index 0000000..a5ef31c Binary files /dev/null and b/mods/bworld/textures/birch_fence_gate.png differ diff --git a/mods/bworld/textures/birch_fence_side.png b/mods/bworld/textures/birch_fence_side.png new file mode 100644 index 0000000..a9e161c Binary files /dev/null and b/mods/bworld/textures/birch_fence_side.png differ diff --git a/mods/bworld/textures/birch_fence_top.png b/mods/bworld/textures/birch_fence_top.png new file mode 100644 index 0000000..810c1a5 Binary files /dev/null and b/mods/bworld/textures/birch_fence_top.png differ diff --git a/mods/bworld/textures/cherry_fence_side.png b/mods/bworld/textures/cherry_fence_side.png new file mode 100644 index 0000000..33c1871 Binary files /dev/null and b/mods/bworld/textures/cherry_fence_side.png differ diff --git a/mods/bworld/textures/cherry_fence_top.png b/mods/bworld/textures/cherry_fence_top.png new file mode 100644 index 0000000..cf8c5bb Binary files /dev/null and b/mods/bworld/textures/cherry_fence_top.png differ diff --git a/mods/bworld/textures/dark_oak_fence_side.png b/mods/bworld/textures/dark_oak_fence_side.png new file mode 100644 index 0000000..914f321 Binary files /dev/null and b/mods/bworld/textures/dark_oak_fence_side.png differ diff --git a/mods/bworld/textures/dark_oak_fence_top.png b/mods/bworld/textures/dark_oak_fence_top.png new file mode 100644 index 0000000..49ab338 Binary files /dev/null and b/mods/bworld/textures/dark_oak_fence_top.png differ diff --git a/mods/bworld/textures/jungle_fence_side.png b/mods/bworld/textures/jungle_fence_side.png new file mode 100644 index 0000000..1b6c88f Binary files /dev/null and b/mods/bworld/textures/jungle_fence_side.png differ diff --git a/mods/bworld/textures/jungle_fence_top.png b/mods/bworld/textures/jungle_fence_top.png new file mode 100644 index 0000000..7b2abf8 Binary files /dev/null and b/mods/bworld/textures/jungle_fence_top.png differ diff --git a/mods/bworld/textures/oak_fence_side.png b/mods/bworld/textures/oak_fence_side.png new file mode 100644 index 0000000..f4fa832 Binary files /dev/null and b/mods/bworld/textures/oak_fence_side.png differ diff --git a/mods/bworld/textures/oak_fence_top.png b/mods/bworld/textures/oak_fence_top.png new file mode 100644 index 0000000..04eca41 Binary files /dev/null and b/mods/bworld/textures/oak_fence_top.png differ diff --git a/mods/bworld/textures/spruce_fence_side.png b/mods/bworld/textures/spruce_fence_side.png new file mode 100644 index 0000000..c02e158 Binary files /dev/null and b/mods/bworld/textures/spruce_fence_side.png differ diff --git a/mods/bworld/textures/spruce_fence_top.png b/mods/bworld/textures/spruce_fence_top.png new file mode 100644 index 0000000..b4dac51 Binary files /dev/null and b/mods/bworld/textures/spruce_fence_top.png differ diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 4cf8339..795509b 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -32,7 +32,7 @@ import { placement_target, set_state_value, } from "$/common/utils.ts"; -import { type Shape, shape_at } from "$/common/block_shapes.ts"; +import { collision_shape_at, type Shape } from "$/common/block_shapes.ts"; import { EXHAUSTION } from "./vitals.ts"; import { ModRuntime, run_guarded, type ServerCommandSource } from "./mod_runtime.ts"; import { @@ -544,8 +544,31 @@ export class GameServer { // changes a block's state bits without anything else happening, see ServerWorld.get_block_value set_block_state(x: number, y: number, z: number, state: number) { const id = this.world.get_block_id(x, y, z); - if (id !== AIR_ID) { + if (id !== AIR_ID && this.world.get_block_value(x, y, z) >>> 16 !== state) { this.world.set_block(x, y, z, id, state); + this.#notify_neighbors(x, y, z); + } + } + + // tells the blocks around one that changed, so they can change with it like a fence connecting to it: their + // components' on_neighbor_change, like minecraft's updateShape + #notify_neighbors(x: number, y: number, z: number) { + const neighbor = { x, y, z, id: this.world.get_block_id(x, y, z) }; + for (const [dx, dy, dz] of NEIGHBORS) { + const [nx, ny, nz] = [x + dx, y + dy, z + dz]; + if (ny < 0 || ny >= CHUNK_HEIGHT) continue; + const id = this.world.get_block_id(nx, ny, nz); + if (id === AIR_ID) continue; + const components = this.mods.components_of(id).filter(({ component }) => component.on_neighbor_change); + if (components.length === 0) continue; + const block = this.mods.block_ref(nx, ny, nz, id); + for (const { mod, id: component_id, component, params } of components) { + run_guarded( + mod, + `${component_id} on_neighbor_change`, + () => component.on_neighbor_change!(block, params, neighbor), + ); + } } } @@ -573,6 +596,7 @@ export class GameServer { } } } + this.#notify_neighbors(x, y, z); // a block standing on this one that can't stand on what it is now breaks, like a crop on farmland that was dug if (y + 1 < CHUNK_HEIGHT) { @@ -1012,7 +1036,7 @@ export class GameServer { const state = placed_state(held.block_id, player); const placing = EverythingRegistry.get("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))) { + if (placing?.has_collision && this.#occupied(tx, ty, tz, collision_shape_at(placing, value))) { this.#correct(player, tx, ty, tz); return; } @@ -1729,7 +1753,10 @@ export class GameServer { if (y < 0 || y >= CHUNK_HEIGHT || !player.chunks.has_block(x, z)) { return; } - this.#send(player, { type: "set_block", x, y, z, id: this.world.get_block_id(x, y, z) }); + // with its states, or the client would show it at its defaults, like a fence that lost its connections + const id = this.world.get_block_id(x, y, z); + const state = this.world.get_block_value(x, y, z) >>> 16; + this.#send(player, state ? { type: "set_block", x, y, z, id, state } : { type: "set_block", x, y, z, id }); } // chunks @@ -1925,6 +1952,9 @@ function death_message(name: string, source: DamageSource) { // minecraft's getStateForPlacement with getHorizontalDirection().getOpposite(). facing is 0 north, 1 east, 2 south, // 3 west, and variants turn the model with it (its north side is the front, like engine:cube's). they look along // (-sin yaw, -cos yaw), so the way back to them is (sin yaw, cos yaw) +// the 6 blocks beside one +const NEIGHBORS = [[-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1]] as const; + function placed_state(block_id: string, player: ServerPlayer): number | undefined { const info = EverythingRegistry.get("blocks", block_id); if (!info?.states?.some((state) => state.name === "facing" && state.bits >= 2)) return undefined; diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index c4d9bb7..10f3f56 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -3,6 +3,7 @@ import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts"; import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts"; import { get_state_value, set_state_value } from "$/common/utils.ts"; +import { covers_face } from "$/common/block_shapes.ts"; import { tag_api } from "$/common/tags.ts"; import type { BlockComponent, @@ -562,6 +563,7 @@ export class ModRuntime { game().set_block_state(x, y, z, new_value >>> 16); return true; }, + is_face_sturdy: (x, y, z, face) => covers_face(game().world.collision_shape(x, y, z), face), get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never, set_block_item: (x, y, z, item) => { if (game().world.get_block_id(x, y, z) === AIR_ID) return; diff --git a/tests/fence_test.ts b/tests/fence_test.ts new file mode 100644 index 0000000..1fb36f6 --- /dev/null +++ b/tests/fence_test.ts @@ -0,0 +1,124 @@ +import { assert, assertEquals } from "@std/assert"; +import { Container, ItemStack } from "$/common/inventory.ts"; +import { CRAFTING_RESULT_SLOT } from "$/common/protocol.ts"; +import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts"; +import { bake_block, block_item_texture, type ModelJson } from "$/common/block_models.ts"; +import { collision_shape_at, covers_face, FULL_SHAPE, shape_at } from "$/common/block_shapes.ts"; +import { move_body } from "$/common/physics.ts"; +import { get_state_value } from "$/common/utils.ts"; +import { update_crafting_result } from "$/server/game/crafting.ts"; +import { test_game } from "./helpers.ts"; + +const Y = 100; + +// a game with the blocks around x 0..4, z 0 at Y cleared, and what's connected where +async function setup() { + const { game } = await test_game("mods"); + for (let x = -1; x <= 5; x++) { + for (let z = -1; z <= 1; z++) game.set_block(x, Y, z, "bworld:air"); + } + const sides = (x: number, z: number) => { + const info = game.world.get_block_info(x, Y, z)!; + const value = game.world.get_block_value(x, Y, z); + return ["north", "east", "south", "west"].filter((side) => get_state_value(value, info, side) === 1); + }; + return { game, sides }; +} + +Deno.test("fences join the fences beside them, and let go when one is broken", async () => { + const { game, sides } = await setup(); + game.set_block(0, Y, 0, "bworld:oak_fence"); + assertEquals(sides(0, 0), []); + game.set_block(1, Y, 0, "bworld:birch_fence"); + game.set_block(2, Y, 0, "bworld:oak_fence"); + assertEquals(sides(0, 0), ["east"]); + assertEquals(sides(1, 0), ["east", "west"]); + assertEquals(sides(2, 0), ["west"]); + + game.set_block(1, Y, 0, "bworld:air"); + assertEquals(sides(0, 0), []); + assertEquals(sides(2, 0), []); +}); + +Deno.test("fences join full sides of solid blocks, but not leaves, plants or a slab's half", async () => { + const { game, sides } = await setup(); + game.set_block(0, Y, 0, "bworld:oak_fence"); + game.set_block(0, Y, -1, "bworld:stone"); + game.set_block(1, Y, 0, "bworld:leaves"); + game.set_block(-1, Y, 0, "bworld:wheat"); + assertEquals(sides(0, 0), ["north"]); + assert(!covers_face([[0, 0, 0, 1, 0.5, 1]], "north")); + assert(covers_face(FULL_SHAPE, "north")); +}); + +Deno.test("a fence is drawn as a post and a bar for each side it joins, and its item is the fence model", async () => { + const { game } = await setup(); + const fence = EverythingRegistry.get("blocks", "bworld:oak_fence")!; + const models = Object.fromEntries(EverythingRegistry.entries("models")); + game.set_block(0, Y, 0, "bworld:oak_fence"); + const alone = bake_block(fence, game.world.get_block_value(0, Y, 0), models); + game.set_block(1, Y, 0, "bworld:oak_fence"); + const joined = bake_block(fence, game.world.get_block_value(0, Y, 0), models); + // a post is 6 faces, a side is two bars of 5 + assertEquals(alone.length, 6); + assertEquals(joined.length, 16); + // the bars on the east side, turned from the side model's north + assert(joined.slice(6).every((quad) => quad.positions.every((v, i) => i % 3 !== 0 || v >= 0.4375))); + assert(joined.every((quad) => quad.texture.startsWith("bworld:oak_fence_"))); + assertEquals(block_item_texture(fence), undefined); +}); + +Deno.test("fences are pointed at by their post and bars, and are too tall to jump over", async () => { + const { game } = await setup(); + game.set_block(0, Y, 0, "bworld:oak_fence"); + game.set_block(1, Y, 0, "bworld:oak_fence"); + const info = game.world.get_block_info(0, Y, 0)!; + const value = game.world.get_block_value(0, Y, 0); + assertEquals(shape_at(info, value).map((box) => box[4]), [1, 1]); + assertEquals(collision_shape_at(info, value).map((box) => box[4]), [1.5, 1.5]); + // a fence on its own is just its post + assertEquals(collision_shape_at(info, 0), [[6 / 16, 0, 6 / 16, 10 / 16, 1.5, 10 / 16]]); + + // standing on top of one, a block and a half up + const body = { x: 0.5, y: Y + 3, z: 0.5, vx: 0, vy: 0, vz: 0, width: 0.6, height: 1.8 }; + for (let i = 0; i < 40; i++) move_body(body, -32, (x, y, z) => game.world.collision_shape(x, y, z)); + assertEquals(body.y, Y + 1.5); + // walking into its side stops at the post, even a block above the fence's bottom + const walker = { x: 0.5, y: Y + 1, z: 2, vx: 0, vy: 0, vz: -4, width: 0.6, height: 1.8 }; + for (let i = 0; i < 20; i++) { + walker.vz = -4; + move_body(walker, 0, (x, y, z) => game.world.collision_shape(x, y, z)); + } + assertEquals(walker.z, 10 / 16 + 0.3); +}); + +Deno.test("six planks and two sticks make three fences of that wood", async () => { + const { game } = await test_game("mods"); + const grid = new Container(10); + for (const slot of [0, 2, 3, 5]) grid.set_item(slot, new ItemStack("bworld:spruce_planks", 1)); + for (const slot of [1, 4]) grid.set_item(slot, new ItemStack("bworld:stick", 1)); + update_crafting_result(grid, game.recipes.shaped); + const result = grid.get_item(CRAFTING_RESULT_SLOT); + assertEquals([result?.type_id, result?.amount], ["bworld:spruce_fence", 3]); +}); + +Deno.test("clicking the ground beside a fence tells the client it's still joined, not a bare post", async () => { + const t = await test_game("mods"); + t.join(1, "alice"); + for (let x = -3; x <= 3; x++) { + for (let z = -3; z <= 3; z++) t.game.set_block(x, 99, z, "bworld:stone"); + } + t.send(1, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch: 0 }); + t.game.tick(); + t.game.set_block(0, 100, 0, "bworld:oak_fence"); + t.game.set_block(1, 100, 0, "bworld:oak_fence"); + const joined = t.game.world.get_block_value(0, 100, 0) >>> 16; + assert(joined !== 0); + t.take(1); + + // a fence is thin, so the ground's top beside its post can be clicked. what would go there is the fence's spot, + // and the server puts back what's really there + t.send(1, { type: "use_block", x: 0, y: 99, z: 0, face: "top" }); + const corrections = t.take(1).filter((m) => m.type === "set_block" && m.x === 0 && m.y === 100 && m.z === 0); + assertEquals(corrections.map((m) => [m.id, m.state]), [["bworld:oak_fence", joined]]); +});