Animated textures !
This commit is contained in:
+36
-5
@@ -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<string, Uint8Array>) {
|
||||
// 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<string, Uint8Array>, texture_json = new Map<string, TextureJson>()) {
|
||||
const images = new Map<string, ImageBitmap>();
|
||||
await Promise.all([...textures].map(async ([id, png]) => {
|
||||
try {
|
||||
@@ -64,7 +68,18 @@ export async function build_atlas(textures: Map<string, Uint8Array>) {
|
||||
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<string, Animation>();
|
||||
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<string, Uint8Array>) {
|
||||
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<string, Uint8Array>) {
|
||||
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
|
||||
|
||||
@@ -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
|
||||
|
||||
+9
-2
@@ -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<string, TextureJson>();
|
||||
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"}`);
|
||||
|
||||
@@ -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<ArrayBuffer>;
|
||||
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<ArrayBuffer>;
|
||||
|
||||
// pixels is the whole png, rgba row by row, image_width pixels wide
|
||||
constructor(
|
||||
readonly region: SpriteRegion,
|
||||
readonly animation: Animation,
|
||||
readonly pixels: Uint8ClampedArray<ArrayBuffer>,
|
||||
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],
|
||||
);
|
||||
}
|
||||
}
|
||||
+54
-11
@@ -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<Record<ScriptSide, string>>;
|
||||
// png bytes by texture id, like copper_tools:copper_block
|
||||
textures: Map<string, Uint8Array>;
|
||||
// the .json of the textures that have one, like animated ones, by texture id
|
||||
texture_json?: Map<string, TextureJson>;
|
||||
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/<side>.js
|
||||
// textures/<name>.png the texture <mod id>:<name>
|
||||
// textures/<name>.json its animation, if it has one
|
||||
// credits.md
|
||||
export function write_bmod(bmod: Bmod): Uint8Array<ArrayBuffer> {
|
||||
const text = (value: string) => new TextEncoder().encode(value);
|
||||
@@ -85,6 +89,9 @@ export function write_bmod(bmod: Bmod): Uint8Array<ArrayBuffer> {
|
||||
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<ModData> | undefined;
|
||||
const manifest = parse("manifest.json") as ManifestJson | undefined;
|
||||
const raw_data = parse("data.json") as Partial<ModData> | 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<string, Uint8Array>();
|
||||
// sizes are checked once it's known which textures are animated
|
||||
const pngs = new Map<string, Uint8Array>();
|
||||
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<string, TextureJson>();
|
||||
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<string, Uint8Array>();
|
||||
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}`;
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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<string, string>;
|
||||
// textures/<name>.json by texture id, for the textures that have one (see texture_animation.ts)
|
||||
texture_json: Map<string, TextureJson>;
|
||||
}
|
||||
|
||||
// dependencies before the mods that need them, otherwise alphabetical
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
// animated textures, like minecraft's .png.mcmeta and in the same format: textures/<name>.json next to
|
||||
// textures/<name>.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<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -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/<name>.png
|
||||
textures/<name>.json # for animated textures
|
||||
credits.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
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 262 B |
@@ -0,0 +1,23 @@
|
||||
{
|
||||
|
||||
"animation": {
|
||||
|
||||
"frametime": 1,
|
||||
|
||||
"frames": [
|
||||
0,
|
||||
1, 2, 3, 4,
|
||||
5,
|
||||
6, 7,
|
||||
8,
|
||||
9, 10,
|
||||
11,
|
||||
12,
|
||||
13,
|
||||
14, 15
|
||||
]
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.1 KiB |
@@ -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]
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.7 KiB |
@@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
// animated textures: textures/<name>.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]);
|
||||
});
|
||||
+22
-4
@@ -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;
|
||||
|
||||
@@ -27,6 +27,7 @@ export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>>
|
||||
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<Uint8Array<ArrayBuffer>>
|
||||
},
|
||||
scripts,
|
||||
textures,
|
||||
texture_json,
|
||||
credits: manifest.credits ? Deno.readTextFileSync(`${mod.dir}/${manifest.credits}`) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user