@automataframework/art 0.0.0-stage → 0.0.1-preview.12.sha-e1e5dd9

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.
Files changed (36) hide show
  1. package/LICENSE +674 -0
  2. package/dist/bin.d.ts +3 -0
  3. package/dist/bin.js +38 -0
  4. package/dist/features/clean/clean.d.ts +12 -0
  5. package/dist/features/clean/clean.js +75 -0
  6. package/dist/features/make/fal.d.ts +10 -0
  7. package/dist/features/make/fal.js +19 -0
  8. package/dist/features/make/ledger.d.ts +17 -0
  9. package/dist/features/make/ledger.js +29 -0
  10. package/dist/features/make/make.d.ts +20 -0
  11. package/dist/features/make/make.js +97 -0
  12. package/dist/features/make/models.d.ts +11 -0
  13. package/dist/features/make/models.js +7 -0
  14. package/dist/features/palette/duel.d.ts +2 -0
  15. package/dist/features/palette/duel.js +22 -0
  16. package/dist/features/palette/palette.d.ts +8 -0
  17. package/dist/features/palette/palette.js +35 -0
  18. package/dist/features/sidecar/sidecar.d.ts +15 -0
  19. package/dist/features/sidecar/sidecar.js +35 -0
  20. package/dist/index.d.ts +7 -0
  21. package/dist/index.js +9 -0
  22. package/dist/lib/png.d.ts +4 -0
  23. package/dist/lib/png.js +49 -0
  24. package/package.json +38 -3
  25. package/vendor/unfake/LICENSE +21 -0
  26. package/vendor/unfake/SOURCE.md +24 -0
  27. package/vendor/unfake/lib/core-client.js +159 -0
  28. package/vendor/unfake/lib/core-codec.js +35 -0
  29. package/vendor/unfake/lib/cvfree.js +193 -0
  30. package/vendor/unfake/lib/edge-detect.js +127 -0
  31. package/vendor/unfake/lib/pixel.js +541 -0
  32. package/vendor/unfake/lib/utils.js +520 -0
  33. package/vendor/unfake/vendor/unfake-core/unfake_wasm.js +524 -0
  34. package/vendor/unfake/vendor/unfake-core/unfake_wasm_bg.wasm +0 -0
  35. package/vendor/unfake/workers/unfake-core-worker.js +259 -0
  36. package/README.md +0 -3
