Allow for textures that aren't 16x16

This commit is contained in:
2026-09-28 16:20:37 -03:00
parent 52ef4e5ca6
commit fe149bb9ad
18 changed files with 268 additions and 136 deletions
+81 -37
View File
@@ -6,71 +6,115 @@ import type { SpriteRegion } from "$/common/constants.ts";
export interface AtlasLayout {
// in pixels, a power of two
size: number;
// in sprites, by texture id. engine:missing is always at 0, 0
// by texture id
regions: Record<string, SpriteRegion>;
}
// engine:missing first, then every other texture sorted by id, row by row
export function atlas_layout(ids: Iterable<string>): AtlasLayout {
const sorted = [...new Set(ids)].filter((id) => id !== "engine:missing").sort((a, b) => a.localeCompare(b));
const count = sorted.length + 1;
const size = 2 ** Math.ceil(Math.log2(Math.ceil(Math.sqrt(count)) * TEXTURE_SIZE));
const per_row = size / TEXTURE_SIZE;
const regions: Record<string, SpriteRegion> = { "engine:missing": { x: 0, y: 0 } };
sorted.forEach((id, i) => {
regions[id] = { x: (i + 1) % per_row, y: Math.floor((i + 1) / per_row) };
});
return { size, regions };
export interface TextureSize {
width: number;
height: number;
}
// shelves, tallest first so each row wastes little, and by id when they're the same size so the same textures always
// give the same atlas. engine:missing is 16×16 and always there
export function atlas_layout(sizes: Map<string, TextureSize>): AtlasLayout {
const entries = [...sizes].filter(([id]) => id !== "engine:missing");
entries.push(["engine:missing", { width: TEXTURE_SIZE, height: TEXTURE_SIZE }]);
entries.sort(([a, sa], [b, sb]) => sb.height - sa.height || sb.width - sa.width || a.localeCompare(b));
const area = entries.reduce((sum, [, { width, height }]) => sum + width * height, 0);
const widest = Math.max(...entries.map(([, { width }]) => width));
let size = 2 ** Math.ceil(Math.log2(Math.max(Math.sqrt(area), widest)));
while (true) {
const regions = pack_shelves(entries, size);
if (regions) return { size, regions };
size *= 2;
}
}
// undefined if they don't fit in a size × size square
function pack_shelves(entries: [string, TextureSize][], size: number) {
const regions: Record<string, SpriteRegion> = {};
let x = 0;
let y = 0;
let shelf = 0;
for (const [id, { width, height }] of entries) {
if (x + width > size) {
x = 0;
y += shelf;
shelf = 0;
}
regions[id] = { x, y, width, height };
x += width;
shelf = Math.max(shelf, height);
}
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>) {
const { size, regions } = atlas_layout(textures.keys());
const images = new Map<string, ImageBitmap>();
await Promise.all([...textures].map(async ([id, png]) => {
try {
images.set(id, await createImageBitmap(new Blob([png as Uint8Array<ArrayBuffer>], { type: "image/png" })));
} catch {
console.warn(`Texture ${id} isn't a png that can be shown, it will show as missing`);
}
}));
images.get("engine:missing")?.close();
images.delete("engine:missing");
const { size, regions } = atlas_layout(new Map([...images].map(([id, image]) => [id, image])));
const canvas = new OffscreenCanvas(size, size);
const ctx = canvas.getContext("2d")!;
// magenta and black checker
const missing = regions["engine:missing"];
const half = TEXTURE_SIZE / 2;
ctx.fillStyle = "magenta";
ctx.fillRect(0, 0, 8, 8);
ctx.fillRect(8, 8, 8, 8);
ctx.fillRect(missing.x, missing.y, half, half);
ctx.fillRect(missing.x + half, missing.y + half, half, half);
ctx.fillStyle = "black";
ctx.fillRect(8, 0, 8, 8);
ctx.fillRect(0, 8, 8, 8);
ctx.fillRect(missing.x + half, missing.y, half, half);
ctx.fillRect(missing.x, missing.y + half, half, half);
await Promise.all([...textures].map(async ([id, png]) => {
const region = regions[id];
try {
const image = await createImageBitmap(new Blob([png as Uint8Array<ArrayBuffer>], { type: "image/png" }));
ctx.drawImage(image, region.x * TEXTURE_SIZE, region.y * TEXTURE_SIZE);
image.close();
} catch {
console.warn(`Texture ${id} isn't a png that can be shown, it will show as missing`);
regions[id] = regions["engine:missing"];
}
}));
for (const [id, image] of images) {
ctx.drawImage(image, regions[id].x, regions[id].y);
image.close();
}
for (const id of textures.keys()) {
regions[id] ??= missing;
}
// which pixels of each texture can be seen, for the 3d models of dropped items (see item_model.ts)
const pixels = ctx.getImageData(0, 0, size, size).data;
opaque.clear();
for (const [id, region] of Object.entries(regions)) {
const mask = new Uint8Array(TEXTURE_SIZE * TEXTURE_SIZE);
for (let py = 0; py < TEXTURE_SIZE; py++) {
for (let px = 0; px < TEXTURE_SIZE; px++) {
const i = ((region.y * TEXTURE_SIZE + py) * size + region.x * TEXTURE_SIZE + px) * 4;
mask[py * TEXTURE_SIZE + px] = pixels[i + 3] > 0 ? 1 : 0;
const mask = new Uint8Array(region.width * region.height);
for (let py = 0; py < region.height; py++) {
for (let px = 0; px < region.width; px++) {
const i = ((region.y + py) * size + region.x + px) * 4;
mask[py * region.width + px] = pixels[i + 3] > 0 ? 1 : 0;
}
}
opaque.set(id, mask);
opaque.set(id, { width: region.width, height: region.height, mask });
}
return { image: canvas.transferToImageBitmap(), regions };
}
// by texture id, TEXTURE_SIZE * TEXTURE_SIZE of 1 (can be seen) or 0, row by row from the top
const opaque = new Map<string, Uint8Array>();
// a texture's pixels, 1 (can be seen) or 0, row by row from the top
export interface OpaqueMask {
width: number;
height: number;
mask: Uint8Array;
}
// by texture id
const opaque = new Map<string, OpaqueMask>();
// which pixels of a texture aren't fully see-through, undefined before the atlas is built or for unknown textures
export function opaque_pixels(texture_id: string): Uint8Array | undefined {
export function opaque_pixels(texture_id: string): OpaqueMask | undefined {
return opaque.get(texture_id);
}