From fbc92669366bd3c2a4dab2f6e4fa398c198bbc4a Mon Sep 17 00:00:00 2001 From: Paula Date: Wed, 7 Oct 2026 19:11:44 -0300 Subject: [PATCH] Animated textures ! --- client/atlas.ts | 41 ++++++- client/client.ts | 2 + client/main.ts | 11 +- client/texture_animations.ts | 101 +++++++++++++++++ common/bmod.ts | 65 +++++++++-- common/constants.ts | 3 + common/mod_check.ts | 3 + common/texture_animation.ts | 104 ++++++++++++++++++ docs/modding/gettingstarted/modfiles.md | 2 + docs/modding/resources/textures.md | 47 +++++++- mods/bworld/blocks/water.json | 2 +- mods/bworld/textures/water.png | Bin 262 -> 0 bytes mods/bworld/textures/water_flow.json | 23 ++++ mods/bworld/textures/water_flow.png | Bin 0 -> 4228 bytes mods/bworld/textures/water_still.json | 8 ++ mods/bworld/textures/water_still.png | Bin 0 -> 1713 bytes server/load_bmods.ts | 1 + tests/texture_animation_test.ts | 139 ++++++++++++++++++++++++ tools/check_mods.ts | 26 ++++- tools/pack_mod.ts | 2 + 20 files changed, 555 insertions(+), 25 deletions(-) create mode 100644 client/texture_animations.ts create mode 100644 common/texture_animation.ts delete mode 100644 mods/bworld/textures/water.png create mode 100644 mods/bworld/textures/water_flow.json create mode 100644 mods/bworld/textures/water_flow.png create mode 100644 mods/bworld/textures/water_still.json create mode 100644 mods/bworld/textures/water_still.png create mode 100644 tests/texture_animation_test.ts diff --git a/client/atlas.ts b/client/atlas.ts index 7b26c17..89affa0 100644 --- a/client/atlas.ts +++ b/client/atlas.ts @@ -2,6 +2,8 @@ // from the textures in the server's .bmod files import { TEXTURE_SIZE } from "$/common/constants.ts"; import type { SpriteRegion } from "$/common/constants.ts"; +import { type Animation, texture_animation, type TextureJson } from "$/common/texture_animation.ts"; +import { AnimatedTexture } from "./texture_animations.ts"; export interface AtlasLayout { // in pixels, a power of two @@ -51,8 +53,10 @@ function pack_shelves(entries: [string, TextureSize][], size: number) { return y + shelf <= size ? regions : undefined; } -// textures are png bytes by id. ones that don't decode show as missing -export async function build_atlas(textures: Map) { +// textures are png bytes by id, texture_json the .json of the ones that have one. ones that don't decode show as +// missing. an animated texture takes one frame's room, its first frame, and plays from animated (see +// texture_animations.ts) +export async function build_atlas(textures: Map, texture_json = new Map()) { const images = new Map(); await Promise.all([...textures].map(async ([id, png]) => { try { @@ -64,7 +68,18 @@ export async function build_atlas(textures: Map) { images.get("engine:missing")?.close(); images.delete("engine:missing"); - const { size, regions } = atlas_layout(new Map([...images].map(([id, image]) => [id, image]))); + const animations = new Map(); + for (const [id, image] of images) { + const json = texture_json.get(id); + const animation = json && texture_animation(json, image); + if (animation) animations.set(id, animation); + } + const sizes = new Map([...images].map(([id, image]) => { + const animation = animations.get(id); + return [id, animation ? { width: animation.frame_width, height: animation.frame_height } : image]; + })); + + const { size, regions } = atlas_layout(sizes); const canvas = new OffscreenCanvas(size, size); const ctx = canvas.getContext("2d")!; @@ -78,8 +93,17 @@ export async function build_atlas(textures: Map) { ctx.fillRect(missing.x + half, missing.y, half, half); ctx.fillRect(missing.x, missing.y + half, half, half); + const animated: AnimatedTexture[] = []; for (const [id, image] of images) { - ctx.drawImage(image, regions[id].x, regions[id].y); + const animation = animations.get(id); + const { x, y, width, height } = regions[id]; + if (animation) { + const first = animation.frames[0]; + ctx.drawImage(image, first.x, first.y, width, height, x, y, width, height); + animated.push(new AnimatedTexture(regions[id], animation, image_pixels(image), image.width)); + } else { + ctx.drawImage(image, x, y); + } image.close(); } for (const id of textures.keys()) { @@ -100,7 +124,14 @@ export async function build_atlas(textures: Map) { opaque.set(id, { width: region.width, height: region.height, mask }); } - return { image: canvas.transferToImageBitmap(), regions }; + return { image: canvas.transferToImageBitmap(), regions, animated }; +} + +// every frame of an animated texture stays in memory, to copy into the atlas when it's that frame's turn +function image_pixels(image: ImageBitmap) { + const ctx = new OffscreenCanvas(image.width, image.height).getContext("2d")!; + ctx.drawImage(image, 0, 0); + return ctx.getImageData(0, 0, image.width, image.height).data; } // a texture's pixels, 1 (can be seen) or 0, row by row from the top diff --git a/client/client.ts b/client/client.ts index cf56438..400247f 100644 --- a/client/client.ts +++ b/client/client.ts @@ -24,6 +24,7 @@ import { Container } from "$/common/inventory.ts"; import { PLAYER_MENU } from "$/common/protocol.ts"; import { EverythingRegistry } from "$/common/everything_registry.ts"; import type { EntityJson } from "$/common/mod_data.ts"; +import { tick_texture_animations } from "./texture_animations.ts"; // how far from the eyes entities can be hit, like minecraft const ENTITY_REACH = 3; @@ -194,6 +195,7 @@ export class Client { this.connection.send({ type: "view_distance", distance: view_distance }); } this.level.tick(); + tick_texture_animations(); } // closed_screen: a screen closed this frame and took its keys, so they don't also open the inventory or pick a diff --git a/client/main.ts b/client/main.ts index 8cb6558..9d065d9 100644 --- a/client/main.ts +++ b/client/main.ts @@ -6,11 +6,14 @@ import { Options } from "./options.ts"; import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress } from "./handshake.ts"; import { build_atlas, engine_textures } from "./atlas.ts"; import { confirm_mods } from "./confirm_mods.ts"; +import { set_texture_animations } from "./texture_animations.ts"; +import type { TextureJson } from "$/common/texture_animation.ts"; import { ModLoadError } from "$/common/mod_loader.ts"; import { begin_drawing, canvas, clear_background, + device, end_drawing, init_font, init_window, @@ -136,12 +139,16 @@ async function join_server(address: ServerAddress, name: string, status: (text: status("Downloading the server's mods..."); const bmods = await download_mods(welcome.mods, address.base); const textures = await engine_textures(); + const texture_json = new Map(); for (const bmod of bmods) { for (const [id, png] of bmod.textures) textures.set(id, png); + for (const [id, json] of bmod.texture_json ?? []) texture_json.set(id, json); } - const atlas = await build_atlas(textures); + const atlas = await build_atlas(textures, texture_json); loaded_mods = true; - AssetManager.instance.assets["bworld:textures"] = load_texture(atlas.image); + const atlas_texture = load_texture(atlas.image); + set_texture_animations(atlas_texture.tex, device.queue, atlas.animated); + AssetManager.instance.assets["bworld:textures"] = atlas_texture; AssetManager.instance.assets["bworld:textures_info"] = atlas.regions; await load_client_mods(welcome.mods, bmods); console.log(`Mods: ${welcome.mods.map((mod) => `${mod.id} ${mod.version}`).join(", ") || "none"}`); diff --git a/client/texture_animations.ts b/client/texture_animations.ts new file mode 100644 index 0000000..2df517e --- /dev/null +++ b/client/texture_animations.ts @@ -0,0 +1,101 @@ +// animated textures play like minecraft's: the atlas holds one frame of each, and every tick the ones whose frame +// changed copy the new frame's pixels over it. models never change, only the atlas does +import type { SpriteRegion } from "$/common/constants.ts"; +import type { Animation } from "$/common/texture_animation.ts"; + +// pixels to copy into a texture's place in the atlas: frame_width × frame_height of them, starting at offset bytes +// into data, rows bytes_per_row apart +export interface FrameUpload { + data: Uint8ClampedArray; + offset: number; + bytes_per_row: number; +} + +export class AnimatedTexture { + // which of animation.frames shows, and how many ticks it has shown for + #frame = 0; + #ticks = 0; + // the frame blended into the next one, for animations that interpolate + readonly #blended: Uint8ClampedArray; + + // pixels is the whole png, rgba row by row, image_width pixels wide + constructor( + readonly region: SpriteRegion, + readonly animation: Animation, + readonly pixels: Uint8ClampedArray, + readonly image_width: number, + ) { + this.#blended = new Uint8ClampedArray(animation.frame_width * animation.frame_height * 4); + } + + // one tick on, and what to copy into the atlas if the texture looks different now + tick(): FrameUpload | undefined { + const frames = this.animation.frames; + const current = frames[this.#frame]; + this.#ticks += 1; + if (this.#ticks >= current.time) { + this.#ticks = 0; + this.#frame = (this.#frame + 1) % frames.length; + const next = frames[this.#frame]; + if (next.x !== current.x || next.y !== current.y) return this.#frame_upload(next); + } else if (this.animation.interpolate) { + const next = frames[(this.#frame + 1) % frames.length]; + if (next.x !== current.x || next.y !== current.y) { + return this.#blend(current, next, this.#ticks / current.time); + } + } + return undefined; + } + + #frame_upload(frame: { x: number; y: number }): FrameUpload { + return { + data: this.pixels, + offset: (frame.y * this.image_width + frame.x) * 4, + bytes_per_row: this.image_width * 4, + }; + } + + // the colour moves from one frame to the next, the see-through-ness stays the current frame's, like minecraft + #blend(from: { x: number; y: number }, to: { x: number; y: number }, amount: number): FrameUpload { + const { frame_width, frame_height } = this.animation; + for (let y = 0; y < frame_height; y++) { + for (let x = 0; x < frame_width; x++) { + const a = ((from.y + y) * this.image_width + from.x + x) * 4; + const b = ((to.y + y) * this.image_width + to.x + x) * 4; + const out = (y * frame_width + x) * 4; + for (let c = 0; c < 3; c++) { + this.#blended[out + c] = this.pixels[a + c] + (this.pixels[b + c] - this.pixels[a + c]) * amount; + } + this.#blended[out + 3] = this.pixels[a + 3]; + } + } + return { data: this.#blended, offset: 0, bytes_per_row: frame_width * 4 }; + } +} + +let atlas: GPUTexture | undefined; +let queue: GPUQueue | undefined; +let animated: AnimatedTexture[] = []; + +// the atlas just made and its animated textures, replacing the last server's +export function set_texture_animations(texture: GPUTexture, gpu_queue: GPUQueue, textures: AnimatedTexture[]) { + atlas = texture; + queue = gpu_queue; + animated = textures; +} + +// once a tick, like minecraft's TextureAtlas.cycleAnimationFrames +export function tick_texture_animations() { + if (!atlas || !queue) return; + for (const texture of animated) { + const upload = texture.tick(); + if (!upload) continue; + const { region, animation } = texture; + queue.writeTexture( + { texture: atlas, origin: [region.x, region.y] }, + upload.data, + { offset: upload.offset, bytesPerRow: upload.bytes_per_row }, + [animation.frame_width, animation.frame_height], + ); + } +} diff --git a/common/bmod.ts b/common/bmod.ts index c8b3add..7fdc600 100644 --- a/common/bmod.ts +++ b/common/bmod.ts @@ -2,7 +2,7 @@ // docs/modding/gettingstarted/modfiles.md. the same code reads them on the server and in the browser, so it only works on bytes import { unzipSync, zipSync } from "fflate"; import type { ModelJson } from "./block_models.ts"; -import { MAX_TEXTURE_SIZE } from "./constants.ts"; +import { MAX_ANIMATED_TEXTURE_SIZE, MAX_TEXTURE_SIZE } from "./constants.ts"; import { type BlockJson, type EffectJson, @@ -28,6 +28,7 @@ import { validate_tag, } from "./mod_data.ts"; import type { ModData } from "./mod_loader.ts"; +import { texture_animation, type TextureJson, validate_texture_json } from "./texture_animation.ts"; import { ENGINE_GLOBAL } from "./hooks.ts"; export const BMOD_EXTENSION = ".bmod"; @@ -48,6 +49,8 @@ export interface Bmod { scripts: Partial>; // png bytes by texture id, like copper_tools:copper_block textures: Map; + // the .json of the textures that have one, like animated ones, by texture id + texture_json?: Map; credits?: string; } @@ -63,6 +66,7 @@ export class BmodError extends Error { // data.json every block, model, item, recipe, ore, entity, entity model, effect and tag // scripts/.js // textures/.png the texture : +// textures/.json its animation, if it has one // credits.md export function write_bmod(bmod: Bmod): Uint8Array { const text = (value: string) => new TextEncoder().encode(value); @@ -85,6 +89,9 @@ export function write_bmod(bmod: Bmod): Uint8Array { for (const [id, png] of bmod.textures) { files[`textures/${id.split(":")[1]}.png`] = png; } + for (const [id, json] of bmod.texture_json ?? []) { + files[`textures/${id.split(":")[1]}.json`] = text(JSON.stringify(json)); + } files["manifest.json"] = text(JSON.stringify(manifest, null, "\t")); files["data.json"] = text(JSON.stringify(bmod.data)); @@ -115,7 +122,7 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod { } const problems: string[] = []; - const json = (name: string): unknown => { + const parse = (name: string): unknown => { const content = files[name]; if (!content) { problems.push(`${name} is missing`); @@ -130,8 +137,8 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod { }; const text = (name: string) => files[name] && new TextDecoder().decode(files[name]); - const manifest = json("manifest.json") as ManifestJson | undefined; - const raw_data = json("data.json") as Partial | undefined; + const manifest = parse("manifest.json") as ManifestJson | undefined; + const raw_data = parse("data.json") as Partial | undefined; if (!manifest || !raw_data) throw new BmodError(file, problems); for (const problem of validate_manifest(manifest, manifest.id)) problems.push(`manifest.json: ${problem}`); @@ -179,7 +186,8 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod { problems.push(`manifest.json: credits ${manifest.credits} isn't in the file`); } - const textures = new Map(); + // sizes are checked once it's known which textures are animated + const pngs = new Map(); for (const [name, content] of Object.entries(files)) { const match = name.match(/^textures\/(.+)\.png$/); if (!match) continue; @@ -189,15 +197,38 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod { problems.push(`${name}: texture names must be a-z, 0-9 and _`); } else if (!size) { problems.push(`${name}: isn't a png`); - } else if (texture_size_problem(size)) { - problems.push(`${name}: ${texture_size_problem(size)}`); } else { - textures.set(id, content); + pngs.set(id, content); + } + } + const texture_json = new Map(); + for (const name of Object.keys(files)) { + const match = name.match(/^textures\/(.+)\.json$/); + if (!match) continue; + const id = `${mod}:${match[1]}`; + const png = pngs.get(id); + if (!png) { + problems.push(`${name}: there's no textures/${match[1]}.png for it to go with`); + continue; + } + const json = parse(name); + if (json === undefined) continue; + const json_problems = validate_texture_json(json, png_size(png)!); + for (const problem of json_problems) problems.push(`${name}: ${problem}`); + if (json_problems.length === 0) texture_json.set(id, json as TextureJson); + } + const textures = new Map(); + for (const [id, png] of pngs) { + const problem = texture_size_problem(png_size(png)!, texture_json.get(id)); + if (problem) { + problems.push(`textures/${id.split(":")[1]}.png: ${problem}`); + } else { + textures.set(id, png); } } if (problems.length > 0) throw new BmodError(file, problems); - return { manifest, data, scripts, textures, credits }; + return { manifest, data, scripts, textures, texture_json, credits }; } // the same mod without its server and worldgen scripts, what players get. the server sends them the world @@ -220,9 +251,21 @@ function checked(list: unknown, name: string, validate: (json: unknown) => strin return list; } -// textures can be any size up to MAX_TEXTURE_SIZE, like 64×32 for an entity. blocks and items stretch theirs to fit -export function texture_size_problem(size: { width: number; height: number }): string | undefined { +// textures can be any size up to MAX_TEXTURE_SIZE, like 64×32 for an entity. blocks and items stretch theirs to fit. +// for an animated one (json is its .json) that's each frame's size +export function texture_size_problem(size: { width: number; height: number }, json?: TextureJson): string | undefined { const { width, height } = size; + const animation = json && texture_animation(json, size); + if (animation) { + const { frame_width, frame_height } = animation; + if (width > MAX_ANIMATED_TEXTURE_SIZE || height > MAX_ANIMATED_TEXTURE_SIZE) { + return `is ${width}×${height}, animated textures can be at most ${MAX_ANIMATED_TEXTURE_SIZE}×${MAX_ANIMATED_TEXTURE_SIZE}`; + } + if (frame_width > MAX_TEXTURE_SIZE || frame_height > MAX_TEXTURE_SIZE) { + return `has ${frame_width}×${frame_height} frames, textures can be at most ${MAX_TEXTURE_SIZE}×${MAX_TEXTURE_SIZE}`; + } + return undefined; + } if (width < 1 || height < 1 || width > MAX_TEXTURE_SIZE || height > MAX_TEXTURE_SIZE) { return `is ${width}×${height}, textures can be at most ${MAX_TEXTURE_SIZE}×${MAX_TEXTURE_SIZE}`; } diff --git a/common/constants.ts b/common/constants.ts index 6ede867..dc8da2d 100644 --- a/common/constants.ts +++ b/common/constants.ts @@ -3,6 +3,9 @@ export const TEXTURE_SIZE = 16; // the most a texture can be on either side, entity sprites are bigger than blocks' export const MAX_TEXTURE_SIZE = 256; +// the most an animated texture's png can be on either side, all its frames together. each frame is a texture, at most +// MAX_TEXTURE_SIZE +export const MAX_ANIMATED_TEXTURE_SIZE = 4096; // the game's version, what mods' game_version is checked against. mods with engine_access are tied to its minor version export const GAME_VERSION = "0.1.0"; diff --git a/common/mod_check.ts b/common/mod_check.ts index 677e7af..2339965 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -17,6 +17,7 @@ import { import { PLAYER_PARTS } from "./everything_registry.ts"; import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts"; import { resolve_tags } from "./tags.ts"; +import type { TextureJson } from "./texture_animation.ts"; import { BIOMES } from "./worldgen/overworld.ts"; export interface ModReport { @@ -43,6 +44,8 @@ export interface LoadedMod { textures: string[]; // absolute paths by texture id texture_files: Map; + // textures/.json by texture id, for the textures that have one (see texture_animation.ts) + texture_json: Map; } // dependencies before the mods that need them, otherwise alphabetical diff --git a/common/texture_animation.ts b/common/texture_animation.ts new file mode 100644 index 0000000..d05c32e --- /dev/null +++ b/common/texture_animation.ts @@ -0,0 +1,104 @@ +// animated textures, like minecraft's .png.mcmeta and in the same format: textures/.json next to +// textures/.png says how to cut the png into frames and how long each one shows. see docs/modding/resources/textures.md +export interface TextureJson { + animation?: AnimationJson; +} + +export interface AnimationJson { + // ticks each frame shows unless the frame says otherwise, 1 if not given + frametime?: number; + // blend each frame into the next a tick at a time instead of switching + interpolate?: boolean; + // the order to show frames in, by index or { index, time }. every frame in order if not given + frames?: (number | { index: number; time: number })[]; + // a frame's size in pixels. frames are square, as wide as the png is or as tall if that's less, if not given + width?: number; + height?: number; +} + +// an animation ready to play +export interface Animation { + frame_width: number; + frame_height: number; + interpolate: boolean; + frames: { x: number; y: number; time: number }[]; +} + +// what's wrong with a texture's .json, for the png it goes with +export function validate_texture_json(json: unknown, size: { width: number; height: number }): string[] { + if (!is_object(json)) return [`must be { "animation": { ... } }`]; + if (json.animation === undefined) return []; + const animation = json.animation; + if (!is_object(animation)) return ["animation must be an object"]; + + const problems: string[] = []; + const ticks = (value: unknown) => Number.isInteger(value) && (value as number) >= 1; + if (animation.frametime !== undefined && !ticks(animation.frametime)) { + problems.push("animation.frametime must be a whole number of ticks, at least 1"); + } + if (animation.interpolate !== undefined && typeof animation.interpolate !== "boolean") { + problems.push("animation.interpolate must be true or false"); + } + for (const key of ["width", "height"] as const) { + if (animation[key] !== undefined && !ticks(animation[key])) { + problems.push(`animation.${key} must be a whole number of pixels, at least 1`); + } + } + if (problems.length > 0) return problems; + + const { frame_width, frame_height } = frame_size(animation as AnimationJson, size); + if (size.width % frame_width !== 0 || size.height % frame_height !== 0) { + return [ + `the png is ${size.width}×${size.height}, which doesn't split into ${frame_width}×${frame_height} frames`, + ]; + } + const count = (size.width / frame_width) * (size.height / frame_height); + + if (animation.frames !== undefined) { + if (!Array.isArray(animation.frames) || animation.frames.length === 0) { + problems.push("animation.frames must be a list of frames"); + } else { + animation.frames.forEach((frame, i) => { + const index = is_object(frame) ? frame.index : frame; + if (!Number.isInteger(index) || index < 0 || index >= count) { + problems.push(`animation.frames[${i}]: the png has frames 0 to ${count - 1}`); + } + if (is_object(frame) && !ticks(frame.time)) { + problems.push(`animation.frames[${i}]: time must be a whole number of ticks, at least 1`); + } + }); + } + } + return problems; +} + +// the animation in a texture's .json, which validate_texture_json passed. undefined if it isn't animated +export function texture_animation(json: TextureJson, size: { width: number; height: number }): Animation | undefined { + const animation = json.animation; + if (!animation) return undefined; + const { frame_width, frame_height } = frame_size(animation, size); + const columns = size.width / frame_width; + const frametime = animation.frametime ?? 1; + const order = animation.frames ?? + Array.from({ length: columns * (size.height / frame_height) }, (_, i) => i); + + // frames are read from the png like text, left to right then top to bottom + const frames = order.map((frame) => { + const index = typeof frame === "number" ? frame : frame.index; + return { + x: (index % columns) * frame_width, + y: Math.floor(index / columns) * frame_height, + time: typeof frame === "number" ? frametime : frame.time, + }; + }); + return { frame_width, frame_height, interpolate: animation.interpolate ?? false, frames }; +} + +function frame_size(animation: AnimationJson, size: { width: number; height: number }) { + const side = Math.min(size.width, size.height); + return { frame_width: animation.width ?? side, frame_height: animation.height ?? side }; +} + +function is_object(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/docs/modding/gettingstarted/modfiles.md b/docs/modding/gettingstarted/modfiles.md index f6b1c3b..a48c24e 100644 --- a/docs/modding/gettingstarted/modfiles.md +++ b/docs/modding/gettingstarted/modfiles.md @@ -22,6 +22,7 @@ mods/ worldgen/ores.json worldgen/spawns.json # monsters that spawn on their own, see entities/index.md textures/*.png + textures/*.json # animations, see resources/textures.md scripts/ server.ts # game logic, never sent to players client.ts # sent to players @@ -119,6 +120,7 @@ copper_tools.bmod scripts/worldgen.js scripts/shared.js textures/.png + textures/.json # for animated textures credits.md ``` diff --git a/docs/modding/resources/textures.md b/docs/modding/resources/textures.md index 1a931e5..fd28f22 100644 --- a/docs/modding/resources/textures.md +++ b/docs/modding/resources/textures.md @@ -15,8 +15,51 @@ Any mod can use any texture by its id, including the base game's, like `bworld:s ## Sizes -Textures can be any size up to 256×256. Blocks and items are made for 16×16 and stretch a texture of another size over -the same face, so a 32×32 block texture is just a sharper one. Larger ones are for things like entity skins. +Textures can be any size up to 256×256 (for [animated ones](#animated-textures), each frame). Blocks and items are made +for 16×16 and stretch a texture of another size over the same face, so a 32×32 block texture is just a sharper one. +Larger ones are for things like entity skins. + +## Animated Textures + +A texture animates when a `.json` with the same name sits next to its `.png`, like Minecraft's `.png.mcmeta` and in the +same format. The png holds every frame, square ones stacked top to bottom by default: + +``` +textures/lava_lamp.png 16×64, four 16×16 frames +textures/lava_lamp.json +``` + +```json +{ + "animation": { + "frametime": 2, + "interpolate": false, + "frames": [0, 1, 2, { "index": 3, "time": 10 }, 2, 1], + "width": 16, + "height": 16 + } +} +``` + +Every field is optional, so `{ "animation": {} }` plays every frame in order, one tick each. + +| Field | What it does | +| ------------- | ----------------------------------------------------------------------------------------------- | +| `frametime` | Ticks each frame shows, 1 if not given. There are 20 ticks a second. | +| `interpolate` | Blends each frame into the next a tick at a time instead of switching. | +| `frames` | The order to show frames in, by index or `{ "index", "time" }`. Every frame in order otherwise. | +| `width` | A frame's width in pixels. | +| `height` | A frame's height in pixels. | + +Without `width` and `height`, frames are square and as big as the png's shorter side. Frames are counted like reading +text, left to right then top to bottom, so a png can hold them in a grid as well as a strip. + +Blocks, items and entities use an animated texture's id like any other and get the current frame. The size limit applies +to a frame, and the whole png can be at most 4096×4096. + +Every block using a texture shows the same frame at the same time. Each tick, the client copies the new frame of every +animated texture whose frame changed into the atlas, and interpolated ones every tick. Long `frametime`s are cheaper +than short ones. ## Missing Textures diff --git a/mods/bworld/blocks/water.json b/mods/bworld/blocks/water.json index c2206ba..3b542d1 100644 --- a/mods/bworld/blocks/water.json +++ b/mods/bworld/blocks/water.json @@ -2,7 +2,7 @@ "format_version": 1, "block": { "id": "bworld:water", - "textures": "bworld:water", + "textures": "bworld:water_still", "tint": { "color": "water" }, "render_layer": "translucent", "light_opacity": 1, diff --git a/mods/bworld/textures/water.png b/mods/bworld/textures/water.png deleted file mode 100644 index f95f38407648605eb3588f60370e06034ecf0da8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 262 zcmV+h0r~!kP)rB&zVA-}5D_FI0sue~0AOaQAUVGc z+<@e4ULo&CXa5HzvGwMNxLBwV5x6@5KvmxgvPo4>#byR~|EO>zTa|SO5rK%D6uSEn zVwFa6vQ~n-^H?R`i@UwVmQu1IBEF8WTHQL^r{WrBF4ESEGYb)!vg;;hkS7auW$UG? zUe>s)9cDI*x_2|X-GLk_u=p1$RQ2>QNvP^E#>%$BO5slm`a_-Q1*-^qT-lcfnE(I) M07*qoM6N<$g2!fRX8-^I diff --git a/mods/bworld/textures/water_flow.json b/mods/bworld/textures/water_flow.json new file mode 100644 index 0000000..2a0afda --- /dev/null +++ b/mods/bworld/textures/water_flow.json @@ -0,0 +1,23 @@ +{ + + "animation": { + + "frametime": 1, + + "frames": [ +0, + 1, 2, 3, 4, + 5, + 6, 7, + 8, + 9, 10, + 11, + 12, + 13, + 14, 15 +] + + } + +} + diff --git a/mods/bworld/textures/water_flow.png b/mods/bworld/textures/water_flow.png new file mode 100644 index 0000000000000000000000000000000000000000..f3b7ff9b4e15961348f11150992f5d7310fae83b GIT binary patch literal 4228 zcmZ`-eLT~9|Nd@9sAb1P_bA8IQXNcn z#4QXZ71=~lDcs4NBep2XJj`LoTC?x(^PSGq{k!i!yvFw8{eEBX>wR61PU+a5X??c6P7UP+T&BZ+LapO(3p5JOqym(5vn3<&f z`2HV^PDy_hZ$3Y4Xcz3o1n)$6WBqH1BE!xe_$$$zkO_13n*CE)Nn*b=%Ujzhz8!hGm8TDBqN7fA+g*}z z(f8?+&i+R&$get8vfocmj2$21y+CcpcxjC-suR<+Ssl$NWnRv;01uBW z<&q1EL%?~bBa{iUPm&kfl`bmYP{rXR&z zUezX>1JBRFb&HF?%;OhOGkOR8;s5M(viNSxFUWusju?iPlXOB(Q;)u2l)CJbgro<5 zSacB$C1-Zi?p+4^Sy}#9JpOm}S+!^J9oN$GS}V6r)s2x7w%%e*{&XLdVK$gL+Dq5> zSAX)IDw_6~pK#NBb%DvEf~x(w?7FXh`w+HT`I2p+4x#m~^I|rF6}ap^+3cps`!N&V zXryaSkz9Z#dW4bADS!w8()gub%6G&#=>EEk+36|BU8D#5P+V;A1+B+nk!_4vd4)th#AP zmJ8Qmv8Yrp?4usuteTCRL}*of1Qiel)=~miUf!=+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_still.json new file mode 100644 index 0000000..65c3bf7 --- /dev/null +++ b/mods/bworld/textures/water_still.json @@ -0,0 +1,8 @@ +{ + "animation": { + "frametime": 10, + "interpolate": true, + "frames": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + } +} + diff --git a/mods/bworld/textures/water_still.png b/mods/bworld/textures/water_still.png new file mode 100644 index 0000000000000000000000000000000000000000..602f3a621c420610a49cb0a175a7c65831439c04 GIT binary patch literal 1713 zcmZXVdr;F?7RPTw5*lIM*X$Vp(PxG^}B?b-Cb;@HSAr6qA7$StH1OglC?#y=gk2~i+X3qEC z&$;KE%OAx>lU=sC0077_?5KE$bprqc-XS<<9q|is4ui{J9bo~`EG4a^;T>xtmz~H5 zz*V(AFcJ6!ieq!D;Lr&{LSDKcKaF=5aMLn#1=QTL0w|OkL=E0=g)+YafIy9jVjU|; z8LwvLdjHw&gTkVzuD(OO&W$d0(@(z5%JeI1c|*ePDW9*O_@sBb2Sw4m39~u7*U*%z zs!Dpc*oJSj5;-Ew;ED@u)0n7i=@6OYq`s<7j3pt{nTOu9&$y8%eo{<`lq}wj7dpMT zegqtIoDq+v2MVi`lwb?*jIPDd2T9`5hJ{ntq4wJcm!n}@VzuPafrB&^`DGVx(^4(J zRhJ6FV_k#Tzvf|*W%u^^OiAWyhCz5iPIGbMK+k<7-67?Pi;l#|M~ubcqMD8Y?m+#%kB>%dj@xhUd9(t&s&-c25R!qq*uNLjHX99gPEkp=2iw2${3=d_yewqC3{4@2g4C zp{E0p?>Tlt*a>wfJFpRx$-$|S zewY6bRsw0d0Lv}LD}w{1a4)D>WPJ@0HA!@Bqvcl-2{}ia&b#NWQO=WPPq)g!Lh6H! z6sP*pkRXVqpdr6lsFPEYDA>6MA<5=WiMwV33wC8c?i?%G4ezA!sQG$q*N3$K!nU@> z$VG=noHI-6Z_WRP=8T*%DZtT`CC@jt{4m=N>0)uMzt}!nIE|BC>4WlnI`9nE0g*2y zJ~@O@>}B+02*=ONMD1dAXgA51dr1CDT$Qy_{+Z*~F|8vFB wV)cy-k?I%X)uR5MN)16;)9DcLnO<6E^5J~aJZ~Vu(Oy8zp|~i;UpOWI0!GLx$N&HU literal 0 HcmV?d00001 diff --git a/server/load_bmods.ts b/server/load_bmods.ts index 3140cf3..ede1432 100644 --- a/server/load_bmods.ts +++ b/server/load_bmods.ts @@ -108,6 +108,7 @@ function as_loaded_mod(file: string, bmod: Bmod): LoadedMod { tags: entries(bmod.data.tags), textures: [...bmod.textures.keys()], texture_files: new Map(), + texture_json: new Map(bmod.texture_json), }; } diff --git a/tests/texture_animation_test.ts b/tests/texture_animation_test.ts new file mode 100644 index 0000000..a6ec6ab --- /dev/null +++ b/tests/texture_animation_test.ts @@ -0,0 +1,139 @@ +// animated textures: textures/.json, carrying it through .bmod files, and playing it a tick at a time +import { assertEquals, assertThrows } from "@std/assert"; +import { zipSync } from "fflate"; +import { read_bmod, texture_size_problem } from "$/common/bmod.ts"; +import { texture_animation, validate_texture_json } from "$/common/texture_animation.ts"; +import { AnimatedTexture } from "$/client/texture_animations.ts"; +import { load_and_check } from "$/tools/check_mods.ts"; +import { pack_mod } from "$/tools/pack_mod.ts"; +import { create_mod } from "$/tools/new_mod.ts"; +import { copy_dir } from "./helpers.ts"; + +// a png's header and nothing else, enough for everything that only reads its size +function png_header(width: number, height: number) { + const bytes = new Uint8Array(24); + bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + new DataView(bytes.buffer).setUint32(16, width); + new DataView(bytes.buffer).setUint32(20, height); + return bytes; +} + +Deno.test("an animation is cut into square frames down the png unless it says otherwise", () => { + const strip = texture_animation({ animation: { frametime: 2 } }, { width: 16, height: 48 })!; + assertEquals(strip.frame_width, 16); + assertEquals(strip.frame_height, 16); + assertEquals(strip.interpolate, false); + assertEquals(strip.frames, [{ x: 0, y: 0, time: 2 }, { x: 0, y: 16, time: 2 }, { x: 0, y: 32, time: 2 }]); + + // a grid is read left to right then top to bottom, and frames can repeat with their own times + const grid = texture_animation( + { animation: { width: 8, height: 8, frames: [3, { index: 1, time: 5 }, 3] } }, + { width: 16, height: 16 }, + )!; + assertEquals(grid.frames, [{ x: 8, y: 8, time: 1 }, { x: 8, y: 0, time: 5 }, { x: 8, y: 8, time: 1 }]); + + assertEquals(texture_animation({}, { width: 16, height: 16 }), undefined); +}); + +Deno.test("a texture's .json that doesn't fit its png says why", () => { + const size = { width: 16, height: 48 }; + assertEquals(validate_texture_json({ animation: {} }, size), []); + assertEquals(validate_texture_json([], size), ['must be { "animation": { ... } }']); + assertEquals(validate_texture_json({ animation: { frametime: 0 } }, size), [ + "animation.frametime must be a whole number of ticks, at least 1", + ]); + assertEquals(validate_texture_json({ animation: { height: 20 } }, size), [ + "the png is 16×48, which doesn't split into 16×20 frames", + ]); + assertEquals(validate_texture_json({ animation: { frames: [0, 3, { index: 1 }] } }, size), [ + "animation.frames[1]: the png has frames 0 to 2", + "animation.frames[2]: time must be a whole number of ticks, at least 1", + ]); +}); + +Deno.test("an animated texture's frames have to fit the size limit, not its whole strip", () => { + const animated = { animation: {} }; + assertEquals(texture_size_problem({ width: 16, height: 512 }), "is 16×512, textures can be at most 256×256"); + assertEquals(texture_size_problem({ width: 16, height: 512 }, animated), undefined); + assertEquals( + texture_size_problem({ width: 512, height: 1024 }, animated), + "has 512×512 frames, textures can be at most 256×256", + ); + assertEquals( + texture_size_problem({ width: 16, height: 8192 }, animated), + "is 16×8192, animated textures can be at most 4096×4096", + ); +}); + +Deno.test("a texture's .json is checked, packed into the .bmod and read back", async () => { + const sources = Deno.makeTempDirSync({ prefix: "bworld_anim_src_" }); + copy_dir("mods/bworld", `${sources}/bworld`); + create_mod("lava_lamps", "Lava Lamps", sources); + const textures = `${sources}/lava_lamps/textures`; + Deno.mkdirSync(`${textures}/lamps`, { recursive: true }); + Deno.writeFileSync(`${textures}/lamps/goo.png`, png_header(16, 64)); + const json = { animation: { frametime: 3, interpolate: true } }; + Deno.writeTextFileSync(`${textures}/lamps/goo.json`, JSON.stringify(json)); + + const lamps = () => load_and_check(sources).find((m) => m.id === "lava_lamps")!; + const mod = lamps(); + assertEquals(mod.report.errors, []); + const bmod = read_bmod(await pack_mod(mod), "lava_lamps.bmod"); + assertEquals([...bmod.texture_json!], [["lava_lamps:lamps_goo", json]]); + + // a .json without its png, or one that doesn't fit it, is an error + Deno.writeTextFileSync(`${textures}/stray.json`, JSON.stringify(json)); + Deno.writeTextFileSync( + `${textures}/lamps/goo.json`, + JSON.stringify({ animation: { width: 5 } }), + ); + const broken = lamps(); + assertEquals(broken.report.errors, [ + "textures/lamps/goo.json: the png is 16×64, which doesn't split into 5×16 frames", + "textures/stray.json: there's no stray.png for it to go with", + ]); + Deno.removeSync(sources, { recursive: true }); + + const text = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)); + const manifest = { format_version: 1, id: "broken", name: "Broken", version: "1.0.0" }; + assertThrows( + () => + read_bmod( + zipSync({ + "manifest.json": text(manifest), + "data.json": text({}), + "textures/goo.png": png_header(16, 32), + "textures/goo.json": text({ animation: { frames: [2] } }), + }), + "broken.bmod", + ), + Error, + "textures/goo.json: animation.frames[0]: the png has frames 0 to 1", + ); +}); + +// a 1 pixel wide strip of frames, each frame's red being its index × 100 +function strip(animation: { frametime?: number; interpolate?: boolean; frames?: number[] }, count: number) { + const pixels = new Uint8ClampedArray(count * 4); + for (let i = 0; i < count; i++) pixels.set([i * 100, 0, 0, 255], i * 4); + const parsed = texture_animation({ animation }, { width: 1, height: count })!; + return new AnimatedTexture({ x: 0, y: 0, width: 1, height: 1 }, parsed, pixels, 1); +} + +// what's in the atlas after each of ticks ticks, the red of it, or undefined for ticks that change nothing +function play(texture: AnimatedTexture, ticks: number) { + return Array.from({ length: ticks }, () => { + const upload = texture.tick(); + return upload && upload.data[upload.offset]; + }); +} + +Deno.test("an animation changes the atlas only on the ticks its frame changes", () => { + assertEquals(play(strip({ frametime: 2 }, 3), 7), [undefined, 100, undefined, 200, undefined, 0, undefined]); + // a frame shown twice in a row doesn't copy itself over itself + assertEquals(play(strip({ frames: [0, 0, 1] }, 2), 4), [undefined, 100, 0, undefined]); +}); + +Deno.test("an interpolated animation blends towards the next frame every tick", () => { + assertEquals(play(strip({ frametime: 4, interpolate: true }, 2), 8), [25, 50, 75, 100, 75, 50, 25, 0]); +}); diff --git a/tools/check_mods.ts b/tools/check_mods.ts index a35fb2f..e20551d 100644 --- a/tools/check_mods.ts +++ b/tools/check_mods.ts @@ -19,6 +19,7 @@ import { } from "$/common/mod_data.ts"; import { check_references, load_order, type LoadedMod, type ModReport } from "$/common/mod_check.ts"; import { png_size, texture_size_problem } from "$/common/bmod.ts"; +import { type TextureJson, validate_texture_json } from "$/common/texture_animation.ts"; import { dirname } from "@std/path"; export { load_order, type LoadedMod, type ModReport }; @@ -81,6 +82,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod { tags: [], textures: [], texture_files: new Map(), + texture_json: new Map(), }; const error = (message: string) => mod.report.errors.push(message); @@ -214,11 +216,27 @@ function load_mod(mods_dir: string, id: string): LoadedMod { mod.textures.push(texture_id); mod.texture_files.set(texture_id, `${dir}/textures/${file}`); const size = png_size(Deno.readFileSync(`${dir}/textures/${file}`)); - if (!size) { - error(`textures/${file}: isn't a png`); - } else if (texture_size_problem(size)) { - error(`textures/${file}: ${texture_size_problem(size)}`); + if (!size) error(`textures/${file}: isn't a png`); + } + for (const file of walk(`${dir}/textures`, ".json")) { + const texture_id = `${id}:${file.replace(/\.json$/, "").replaceAll("/", "_")}`; + const png = mod.texture_files.get(texture_id); + if (!png) { + error(`textures/${file}: there's no ${file.replace(/\.json$/, ".png")} for it to go with`); + continue; } + const json = read_json(`${dir}/textures/${file}`, (message) => error(`textures/${file}: ${message}`)); + const size = png_size(Deno.readFileSync(png)); + if (json === undefined || !size) continue; + const problems = validate_texture_json(json, size); + for (const problem of problems) error(`textures/${file}: ${problem}`); + if (problems.length === 0) mod.texture_json.set(texture_id, json as TextureJson); + } + // once it's known which are animated, their frames are what has to fit + for (const [texture_id, path] of mod.texture_files) { + const size = png_size(Deno.readFileSync(path)); + const problem = size && texture_size_problem(size, mod.texture_json.get(texture_id)); + if (problem) error(`${path.slice(dir.length + 1)}: ${problem}`); } return mod; diff --git a/tools/pack_mod.ts b/tools/pack_mod.ts index 2b77cf6..ca298d4 100644 --- a/tools/pack_mod.ts +++ b/tools/pack_mod.ts @@ -27,6 +27,7 @@ export async function pack_mod(mod: LoadedMod): Promise> for (const [id, path] of [...mod.texture_files].sort(([a], [b]) => a.localeCompare(b))) { textures.set(id, Deno.readFileSync(path)); } + const texture_json = new Map([...mod.texture_json].sort(([a], [b]) => a.localeCompare(b))); return write_bmod({ manifest, @@ -44,6 +45,7 @@ export async function pack_mod(mod: LoadedMod): Promise> }, scripts, textures, + texture_json, credits: manifest.credits ? Deno.readTextFileSync(`${mod.dir}/${manifest.credits}`) : undefined, }); }