@@ -0,0 +1,520 @@
1
+ /**
2
+ * @fileoverview Shared utilities for pixel art and vector processing.
3
+ * This file contains common functions used across the library for tasks like
4
+ * image manipulation, color quantization, and mathematical calculations.
5
+ */
6
+
7
+ import { runCoreOp } from './core-client.js';
8
+
9
+ let progressHandler = null;
10
+
11
+ /**
12
+ * Register a UI callback for pipeline progress messages.
13
+ * @param {((entry: { level: string, text: string }) => void)|null} handler
14
+ */
15
+ export function setProgressHandler(handler) {
16
+ progressHandler = handler;
17
+ }
18
+
19
+ function formatLogArgs(args) {
20
+ return args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ');
21
+ }
22
+
23
+ function emitProgress(level, args) {
24
+ if (!progressHandler) return;
25
+ try {
26
+ progressHandler({ level, text: formatLogArgs(args) });
27
+ } catch {
28
+ /* UI hook must not break pipeline */
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Logger utility with debug control.
34
+ * Controlled by `window.DEBUG_UNFAKE` flag.
35
+ */
36
+ export const logger = {
37
+ _isEnabled: () => typeof window !== 'undefined' ? window.DEBUG_UNFAKE !== false : true,
38
+ log: (...args) => {
39
+ emitProgress('log', args);
40
+ if (logger._isEnabled()) console.log('[unfake.js]', ...args);
41
+ },
42
+ warn: (...args) => {
43
+ emitProgress('warn', args);
44
+ if (logger._isEnabled()) console.warn('[unfake.js]', ...args);
45
+ },
46
+ error: (...args) => {
47
+ emitProgress('error', args);
48
+ console.error('[unfake.js]', ...args);
49
+ },
50
+ };
51
+
52
+
53
+ // --- Image Loading and Conversion --------------------------------------------
54
+
55
+ /**
56
+ * Reads a user-supplied File/Blob into an ImageData object.
57
+ * @param {File|Blob} file The file to read.
58
+ * @returns {Promise<ImageData>} A promise that resolves with the image data.
59
+ */
60
+ export async function fileToImageData(file) {
61
+ logger.log(`Starting conversion of file: ${file.name}, size: ${file.size}`);
62
+
63
+ if (file.size > 50 * 1024 * 1024) { // 50MB limit
64
+ throw new Error(`File too large: ${(file.size / 1024 / 1024).toFixed(1)}MB. Max 50MB.`);
65
+ }
66
+
67
+ const bitmap = await Promise.race([
68
+ createImageBitmap(file),
69
+ new Promise((_, reject) => setTimeout(() => reject(new Error('Image loading timeout')), 30000))
70
+ ]);
71
+ logger.log(`ImageBitmap created: ${bitmap.width}x${bitmap.height}`);
72
+
73
+ const canvas = typeof OffscreenCanvas !== 'undefined'
74
+ ? new OffscreenCanvas(bitmap.width, bitmap.height)
75
+ : document.createElement('canvas');
76
+
77
+ if (!(canvas instanceof OffscreenCanvas)) {
78
+ canvas.width = bitmap.width;
79
+ canvas.height = bitmap.height;
80
+ }
81
+
82
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
83
+ ctx.drawImage(bitmap, 0, 0);
84
+ return ctx.getImageData(0, 0, canvas.width, canvas.height);
85
+ }
86
+
87
+ /**
88
+ * Encodes ImageData to a PNG buffer via unfake-core (png crate), canvas fallback.
89
+ * @param {ImageData} imgData The image data to encode.
90
+ * @returns {Promise<Uint8Array>} A Uint8Array containing the PNG file data.
91
+ */
92
+ export async function encodePng(imgData) {
93
+ try {
94
+ return await runCoreOp('encodePng', { image: imgData });
95
+ } catch (e) {
96
+ logger.warn('core PNG encode failed, canvas fallback:', e);
97
+ const canvas = document.createElement('canvas');
98
+ canvas.width = imgData.width;
99
+ canvas.height = imgData.height;
100
+ canvas.getContext('2d').putImageData(imgData, 0, 0);
101
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'));
102
+ if (!blob) throw new Error('Canvas fallback for PNG encoding failed.');
103
+ return new Uint8Array(await blob.arrayBuffer());
104
+ }
105
+ }
106
+
107
+ // --- Image Processing and Cleanup --------------------------------------------
108
+
109
+ /**
110
+ * Applies morphological cleanup to an image.
111
+ * Uses OPEN to remove noise and CLOSE to fill small gaps.
112
+ * @param {ImageData} imgData The input image data.
113
+ * @returns {Promise<ImageData>} The cleaned image data.
114
+ */
115
+ export async function morphologicalCleanup(imgData) {
116
+ return runCoreOp('morphCleanup', { image: imgData });
117
+ }
118
+
119
+ /**
120
+ * Converts the alpha channel to binary (0 or 255) based on a threshold.
121
+ * @param {ImageData} imgData The input image data.
122
+ * @param {number} [threshold=128] Alpha threshold (0-255).
123
+ * @returns {ImageData} The processed image data.
124
+ */
125
+ export function alphaBinarization(imgData, threshold = 128) {
126
+ const { data, width, height } = imgData;
127
+ const out = new Uint8ClampedArray(data);
128
+
129
+ for (let i = 3; i < out.length; i += 4) {
130
+ out[i] = out[i] >= threshold ? 255 : 0;
131
+ }
132
+
133
+ return new ImageData(out, width, height);
134
+ }
135
+
136
+ /**
137
+ * Removes isolated diagonal pixels ("jaggies") from pixel art.
138
+ * @param {ImageData} imgData The input image data.
139
+ * @returns {ImageData} The processed image data.
140
+ */
141
+ export function jaggyCleaner(imgData) {
142
+ const { data, width, height } = imgData;
143
+ const out = new Uint8ClampedArray(data);
144
+
145
+ const get = (x, y) => {
146
+ if (x < 0 || x >= width || y < 0 || y >= height) return null;
147
+ const i = (y * width + x) * 4;
148
+ return { r: out[i], g: out[i + 1], b: out[i + 2], a: out[i + 3] };
149
+ };
150
+
151
+ const set = (x, y, color) => {
152
+ if (x < 0 || x >= width || y < 0 || y >= height) return;
153
+ const i = (y * width + x) * 4;
154
+ Object.assign(out, [color.r, color.g, color.b, color.a], i);
155
+ };
156
+
157
+ const isOpaque = (p) => p?.a > 128;
158
+
159
+ // Apply rule-based cleaning for orphaned diagonal pixels
160
+ for (let y = 1; y < height - 1; y++) {
161
+ for (let x = 1; x < width - 1; x++) {
162
+ if (!isOpaque(get(x, y))) continue;
163
+
164
+ const N = isOpaque(get(x, y - 1)), S = isOpaque(get(x, y + 1));
165
+ const E = isOpaque(get(x + 1, y)), W = isOpaque(get(x - 1, y));
166
+ const NE = isOpaque(get(x + 1, y - 1)), NW = isOpaque(get(x - 1, y - 1));
167
+ const SE = isOpaque(get(x + 1, y + 1)), SW = isOpaque(get(x - 1, y + 1));
168
+
169
+ const opaqueOrth = N + S + E + W;
170
+ const opaqueDiag = NE + NW + SE + SW;
171
+
172
+ // Remove pixel if it has no orthogonal neighbors and only one diagonal one
173
+ if (opaqueOrth === 0 && opaqueDiag === 1) {
174
+ set(x, y, { r: 0, g: 0, b: 0, a: 0 });
175
+ }
176
+ }
177
+ }
178
+
179
+ return new ImageData(out, width, height);
180
+ }
181
+
182
+ /**
183
+ * Ensures final pixels have binary alpha and transparent pixels are black.
184
+ * @param {ImageData} imgData The image to clean.
185
+ * @returns {ImageData} The cleaned image.
186
+ */
187
+ export function finalizePixels(imgData) {
188
+ const data = imgData.data;
189
+ for (let i = 0; i < data.length; i += 4) {
190
+ if (data[i + 3] < 128) {
191
+ data[i] = data[i + 1] = data[i + 2] = data[i + 3] = 0;
192
+ } else {
193
+ data[i + 3] = 255;
194
+ }
195
+ }
196
+ return imgData;
197
+ }
198
+
199
+ // --- Color and Palette -------------------------------------------------------
200
+
201
+ /**
202
+ * Automatically detects the optimal number of colors in an image.
203
+ * Uses aggressive clustering and dominant color analysis.
204
+ * @param {ImageData} imgData The input image data.
205
+ * @param {object} [options] Options for detection.
206
+ * @returns {Promise<number>} The estimated optimal number of colors.
207
+ */
208
+ export async function detectOptimalColorCount(imgData, {
209
+ downsampleTo = 64,
210
+ colorQuantizeFactor = 48,
211
+ dominanceThreshold = 0.015,
212
+ maxColors = 32
213
+ } = {}) {
214
+ logger.log('Detecting optimal color count...');
215
+ const result = await runCoreOp('detectColorCount', {
216
+ image: imgData,
217
+ downsampleTo,
218
+ quantize: colorQuantizeFactor,
219
+ dominance: dominanceThreshold,
220
+ maxColors,
221
+ });
222
+ logger.log(`Final auto-detected color count: ${result}`);
223
+ return result;
224
+ }
225
+
226
+
227
+ /**
228
+ * Quantize colors via unfake-core (imagequant for auto palettes, nearest-remap
229
+ * for a fixed palette). Runs in the WASM worker.
230
+ * @param {ImageData} imgData The input image data.
231
+ * @param {number} maxColors The maximum number of colors.
232
+ * @param {{r,g,b,a}[]|null} [fixedPalette=null] Optional fixed palette.
233
+ * @returns {Promise<{quantized: ImageData, colorsUsed: number, palette: object[]}>}
234
+ */
235
+ export async function quantizeImage(imgData, maxColors, fixedPalette = null) {
236
+ const r = await runCoreOp('quantize', { image: imgData, maxColors, fixedPalette });
237
+ return {
238
+ quantized: finalizePixels(r.quantized),
239
+ colorsUsed: r.colorsUsed,
240
+ palette: r.palette,
241
+ };
242
+ }
243
+
244
+ /**
245
+ * Counts the number of unique opaque colors in an ImageData object.
246
+ * @param {ImageData} imgData The image data.
247
+ * @returns {number} The count of unique colors.
248
+ */
249
+ export function countColors(imgData) {
250
+ const seen = new Set();
251
+ const d = imgData.data;
252
+ for (let i = 0; i < d.length; i += 4) {
253
+ if (d[i + 3] > 128) { // Count only opaque colors
254
+ seen.add((d[i] << 16) | (d[i + 1] << 8) | d[i + 2]);
255
+ }
256
+ if (seen.size > 256) break; // Optimization for many-colored images
257
+ }
258
+ return seen.size;
259
+ }
260
+
261
+ /**
262
+ * Extracts the unique colors from an ImageData object into an array of objects.
263
+ * @param {ImageData} imgData The image data.
264
+ * @returns {Array<{r: number, g: number, b: number, a: number}>} An array of color objects.
265
+ */
266
+ export function getPaletteAsObjects(imgData) {
267
+ const seen = new Set();
268
+ const palette = [];
269
+ const d = imgData.data;
270
+ for (let i = 0; i < d.length; i += 4) {
271
+ const r = d[i], g = d[i + 1], b = d[i + 2], a = d[i + 3];
272
+ if (a > 128) { // Count only opaque colors
273
+ const key = `${r}|${g}|${b}|${a}`;
274
+ if (!seen.has(key)) {
275
+ seen.add(key);
276
+ palette.push({ r, g, b, a });
277
+ }
278
+ }
279
+ }
280
+ return palette;
281
+ }
282
+
283
+ /**
284
+ * Extracts the unique colors from an ImageData object into a hex palette.
285
+ * @param {ImageData} imgData The image data.
286
+ * @returns {string[]} An array of hex color strings (e.g., "#rrggbbaa").
287
+ */
288
+ export function getPaletteFromImage(imgData) {
289
+ const seen = new Set();
290
+ const d = imgData.data;
291
+ for (let i = 0; i < d.length; i += 4) {
292
+ seen.add((d[i] << 24) | (d[i + 1] << 16) | (d[i + 2] << 8) | d[i + 3]);
293
+ }
294
+ const toHex = val => val.toString(16).padStart(2, '0');
295
+ return Array.from(seen).map(key => {
296
+ const r = (key >>> 24);
297
+ const g = (key >>> 16) & 0xFF;
298
+ const b = (key >>> 8) & 0xFF;
299
+ const a = key & 0xFF;
300
+ return `#${toHex(r)}${toHex(g)}${toHex(b)}${toHex(a)}`;
301
+ });
302
+ }
303
+
304
+ // --- Scaling and Resampling --------------------------------------------------
305
+
306
+ /**
307
+ * Detects pixel grid scale from a signal using peak analysis.
308
+ * @param {number[]} signal An array of numbers representing e.g., gradient profile.
309
+ * @returns {number} The detected scale factor (at least 1).
310
+ */
311
+ export function detectScale(signal) {
312
+ if (signal.length < 3) return 1;
313
+
314
+ const meanVal = signal.reduce((a, b) => a + b, 0) / signal.length;
315
+ const std = Math.sqrt(signal.reduce((a, b) => a + (b - meanVal) ** 2, 0) / signal.length);
316
+ const threshold = meanVal + 1.5 * std;
317
+
318
+ const peaks = [];
319
+ for (let i = 1; i < signal.length - 1; i++) {
320
+ if (signal[i] > threshold && signal[i] > signal[i - 1] && signal[i] > signal[i + 1]) {
321
+ // Ensure peaks are spaced out
322
+ if (peaks.length === 0 || i - peaks[peaks.length - 1] > 2) {
323
+ peaks.push(i);
324
+ }
325
+ }
326
+ }
327
+
328
+ if (peaks.length <= 2) {
329
+ logger.log('detectScale: Not enough peaks found, returning 1.');
330
+ return 1;
331
+ }
332
+
333
+ const spacings = peaks.slice(1).map((p, i) => p - peaks[i]);
334
+ logger.log(`detectScale: Found ${peaks.length} peaks, spacings: [${spacings}]`);
335
+
336
+ // Heuristic: if most spacings are close to the median, use the median.
337
+ const medianSpacing = median(spacings);
338
+ const closeSpacings = spacings.filter(s => Math.abs(s - medianSpacing) <= 2);
339
+
340
+ if (closeSpacings.length / spacings.length > 0.7) {
341
+ logger.log(`detectScale: Using median spacing: ${medianSpacing}`);
342
+ return Math.round(medianSpacing);
343
+ }
344
+
345
+ // Otherwise, return the mode as a fallback.
346
+ const modeSpacing = mode(spacings);
347
+ logger.log(`detectScale: Using fallback mode spacing: ${modeSpacing}`);
348
+ return modeSpacing > 1 ? modeSpacing : 1;
349
+ }
350
+
351
+ /**
352
+ * Downscales an image by sampling pixels within blocks.
353
+ * @param {ImageData} imgData The source image data.
354
+ * @param {number} hScale Horizontal scale factor.
355
+ * @param {number} vScale Vertical scale factor.
356
+ * @param {string} [method='median'] Sampling method: 'median', 'mode', 'mean', 'domMean', 'nearest'.
357
+ * @param {number} [domMeanThreshold=0.05] Threshold for 'domMean' method.
358
+ * @returns {ImageData} The downscaled image data.
359
+ */
360
+ export function downscaleBlock(imgData, hScale, vScale, method = 'median', domMeanThreshold = 0.05) {
361
+ const targetW = Math.floor(imgData.width / hScale);
362
+ const targetH = Math.floor(imgData.height / vScale);
363
+ if (targetW <= 0 || targetH <= 0) return new ImageData(1, 1);
364
+
365
+ const out = new Uint8ClampedArray(targetW * targetH * 4);
366
+ const d = imgData.data;
367
+
368
+ for (let ty = 0; ty < targetH; ty++) {
369
+ for (let tx = 0; tx < targetW; tx++) {
370
+ const offset = (ty * targetW + tx) * 4;
371
+
372
+ if (method === 'nearest') {
373
+ const sx = tx * hScale + Math.floor(hScale / 2);
374
+ const sy = ty * vScale + Math.floor(vScale / 2);
375
+ if (sx < imgData.width && sy < imgData.height) {
376
+ const idx = (sy * imgData.width + sx) * 4;
377
+ out[offset] = d[idx];
378
+ out[offset + 1] = d[idx + 1];
379
+ out[offset + 2] = d[idx + 2];
380
+ out[offset + 3] = d[idx + 3];
381
+ }
382
+ continue;
383
+ }
384
+
385
+ const colorsR = [], colorsG = [], colorsB = [], colorsA = [];
386
+
387
+ for (let dy = 0; dy < vScale; dy++) {
388
+ for (let dx = 0; dx < hScale; dx++) {
389
+ const sx = tx * hScale + dx, sy = ty * vScale + dy;
390
+ if (sx >= imgData.width || sy >= imgData.height) continue;
391
+
392
+ const idx = (sy * imgData.width + sx) * 4;
393
+ if (d[idx + 3] > 128) { // Only consider mostly opaque pixels for color
394
+ colorsR.push(d[idx]);
395
+ colorsG.push(d[idx + 1]);
396
+ colorsB.push(d[idx + 2]);
397
+ }
398
+ colorsA.push(d[idx + 3]); // Always consider alpha for aggregation
399
+ }
400
+ }
401
+
402
+ if (colorsA.length === 0) continue;
403
+
404
+ const hasColor = colorsR.length > 0;
405
+
406
+ let aggregator;
407
+ switch (method) {
408
+ // case 'nearest' is handled above
409
+ case 'mode': aggregator = mode; break;
410
+ case 'mean': aggregator = mean; break;
411
+ case 'median': aggregator = median; break;
412
+ case 'domMean': aggregator = colors => dominantOrMean(colors, domMeanThreshold); break;
413
+ default:
414
+ logger.warn(`Unknown downscale method "${method}", falling back to "median".`);
415
+ aggregator = median;
416
+ }
417
+
418
+ out[offset] = hasColor ? aggregator(colorsR) : 0;
419
+ out[offset + 1] = hasColor ? aggregator(colorsG) : 0;
420
+ out[offset + 2] = hasColor ? aggregator(colorsB) : 0;
421
+ // Median is robust for alpha to preserve hard edges
422
+ out[offset + 3] = median(colorsA);
423
+ }
424
+ }
425
+ return new ImageData(out, targetW, targetH);
426
+ }
427
+
428
+ // --- Math Helpers ------------------------------------------------------------
429
+
430
+ export const median = (arr) => {
431
+ if (arr.length === 0) return 0;
432
+ const mid = Math.floor(arr.length / 2);
433
+ const sorted = [...arr].sort((a, b) => a - b);
434
+ return arr.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
435
+ };
436
+
437
+ export const mode = (arr) => {
438
+ if (arr.length === 0) return 0;
439
+ const counts = {};
440
+ let max = 0, res = arr[0];
441
+ for (const v of arr) {
442
+ counts[v] = (counts[v] || 0) + 1;
443
+ if (counts[v] > max) {
444
+ max = counts[v];
445
+ res = v;
446
+ }
447
+ }
448
+ return res;
449
+ };
450
+
451
+ export const mean = (arr) => {
452
+ if (arr.length === 0) return 0;
453
+ return Math.round(arr.reduce((a, b) => a + b, 0) / arr.length);
454
+ };
455
+
456
+ /**
457
+ * Uses dominant color if frequent enough, otherwise falls back to the mean.
458
+ * @param {number[]} arr Array of color values.
459
+ * @param {number} [threshold=0.05] Frequency threshold for dominant color (0-1).
460
+ * @returns {number} The aggregated color value.
461
+ */
462
+ export function dominantOrMean(arr, threshold = 0.05) {
463
+ if (arr.length === 0) return 0;
464
+ const freq = {};
465
+ arr.forEach(v => freq[v] = (freq[v] || 0) + 1);
466
+
467
+ const [dominant, count] = Object.entries(freq).reduce(
468
+ (best, cur) => (cur[1] > best[1] ? cur : best),
469
+ [null, 0]
470
+ );
471
+
472
+ if (dominant !== null && count / arr.length >= threshold) {
473
+ return +dominant;
474
+ }
475
+ return mean(arr);
476
+ }
477
+
478
+ /**
479
+ * Calculates the Greatest Common Divisor (GCD) of an array of numbers.
480
+ * @param {number[]} arr The array of numbers.
481
+ * @returns {number} The GCD of the array.
482
+ */
483
+ export function gcdArray(arr) {
484
+ if (!arr.length) return 1;
485
+ let result = arr[0];
486
+ for (let i = 1; i < arr.length; i++) {
487
+ result = gcd(result, arr[i]);
488
+ if (result === 1) return 1; // Early exit
489
+ }
490
+ return result;
491
+ }
492
+
493
+ /**
494
+ * Calculates the GCD of two numbers using the Euclidean algorithm.
495
+ */
496
+ function gcd(a, b) {
497
+ a = Math.abs(a);
498
+ b = Math.abs(b);
499
+ while (b) {
500
+ [a, b] = [b, a % b];
501
+ }
502
+ return a;
503
+ }
504
+
505
+ /**
506
+ * Multiplies two 2x2 matrices (a * b).
507
+ * @param {number[][]} a First matrix.
508
+ * @param {number[][]} b Second matrix.
509
+ * @returns {number[][]} The resulting matrix.
510
+ */
511
+ export function multiply2x2(a, b) {
512
+ const [a00, a01] = a[0];
513
+ const [a10, a11] = a[1];
514
+ const [b00, b01] = b[0];
515
+ const [b10, b11] = b[1];
516
+ return [
517
+ [a00 * b00 + a01 * b10, a00 * b01 + a01 * b11],
518
+ [a10 * b00 + a11 * b10, a10 * b01 + a11 * b11]
519
+ ];
520
+ }