-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormalize-strip.mjs
More file actions
165 lines (139 loc) · 5.29 KB
/
Copy pathnormalize-strip.mjs
File metadata and controls
165 lines (139 loc) · 5.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/usr/bin/env node
import sharp from 'sharp';
import { parseArgs } from 'node:util';
import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
const { values } = parseArgs({
options: {
input: { type: 'string' },
outdir: { type: 'string' },
frames: { type: 'string', default: '4' },
framesize: { type: 'string', default: '128' },
anchor: { type: 'string' },
lockframe1: { type: 'boolean', default: false },
name: { type: 'string', default: 'frame' },
},
});
if (!values.input || !values.outdir) {
console.error(
'Usage: node scripts/normalize-strip.mjs \\\n' +
' --input sprites/raw/walk-strip.png \\\n' +
' --outdir sprites/final \\\n' +
' [--frames 4] [--framesize 128] \\\n' +
' [--anchor sprites/final/companion-front.png] \\\n' +
' [--lockframe1] [--name walk]'
);
process.exit(1);
}
const numFrames = Number(values.frames);
const frameSize = Number(values.framesize);
mkdirSync(values.outdir, { recursive: true });
// Load the full strip
const stripMeta = await sharp(values.input).metadata();
const slotW = Math.floor(stripMeta.width / numFrames);
const slotH = stripMeta.height;
console.log(`Strip: ${stripMeta.width}x${stripMeta.height}, ${numFrames} slots of ${slotW}x${slotH}`);
// Find the bounding box of non-transparent (and non-magenta) pixels
async function findBounds(buffer, w, h) {
const { data } = await sharp(buffer)
.raw()
.toBuffer({ resolveWithObject: true });
let minX = w, minY = h, maxX = 0, maxY = 0;
let found = false;
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const i = (y * w + x) * 4;
const r = data[i], g = data[i + 1], b = data[i + 2], a = data[i + 3];
// Skip transparent pixels
if (a < 10) continue;
// Skip magenta background pixels
if (r > 230 && g < 30 && b > 230) continue;
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
found = true;
}
}
if (!found) return null;
return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
}
// Extract each slot from the strip
const slotBuffers = [];
for (let i = 0; i < numFrames; i++) {
const buf = await sharp(values.input)
.extract({ left: i * slotW, top: 0, width: slotW, height: slotH })
.ensureAlpha()
.png()
.toBuffer();
slotBuffers.push(buf);
}
// Find bounds for each frame
const allBounds = [];
for (let i = 0; i < numFrames; i++) {
const bounds = await findBounds(slotBuffers[i], slotW, slotH);
if (bounds) {
allBounds.push({ index: i, ...bounds });
console.log(`Frame ${i + 1}: character at ${bounds.x},${bounds.y} size ${bounds.w}x${bounds.h}`);
} else {
allBounds.push({ index: i, x: 0, y: 0, w: slotW, h: slotH });
console.log(`Frame ${i + 1}: no character found, using full slot`);
}
}
// Find the tallest and widest character across all frames
const maxCharW = Math.max(...allBounds.map(b => b.w));
const maxCharH = Math.max(...allBounds.map(b => b.h));
// Calculate uniform scale to fit in frameSize with padding
const padding = Math.floor(frameSize * 0.05);
const availableSize = frameSize - padding * 2;
const scale = Math.min(availableSize / maxCharW, availableSize / maxCharH);
console.log(`\nMax character size: ${maxCharW}x${maxCharH}`);
console.log(`Scale factor: ${scale.toFixed(3)} → fits in ${frameSize}x${frameSize}`);
// Process each frame
for (let i = 0; i < numFrames; i++) {
const b = allBounds[i];
// Crop to character bounds
let frame = sharp(slotBuffers[i])
.extract({ left: b.x, top: b.y, width: b.w, height: b.h });
// Scale uniformly
const scaledW = Math.round(b.w * scale);
const scaledH = Math.round(b.h * scale);
frame = frame.resize(scaledW, scaledH, {
kernel: sharp.kernel.nearest,
});
// Place on final canvas, anchored at bottom-center
const offsetX = Math.floor((frameSize - scaledW) / 2);
const offsetY = frameSize - scaledH - padding; // bottom-aligned
const finalFrame = await sharp({
create: {
width: frameSize,
height: frameSize,
channels: 4,
background: { r: 0, g: 0, b: 0, alpha: 0 },
},
})
.composite([{
input: await frame.png().toBuffer(),
left: offsetX,
top: offsetY,
}])
.png()
.toBuffer();
const outPath = join(values.outdir, `${values.name}-${String(i + 1).padStart(2, '0')}.png`);
await sharp(finalFrame).toFile(outPath);
console.log(`Saved: ${outPath} (${scaledW}x${scaledH} placed at ${offsetX},${offsetY})`);
}
// Lock frame 1 to the original anchor/seed if requested
if (values.lockframe1 && values.anchor) {
const frame1Path = join(values.outdir, `${values.name}-01.png`);
await sharp(values.anchor)
.resize(frameSize, frameSize, {
fit: 'contain',
background: { r: 0, g: 0, b: 0, alpha: 0 },
kernel: sharp.kernel.nearest,
})
.png()
.toFile(frame1Path);
console.log(`\nFrame 01 locked to anchor: ${values.anchor}`);
}
console.log(`\nDone. ${numFrames} normalized frames in ${values.outdir}`);