@automataframework/art 0.0.1-preview.12.sha-e1e5dd9 → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/index.js +1 -0
- package/package.json +7 -38
- package/LICENSE +0 -674
- package/dist/bin.d.ts +0 -3
- package/dist/bin.js +0 -38
- package/dist/features/clean/clean.d.ts +0 -12
- package/dist/features/clean/clean.js +0 -75
- package/dist/features/make/fal.d.ts +0 -10
- package/dist/features/make/fal.js +0 -19
- package/dist/features/make/ledger.d.ts +0 -17
- package/dist/features/make/ledger.js +0 -29
- package/dist/features/make/make.d.ts +0 -20
- package/dist/features/make/make.js +0 -97
- package/dist/features/make/models.d.ts +0 -11
- package/dist/features/make/models.js +0 -7
- package/dist/features/palette/duel.d.ts +0 -2
- package/dist/features/palette/duel.js +0 -22
- package/dist/features/palette/palette.d.ts +0 -8
- package/dist/features/palette/palette.js +0 -35
- package/dist/features/sidecar/sidecar.d.ts +0 -15
- package/dist/features/sidecar/sidecar.js +0 -35
- package/dist/index.d.ts +0 -7
- package/dist/index.js +0 -9
- package/dist/lib/png.d.ts +0 -4
- package/dist/lib/png.js +0 -49
- package/vendor/unfake/LICENSE +0 -21
- package/vendor/unfake/SOURCE.md +0 -24
- package/vendor/unfake/lib/core-client.js +0 -159
- package/vendor/unfake/lib/core-codec.js +0 -35
- package/vendor/unfake/lib/cvfree.js +0 -193
- package/vendor/unfake/lib/edge-detect.js +0 -127
- package/vendor/unfake/lib/pixel.js +0 -541
- package/vendor/unfake/lib/utils.js +0 -520
- package/vendor/unfake/vendor/unfake-core/unfake_wasm.js +0 -524
- package/vendor/unfake/vendor/unfake-core/unfake_wasm_bg.wasm +0 -0
- package/vendor/unfake/workers/unfake-core-worker.js +0 -259
|
@@ -1,541 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* pixel.js - A module for advanced pixel art optimization.
|
|
3
|
-
* Handles intelligent scale detection, color quantization, downscaling, and PNG encoding.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import {
|
|
7
|
-
fileToImageData,
|
|
8
|
-
morphologicalCleanup,
|
|
9
|
-
jaggyCleaner,
|
|
10
|
-
alphaBinarization,
|
|
11
|
-
countColors,
|
|
12
|
-
detectScale,
|
|
13
|
-
gcdArray,
|
|
14
|
-
median,
|
|
15
|
-
mode,
|
|
16
|
-
mean,
|
|
17
|
-
logger,
|
|
18
|
-
dominantOrMean,
|
|
19
|
-
finalizePixels,
|
|
20
|
-
encodePng,
|
|
21
|
-
getPaletteFromImage,
|
|
22
|
-
downscaleBlock,
|
|
23
|
-
quantizeImage,
|
|
24
|
-
detectOptimalColorCount,
|
|
25
|
-
} from './utils.js';
|
|
26
|
-
import { runCoreOp, ensureCoreWorker, CORE_DS } from './core-client.js';
|
|
27
|
-
import { findOptimalCropOffset, cropImageData } from './cvfree.js';
|
|
28
|
-
import { tiledEdgeDetect, singleRegionEdgeDetect } from './edge-detect.js';
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Upper bound for the "Max Colors" control. Selecting this value means "no
|
|
32
|
-
* color reduction" — quantization is skipped entirely. Any lower value caps the
|
|
33
|
-
* palette to that many colors. Kept here (and re-exported via index.js) so the
|
|
34
|
-
* UI slider and the pipeline guards below can never drift apart.
|
|
35
|
-
*/
|
|
36
|
-
export const MAX_COLORS = 1024;
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Detects pixel art scale by analyzing color run lengths. This method is very reliable for
|
|
40
|
-
* "clean" pixel art with uniform block sizes.
|
|
41
|
-
* @param {ImageData} imgData - The input image data.
|
|
42
|
-
* @returns {number} The detected scale factor (Greatest Common Divisor of run lengths).
|
|
43
|
-
*/
|
|
44
|
-
export function runsBasedDetect(imgData) {
|
|
45
|
-
const { data, width, height } = imgData;
|
|
46
|
-
const allRunLens = [];
|
|
47
|
-
const scanRuns = (isHorizontal) => {
|
|
48
|
-
const primaryDim = isHorizontal ? height : width;
|
|
49
|
-
const secondaryDim = isHorizontal ? width : height;
|
|
50
|
-
for (let i = 0; i < primaryDim; i++) {
|
|
51
|
-
let currentRunLength = 1;
|
|
52
|
-
for (let j = 1; j < secondaryDim; j++) {
|
|
53
|
-
const idx1 = isHorizontal ? (i * width + j) * 4 : (j * width + i) * 4;
|
|
54
|
-
const idx2 = isHorizontal ? idx1 - 4 : ((j - 1) * width + i) * 4;
|
|
55
|
-
const isSamePixel = data[idx1] === data[idx2] && data[idx1 + 1] === data[idx2 + 1] && data[idx1 + 2] === data[idx2 + 2] && data[idx1 + 3] === data[idx2 + 3];
|
|
56
|
-
if (isSamePixel) {
|
|
57
|
-
currentRunLength++;
|
|
58
|
-
} else {
|
|
59
|
-
if (currentRunLength > 1) allRunLens.push(currentRunLength);
|
|
60
|
-
currentRunLength = 1;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
if (currentRunLength > 1) allRunLens.push(currentRunLength);
|
|
64
|
-
}
|
|
65
|
-
};
|
|
66
|
-
scanRuns(true);
|
|
67
|
-
scanRuns(false);
|
|
68
|
-
if (allRunLens.length < 10) {
|
|
69
|
-
return 1;
|
|
70
|
-
}
|
|
71
|
-
const detectedScale = gcdArray(allRunLens);
|
|
72
|
-
logger.log(`Runs-based detection found scale: ${detectedScale}`);
|
|
73
|
-
return Math.max(1, detectedScale);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Edge-aware scale detection, single ROI (unfake-core WASM, JS canonical fallback).
|
|
78
|
-
* @param {ImageData} imgData The input image data.
|
|
79
|
-
* @returns {Promise<number>} The detected scale factor.
|
|
80
|
-
*/
|
|
81
|
-
export async function legacyEdgeAwareDetect(imgData) {
|
|
82
|
-
if (await ensureCoreWorker()) {
|
|
83
|
-
return runCoreOp('detectLegacy', { image: imgData });
|
|
84
|
-
}
|
|
85
|
-
return singleRegionEdgeDetect(imgData);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Detects pixel art scale via tiled edge-aware algorithm (unfake-core WASM, JS canonical fallback).
|
|
90
|
-
* @param {ImageData} imgData The input image data.
|
|
91
|
-
* @returns {Promise<number>} The detected scale factor.
|
|
92
|
-
*/
|
|
93
|
-
export async function edgeAwareDetect(imgData) {
|
|
94
|
-
if (imgData.width * imgData.height > 8_000_000) {
|
|
95
|
-
logger.warn('Image > 8MP, using runs-based detection for performance.');
|
|
96
|
-
return runsBasedDetect(imgData);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
try {
|
|
100
|
-
if (await ensureCoreWorker()) {
|
|
101
|
-
const bestScale = await runCoreOp('detectTiled', { image: imgData });
|
|
102
|
-
logger.log(`Edge-aware (unfake-core WASM) scale: ${bestScale}`);
|
|
103
|
-
return bestScale;
|
|
104
|
-
}
|
|
105
|
-
const bestScale = tiledEdgeDetect(imgData);
|
|
106
|
-
logger.log(`Edge-aware (JS canonical) scale: ${bestScale}`);
|
|
107
|
-
return bestScale;
|
|
108
|
-
} catch (error) {
|
|
109
|
-
logger.error('Edge-aware detection failed:', error);
|
|
110
|
-
return 1;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
async function coreDownscale(imgData, scale, methodId, domThreshold, alignGrid = false) {
|
|
115
|
-
return runCoreOp('downscale', {
|
|
116
|
-
image: imgData,
|
|
117
|
-
scale,
|
|
118
|
-
method: methodId,
|
|
119
|
-
domThreshold,
|
|
120
|
-
alignGrid,
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* Enhanced downscaling method using dominant color.
|
|
127
|
-
* Prevents artifact colors by working with full colors (RGB)
|
|
128
|
-
* rather than individual channels. Works with already quantized colors,
|
|
129
|
-
* which guarantees using only colors from the original palette.
|
|
130
|
-
* @param {ImageData} imgData - Source image data (already quantized).
|
|
131
|
-
* @param {number} scale - Scale factor (same for H and V).
|
|
132
|
-
* @param {number} threshold - Threshold for using dominant color (0.05 = 5%).
|
|
133
|
-
* @returns {ImageData} Downscaled image.
|
|
134
|
-
*/
|
|
135
|
-
export function downscaleByDominantColor(imgData, scale, threshold = 0.15) {
|
|
136
|
-
const targetW = Math.floor(imgData.width / scale);
|
|
137
|
-
const targetH = Math.floor(imgData.height / scale);
|
|
138
|
-
const outData = new Uint8ClampedArray(targetW * targetH * 4);
|
|
139
|
-
const srcData = imgData.data;
|
|
140
|
-
const srcWidth = imgData.width;
|
|
141
|
-
|
|
142
|
-
for (let ty = 0; ty < targetH; ty++) {
|
|
143
|
-
for (let tx = 0; tx < targetW; tx++) {
|
|
144
|
-
const colorCounts = new Map();
|
|
145
|
-
const alphaValues = [];
|
|
146
|
-
const opaqueColorsForMean = [];
|
|
147
|
-
|
|
148
|
-
// Scan scale x scale block once
|
|
149
|
-
for (let dy = 0; dy < scale; dy++) {
|
|
150
|
-
for (let dx = 0; dx < scale; dx++) {
|
|
151
|
-
const sx = tx * scale + dx;
|
|
152
|
-
const sy = ty * scale + dy;
|
|
153
|
-
if (sx >= srcWidth || sy >= imgData.height) continue;
|
|
154
|
-
const idx = (sy * srcWidth + sx) * 4;
|
|
155
|
-
|
|
156
|
-
const a = srcData[idx + 3];
|
|
157
|
-
alphaValues.push(a);
|
|
158
|
-
|
|
159
|
-
// Only consider opaque pixels for color determination
|
|
160
|
-
if (a > 128) {
|
|
161
|
-
const r = srcData[idx];
|
|
162
|
-
const g = srcData[idx + 1];
|
|
163
|
-
const b = srcData[idx + 2];
|
|
164
|
-
const colorInt = (r << 16) | (g << 8) | b;
|
|
165
|
-
colorCounts.set(colorInt, (colorCounts.get(colorInt) || 0) + 1);
|
|
166
|
-
opaqueColorsForMean.push(colorInt);
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
const outIdx = (ty * targetW + tx) * 4;
|
|
172
|
-
|
|
173
|
-
if (opaqueColorsForMean.length > 0) {
|
|
174
|
-
let dominantColor = 0;
|
|
175
|
-
let maxCount = 0;
|
|
176
|
-
|
|
177
|
-
// Find the dominant color from our counts
|
|
178
|
-
for (const [color, count] of colorCounts.entries()) {
|
|
179
|
-
if (count > maxCount) {
|
|
180
|
-
maxCount = count;
|
|
181
|
-
dominantColor = color;
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
let finalColor;
|
|
186
|
-
// Use dominant color only if its frequency is above the threshold
|
|
187
|
-
if (maxCount / opaqueColorsForMean.length >= threshold) {
|
|
188
|
-
finalColor = dominantColor;
|
|
189
|
-
} else {
|
|
190
|
-
// Otherwise, fall back to the mean color of the block
|
|
191
|
-
const rSum = opaqueColorsForMean.reduce((sum, color) => sum + ((color >> 16) & 0xFF), 0);
|
|
192
|
-
const gSum = opaqueColorsForMean.reduce((sum, color) => sum + ((color >> 8) & 0xFF), 0);
|
|
193
|
-
const bSum = opaqueColorsForMean.reduce((sum, color) => sum + (color & 0xFF), 0);
|
|
194
|
-
const avgR = Math.round(rSum / opaqueColorsForMean.length);
|
|
195
|
-
const avgG = Math.round(gSum / opaqueColorsForMean.length);
|
|
196
|
-
const avgB = Math.round(bSum / opaqueColorsForMean.length);
|
|
197
|
-
finalColor = (avgR << 16) | (avgG << 8) | avgB;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
// Write result
|
|
201
|
-
outData[outIdx] = (finalColor >> 16) & 0xFF; // R
|
|
202
|
-
outData[outIdx + 1] = (finalColor >> 8) & 0xFF; // G
|
|
203
|
-
outData[outIdx + 2] = finalColor & 0xFF; // B
|
|
204
|
-
outData[outIdx + 3] = median(alphaValues) > 128 ? 255 : 0; // Binary alpha
|
|
205
|
-
} else {
|
|
206
|
-
// If block is completely transparent, make pixel black and transparent
|
|
207
|
-
outData[outIdx] = 0;
|
|
208
|
-
outData[outIdx + 1] = 0;
|
|
209
|
-
outData[outIdx + 2] = 0;
|
|
210
|
-
outData[outIdx + 3] = 0;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
return new ImageData(outData, targetW, targetH);
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
/** Main image processing pipeline. */
|
|
220
|
-
export async function processImage({
|
|
221
|
-
file,
|
|
222
|
-
maxColors = 32,
|
|
223
|
-
autoColorCount = false,
|
|
224
|
-
manualScale = null,
|
|
225
|
-
detectMethod = 'edge', // 'edge' (default — robust on real AI art), 'auto' (runs→edge), 'runs'
|
|
226
|
-
edgeDetectMethod = 'tiled', // 'tiled' or 'legacy'
|
|
227
|
-
downscaleMethod = 'dominant', // 'dominant', 'median', 'mode', 'mean', 'nearest', 'content-adaptive'
|
|
228
|
-
domMeanThreshold = 0.15, // CHANGED: Increased from 0.05 for more robust dominant color selection.
|
|
229
|
-
cleanup = { morph: false, jaggy: false },
|
|
230
|
-
fixedPalette = null,
|
|
231
|
-
alphaThreshold = 128,
|
|
232
|
-
snapGrid = true,
|
|
233
|
-
elasticGrid = true,
|
|
234
|
-
useCvFreeSnap = true,
|
|
235
|
-
}) {
|
|
236
|
-
if (!file) throw new Error('No file provided.');
|
|
237
|
-
|
|
238
|
-
const t0 = performance.now();
|
|
239
|
-
let current = await fileToImageData(file);
|
|
240
|
-
const originalSize = [current.width, current.height];
|
|
241
|
-
|
|
242
|
-
if (current.width > 8000 || current.height > 8000 || (current.width * current.height > 10_000_000)) {
|
|
243
|
-
throw new Error(`Image too large: ${current.width}x${current.height}.`);
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
// 1. Pre-processing: Binarize alpha
|
|
247
|
-
if (alphaThreshold !== null) {
|
|
248
|
-
current = alphaBinarization(current, alphaThreshold);
|
|
249
|
-
}
|
|
250
|
-
const originalForAdaptiveScale = current;
|
|
251
|
-
|
|
252
|
-
// 2. Scale Detection
|
|
253
|
-
let scale = 1;
|
|
254
|
-
// Fractional cell grid {periodX, periodY, offsetX, offsetY, cellsX, cellsY}:
|
|
255
|
-
// newer models resample an N-cell canvas to e.g. 2048 px (10.24 px/cell),
|
|
256
|
-
// which no integer scale + snap can follow without drifting.
|
|
257
|
-
let grid = null;
|
|
258
|
-
let gridPhase = { x: 0, y: 0 };
|
|
259
|
-
let effectiveDownscaleMethod = downscaleMethod;
|
|
260
|
-
let effectiveDomThreshold = domMeanThreshold;
|
|
261
|
-
|
|
262
|
-
if (manualScale) {
|
|
263
|
-
scale = Math.max(1, Array.isArray(manualScale) ? manualScale[0] : manualScale);
|
|
264
|
-
logger.log(`Using manual scale: ${scale}`);
|
|
265
|
-
if (!Number.isInteger(scale) && await ensureCoreWorker()) {
|
|
266
|
-
grid = await runCoreOp('gridForScale', { image: current, scale });
|
|
267
|
-
}
|
|
268
|
-
} else {
|
|
269
|
-
const detectionFn = {
|
|
270
|
-
'runs': runsBasedDetect,
|
|
271
|
-
'edge': edgeDetectMethod === 'legacy' ? legacyEdgeAwareDetect : edgeAwareDetect,
|
|
272
|
-
'auto': async (img) => {
|
|
273
|
-
if (await ensureCoreWorker()) {
|
|
274
|
-
const s = await runCoreOp('detectAuto', { image: img });
|
|
275
|
-
logger.log(`Auto-detect (unfake-core WASM): ${s}`);
|
|
276
|
-
return s;
|
|
277
|
-
}
|
|
278
|
-
const runsScale = runsBasedDetect(img);
|
|
279
|
-
if (runsScale > 1) {
|
|
280
|
-
logger.log('Auto-detect: "runs" method was successful.');
|
|
281
|
-
return runsScale;
|
|
282
|
-
}
|
|
283
|
-
logger.log('Auto-detect: "runs" failed, falling back to "edge".');
|
|
284
|
-
const edgeFn = edgeDetectMethod === 'legacy' ? legacyEdgeAwareDetect : edgeAwareDetect;
|
|
285
|
-
return await edgeFn(img);
|
|
286
|
-
}
|
|
287
|
-
}[detectMethod];
|
|
288
|
-
|
|
289
|
-
const heuristicScale = await detectionFn(originalForAdaptiveScale);
|
|
290
|
-
scale = heuristicScale;
|
|
291
|
-
|
|
292
|
-
if (await ensureCoreWorker()) {
|
|
293
|
-
grid = await runCoreOp('detectGrid', { image: originalForAdaptiveScale });
|
|
294
|
-
if (grid) {
|
|
295
|
-
scale = (grid.periodX + grid.periodY) / 2;
|
|
296
|
-
logger.log(
|
|
297
|
-
`Fractional grid: ${grid.periodX.toFixed(4)} x ${grid.periodY.toFixed(4)} px/cell ` +
|
|
298
|
-
`(${grid.cellsX}x${grid.cellsY} cells; integer detector said ${heuristicScale}).`
|
|
299
|
-
);
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
if (!grid && !Number.isInteger(scale)) {
|
|
304
|
-
scale = Math.max(1, Math.round(scale));
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
// 2.4. Elastic grid: hand-drawn pixel art jitters its cells around the
|
|
308
|
-
// scale (40..49 px columns at 43), so a fixed grid drifts half a cell
|
|
309
|
-
// somewhere and doubles or drops a pixel. Where fitting the boundaries to
|
|
310
|
-
// the drawn edges captures clearly more of them, sample those cells instead.
|
|
311
|
-
let bounds = null;
|
|
312
|
-
if (elasticGrid && scale >= 8 && await ensureCoreWorker()) {
|
|
313
|
-
let base = grid;
|
|
314
|
-
if (!base) {
|
|
315
|
-
const off = await runCoreOp('cropOffset', { image: current, scale });
|
|
316
|
-
base = { periodX: scale, periodY: scale, offsetX: off.x, offsetY: off.y };
|
|
317
|
-
}
|
|
318
|
-
bounds = await runCoreOp('elasticBounds', { image: current, grid: base });
|
|
319
|
-
if (bounds) {
|
|
320
|
-
const axes = ['x', 'y'].filter((_, i) => bounds.adapted[i]).join(' and ');
|
|
321
|
-
logger.log(`Elastic grid on ${axes}: ${bounds.cellsX}x${bounds.cellsY} cells.`);
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
if (scale <= 1 && downscaleMethod !== 'content-adaptive') {
|
|
325
|
-
logger.log('Scale is 1, skipping downscale and grid snapping.');
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
// 2.5. Snap to Grid (cv-free or OpenCV Sobel crop alignment).
|
|
329
|
-
// A fractional grid carries its own phase — cells are sampled in place.
|
|
330
|
-
if (snapGrid && scale > 1 && !grid && !bounds) {
|
|
331
|
-
logger.log('Snapping to grid via auto-crop...');
|
|
332
|
-
if (await ensureCoreWorker()) {
|
|
333
|
-
const autoCrop = await runCoreOp('cropOffset', { image: current, scale });
|
|
334
|
-
const cropX = (autoCrop.x + gridPhase.x) % scale;
|
|
335
|
-
const cropY = (autoCrop.y + gridPhase.y) % scale;
|
|
336
|
-
const newWidth = Math.floor((current.width - cropX) / scale) * scale;
|
|
337
|
-
const newHeight = Math.floor((current.height - cropY) / scale) * scale;
|
|
338
|
-
if (newWidth >= scale && newHeight >= scale) {
|
|
339
|
-
current = cropImageData(current, cropX, cropY, newWidth, newHeight);
|
|
340
|
-
logger.log(`Image cropped to: ${current.width} x ${current.height} (unfake-core)`);
|
|
341
|
-
} else {
|
|
342
|
-
logger.warn('Snapping skipped: resulting image would be too small.');
|
|
343
|
-
}
|
|
344
|
-
} else {
|
|
345
|
-
const autoCrop = findOptimalCropOffset(current, scale);
|
|
346
|
-
const cropX = (autoCrop.x + gridPhase.x) % scale;
|
|
347
|
-
const cropY = (autoCrop.y + gridPhase.y) % scale;
|
|
348
|
-
const newWidth = Math.floor((current.width - cropX) / scale) * scale;
|
|
349
|
-
const newHeight = Math.floor((current.height - cropY) / scale) * scale;
|
|
350
|
-
if (newWidth >= scale && newHeight >= scale) {
|
|
351
|
-
current = cropImageData(current, cropX, cropY, newWidth, newHeight);
|
|
352
|
-
logger.log(`Image cropped to: ${current.width} x ${current.height} (cv-free fallback)`);
|
|
353
|
-
} else {
|
|
354
|
-
logger.warn('Snapping skipped: resulting image would be too small.');
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
// 3. Optional Pre-Processing Cleanup
|
|
360
|
-
if (cleanup.morph) {
|
|
361
|
-
current = await morphologicalCleanup(current);
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
// 4. Color Quantization (before downscaling)
|
|
365
|
-
const initialColors = countColors(current);
|
|
366
|
-
let colorsUsed = initialColors;
|
|
367
|
-
let quantizeAfter = false;
|
|
368
|
-
|
|
369
|
-
// Auto-detect optimal color count if enabled
|
|
370
|
-
let effectiveMaxColors = maxColors;
|
|
371
|
-
if (autoColorCount && initialColors > 2) {
|
|
372
|
-
logger.log('Auto-detecting optimal color count...');
|
|
373
|
-
try {
|
|
374
|
-
effectiveMaxColors = await detectOptimalColorCount(current, {
|
|
375
|
-
downsampleTo: 64,
|
|
376
|
-
colorQuantizeFactor: 48,
|
|
377
|
-
dominanceThreshold: 0.015,
|
|
378
|
-
maxColors: Math.min(maxColors, 32) // Cap at 32 for auto-detection
|
|
379
|
-
});
|
|
380
|
-
logger.log(`Auto-detected optimal color count: ${effectiveMaxColors}`);
|
|
381
|
-
} catch (error) {
|
|
382
|
-
logger.warn('Auto-color detection failed, using manual setting:', error);
|
|
383
|
-
effectiveMaxColors = maxColors;
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
if (effectiveDownscaleMethod === 'content-adaptive') {
|
|
388
|
-
// Не квантизуем до даунскейла
|
|
389
|
-
} else if (effectiveMaxColors < MAX_COLORS && initialColors > effectiveMaxColors) {
|
|
390
|
-
logger.log(`Quantizing from ${initialColors} to a max of ${effectiveMaxColors} colors.`);
|
|
391
|
-
const quantResult = await quantizeImage(current, effectiveMaxColors, fixedPalette);
|
|
392
|
-
current = quantResult.quantized;
|
|
393
|
-
colorsUsed = quantResult.colorsUsed;
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
// 5. Downscaling
|
|
397
|
-
if (scale > 1) {
|
|
398
|
-
logger.log(`Downscaling by ${scale}x using '${effectiveDownscaleMethod}' method.`);
|
|
399
|
-
const useCoreDs = await ensureCoreWorker();
|
|
400
|
-
if (bounds && effectiveDownscaleMethod !== 'content-adaptive') {
|
|
401
|
-
current = await runCoreOp('downscaleBounds', {
|
|
402
|
-
image: current,
|
|
403
|
-
bounds,
|
|
404
|
-
method: CORE_DS[effectiveDownscaleMethod] ?? CORE_DS.median,
|
|
405
|
-
domThreshold: effectiveDomThreshold,
|
|
406
|
-
});
|
|
407
|
-
quantizeAfter = effectiveDownscaleMethod !== 'dominant';
|
|
408
|
-
} else if (grid && effectiveDownscaleMethod !== 'content-adaptive') {
|
|
409
|
-
const coreMethod = CORE_DS[effectiveDownscaleMethod] ?? CORE_DS.median;
|
|
410
|
-
current = await runCoreOp('downscaleGrid', {
|
|
411
|
-
image: current,
|
|
412
|
-
grid,
|
|
413
|
-
method: coreMethod,
|
|
414
|
-
domThreshold: effectiveDomThreshold,
|
|
415
|
-
});
|
|
416
|
-
quantizeAfter = effectiveDownscaleMethod !== 'dominant';
|
|
417
|
-
} else if (effectiveDownscaleMethod === 'dominant') {
|
|
418
|
-
current = useCoreDs
|
|
419
|
-
? await coreDownscale(current, scale, CORE_DS.dominant, effectiveDomThreshold)
|
|
420
|
-
: downscaleByDominantColor(current, scale, effectiveDomThreshold);
|
|
421
|
-
} else if (effectiveDownscaleMethod === 'qvote') {
|
|
422
|
-
if (useCoreDs) {
|
|
423
|
-
// Rust core quantizes (imagequant) then votes — single canonical qvote.
|
|
424
|
-
current = await coreDownscale(current, scale, CORE_DS.qvote, effectiveDomThreshold);
|
|
425
|
-
} else {
|
|
426
|
-
const qColors = Math.min(effectiveMaxColors, 32);
|
|
427
|
-
const q = await quantizeImage(current, qColors, fixedPalette);
|
|
428
|
-
current = downscaleBlock(q.quantized, scale, scale, 'mode', effectiveDomThreshold);
|
|
429
|
-
colorsUsed = q.colorsUsed;
|
|
430
|
-
}
|
|
431
|
-
quantizeAfter = true;
|
|
432
|
-
} else if (effectiveDownscaleMethod === 'content-adaptive') {
|
|
433
|
-
const cells = bounds ?? grid;
|
|
434
|
-
const targetW = cells ? cells.cellsX : Math.floor(originalSize[0] / scale);
|
|
435
|
-
const targetH = cells ? cells.cellsY : Math.floor(originalSize[1] / scale);
|
|
436
|
-
current = await runCoreOp('contentAdaptive', { image: originalForAdaptiveScale, targetW, targetH });
|
|
437
|
-
quantizeAfter = true;
|
|
438
|
-
} else if (['median', 'mode', 'mean', 'nearest'].includes(effectiveDownscaleMethod)) {
|
|
439
|
-
const coreMethod = {
|
|
440
|
-
median: CORE_DS.median,
|
|
441
|
-
mode: CORE_DS.mode,
|
|
442
|
-
nearest: CORE_DS.nearest,
|
|
443
|
-
mean: CORE_DS.mean,
|
|
444
|
-
}[effectiveDownscaleMethod];
|
|
445
|
-
current = useCoreDs
|
|
446
|
-
? await coreDownscale(current, scale, coreMethod, effectiveDomThreshold)
|
|
447
|
-
: downscaleBlock(current, scale, scale, effectiveDownscaleMethod, effectiveDomThreshold);
|
|
448
|
-
quantizeAfter = true;
|
|
449
|
-
} else {
|
|
450
|
-
logger.warn(`Unknown downscale method '${effectiveDownscaleMethod}', falling back to 'median'.`);
|
|
451
|
-
current = useCoreDs
|
|
452
|
-
? await coreDownscale(current, scale, CORE_DS.median, effectiveDomThreshold)
|
|
453
|
-
: downscaleBlock(current, scale, scale, 'median', effectiveDomThreshold);
|
|
454
|
-
quantizeAfter = true;
|
|
455
|
-
}
|
|
456
|
-
current = finalizePixels(current);
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
// 6. Optional post-downscale quantization
|
|
460
|
-
if (quantizeAfter && effectiveMaxColors < MAX_COLORS) {
|
|
461
|
-
logger.log('Post-downscale quantization...');
|
|
462
|
-
const quantResult = await quantizeImage(current, effectiveMaxColors, fixedPalette);
|
|
463
|
-
current = quantResult.quantized;
|
|
464
|
-
colorsUsed = quantResult.colorsUsed;
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
// 6. Optional Post-Downscale Cleanup
|
|
468
|
-
if (cleanup.jaggy) {
|
|
469
|
-
current = jaggyCleaner(current);
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
if (!current?.width || !current?.height) {
|
|
473
|
-
throw new Error("Processing resulted in an empty image.");
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
// 7. Encode to PNG
|
|
477
|
-
const png = await encodePng(current);
|
|
478
|
-
const palette = getPaletteFromImage(current);
|
|
479
|
-
|
|
480
|
-
logger.log(`Processing complete in ${Math.round(performance.now() - t0)}ms. Final size: ${png.byteLength} bytes.`);
|
|
481
|
-
|
|
482
|
-
// Generate processing manifest
|
|
483
|
-
const manifest = {
|
|
484
|
-
original_size: originalSize,
|
|
485
|
-
final_size: [current.width, current.height],
|
|
486
|
-
processing_steps: {
|
|
487
|
-
scale_detection: {
|
|
488
|
-
method: detectMethod,
|
|
489
|
-
edge_method: manualScale ? null : detectMethod === 'edge' || detectMethod === 'auto' ? edgeDetectMethod : null,
|
|
490
|
-
detected_scale: scale,
|
|
491
|
-
manual_scale: manualScale,
|
|
492
|
-
grid: grid && {
|
|
493
|
-
period: [grid.periodX, grid.periodY],
|
|
494
|
-
offset: [grid.offsetX, grid.offsetY],
|
|
495
|
-
cells: [grid.cellsX, grid.cellsY],
|
|
496
|
-
},
|
|
497
|
-
elastic: bounds && {
|
|
498
|
-
adapted: bounds.adapted,
|
|
499
|
-
cells: [bounds.cellsX, bounds.cellsY],
|
|
500
|
-
},
|
|
501
|
-
},
|
|
502
|
-
color_quantization: {
|
|
503
|
-
max_colors: maxColors,
|
|
504
|
-
initial_colors: initialColors,
|
|
505
|
-
final_colors: colorsUsed,
|
|
506
|
-
fixed_palette: fixedPalette ? fixedPalette.length : null
|
|
507
|
-
},
|
|
508
|
-
downscaling: {
|
|
509
|
-
method: effectiveDownscaleMethod,
|
|
510
|
-
scale_factor: scale,
|
|
511
|
-
dom_mean_threshold: effectiveDomThreshold,
|
|
512
|
-
applied: scale > 1
|
|
513
|
-
},
|
|
514
|
-
cleanup: {
|
|
515
|
-
morphological: cleanup.morph,
|
|
516
|
-
jaggy: cleanup.jaggy
|
|
517
|
-
},
|
|
518
|
-
alpha_processing: {
|
|
519
|
-
threshold: alphaThreshold,
|
|
520
|
-
binarized: alphaThreshold !== null
|
|
521
|
-
},
|
|
522
|
-
grid_snapping: {
|
|
523
|
-
enabled: snapGrid,
|
|
524
|
-
applied: snapGrid && scale > 1 && !grid && !bounds,
|
|
525
|
-
cvfree: useCvFreeSnap,
|
|
526
|
-
phase: gridPhase,
|
|
527
|
-
}
|
|
528
|
-
},
|
|
529
|
-
processing_time_ms: Math.round(performance.now() - t0),
|
|
530
|
-
timestamp: new Date().toISOString()
|
|
531
|
-
};
|
|
532
|
-
|
|
533
|
-
logger.log('Final manifest:', manifest);
|
|
534
|
-
|
|
535
|
-
return {
|
|
536
|
-
png,
|
|
537
|
-
imageData: current,
|
|
538
|
-
palette,
|
|
539
|
-
manifest,
|
|
540
|
-
};
|
|
541
|
-
}
|