feat(write-sprite): compose atlas image + UV-JSON + lock output

This commit is contained in:
Axel Meyer
2026-06-16 21:17:32 +02:00
parent 33f43a1d8e
commit d5fb03b8d0
2 changed files with 104 additions and 0 deletions

58
src/write-sprite.js Normal file
View File

@@ -0,0 +1,58 @@
// src/write-sprite.js
// Compose the diffuse atlas image, build the UV-JSON, write all three
// output files into <outDir>/<atlasId>/.
const fs = require('node:fs');
const path = require('node:path');
const Jimp = require('jimp');
const { serializeSpriteLock } = require('./lock-sprite');
async function composeSpriteAtlas(boundsW, boundsH, placed) {
// Jimp 0.22: synchronous (w, h, color) constructor; color is RGBA32.
const atlas = new Jimp(boundsW, boundsH, 0x00000000);
for (const p of placed) {
// Each `p` carries the source image as `p.image` (jimp instance).
// Blit at (p.x, p.y) — the orchestrator has already pre-offset
// these coordinates by padPx, so x/y is the INNER sprite origin.
atlas.composite(p.image, p.x, p.y);
}
return atlas;
}
function buildUvJson(atlasId, boundsW, boundsH, placed) {
const sprites = {};
for (const p of placed) {
sprites[p.alias] = {
x: p.x,
y: p.y,
w: p.w,
h: p.h,
source_file: p.sourceFile,
};
}
return JSON.stringify({
atlas_id: atlasId,
atlas_size: [boundsW, boundsH],
sprites,
}, null, 2) + '\n';
}
async function writeSpriteOutputs(opts) {
const { atlasId, outDir, placed, boundsW, boundsH, lock } = opts;
const atlasDir = path.join(outDir, atlasId);
fs.mkdirSync(atlasDir, { recursive: true });
const atlas = await composeSpriteAtlas(boundsW, boundsH, placed);
await atlas.writeAsync(path.join(atlasDir, 'sprites.diffuse.atlas.png'));
fs.writeFileSync(
path.join(atlasDir, 'sprites.uv.json'),
buildUvJson(atlasId, boundsW, boundsH, placed),
);
fs.writeFileSync(
path.join(atlasDir, 'sprites.atlas.lock.json'),
serializeSpriteLock(lock),
);
}
module.exports = { composeSpriteAtlas, buildUvJson, writeSpriteOutputs };