pixelkiln 0.142.2 → 0.144.0

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/dist/cli.js CHANGED
@@ -3046,6 +3046,16 @@ var StyleObjectSchema = z.object({
3046
3046
  * chocolate bar.
3047
3047
  */
3048
3048
  palette: z.array(HexColorSchema).default([]),
3049
+ /**
3050
+ * The palette as a file instead of inline colours, relative to the
3051
+ * manifest: a Lospec `.hex`, a GIMP `.gpl`, or a Paint.NET `.txt`.
3052
+ * `loadManifest` reads it into `palette` before validation, so a file
3053
+ * palette hashes the same as the same colours written inline, and editing
3054
+ * the file makes the style's assets stale. Not with `palette` on the same
3055
+ * style; a child style's own `palette` or `paletteFile` replaces its
3056
+ * parent's.
3057
+ */
3058
+ paletteFile: z.string().min(1).optional(),
3049
3059
  /** `target_palette.name` ("Game Boy", "PICO-8"), which PixelLab uses to help the look. Needs `palette`; generators in `TARGET_PALETTE_GENERATORS` only. */
3050
3060
  paletteName: z.string().min(1).max(100).optional(),
3051
3061
  /** `target_palette.max_colors`: at most this many colours in each image, 2 to 64 (drawn from `palette` when one is set). Generators in `TARGET_PALETTE_GENERATORS` only. */
@@ -3541,6 +3551,7 @@ var ParallaxTintSchema = z.object({
3541
3551
  /** 0 leaves the picture as it is; 1 makes every pixel the colour, snapped. */
3542
3552
  amount: z.number().min(0).max(1)
3543
3553
  }).strict();
3554
+ var PARALLAX_LOOPS = ["cut", "crossfade", "mirror"];
3544
3555
  var ParallaxLayerSchema = z.object({
3545
3556
  /** Names the layer in exports; defaults to the asset id, the file name, or "sky". */
3546
3557
  name: z.string().regex(/^[A-Za-z][A-Za-z0-9_-]*$/, "letters, digits, - and _, starting with a letter").optional(),
@@ -3593,7 +3604,14 @@ var ParallaxLayerSchema = z.object({
3593
3604
  */
3594
3605
  foot: z.number().gt(0).max(1).optional(),
3595
3606
  /** Pull the picture (each sprite of a run) toward a colour and snap it to the set's palette. Applied after `foot`. */
3596
- tint: ParallaxTintSchema.optional()
3607
+ tint: ParallaxTintSchema.optional(),
3608
+ /**
3609
+ * Make a picture that repeats sideways join smoothly, before `foot` and
3610
+ * `tint`: `cut` crops it to the two columns that best continue into each
3611
+ * other, `crossfade` blends its last eighth into its first and snaps the
3612
+ * blend to the picture's colours, `mirror` adds a flipped copy beside it.
3613
+ */
3614
+ loop: z.enum(PARALLAX_LOOPS).optional()
3597
3615
  }).strict().superRefine((layer, ctx) => {
3598
3616
  const sources = [layer.asset, layer.file, layer.sky, layer.run].filter((value) => value !== void 0).length;
3599
3617
  if (sources !== 1) {
@@ -3612,6 +3630,10 @@ var ParallaxLayerSchema = z.object({
3612
3630
  if (layer[key3] !== void 0) ctx.addIssue({ code: z.ZodIssueCode.custom, path: [key3], message: `${key3} does not apply to a sky layer` });
3613
3631
  }
3614
3632
  }
3633
+ if (layer.loop !== void 0) {
3634
+ const why = layer.sky !== void 0 ? "a sky layer is drawn to the view's width" : layer.run !== void 0 ? "a run is laid as a loop already" : layer.repeat === false ? "the layer does not repeat" : void 0;
3635
+ if (why) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["loop"], message: `loop does not apply: ${why}` });
3636
+ }
3615
3637
  if (layer.foot !== void 0 && layer.extend !== void 0) {
3616
3638
  ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["extend"], message: "extend repeats the bottom row, which foot thins out; use one or the other" });
3617
3639
  }
@@ -4448,6 +4470,38 @@ function quantize(png, palette) {
4448
4470
  function quantizeToPalette(png, palette) {
4449
4471
  return quantize(png, palette).png;
4450
4472
  }
4473
+ function parsePaletteFile(text, fileName) {
4474
+ const ext = fileName.toLowerCase().split(".").pop();
4475
+ const lines = text.replace(/^/, "").split(/\r?\n/);
4476
+ const colors = [];
4477
+ const fail = (line, why) => {
4478
+ throw new Error(`${fileName}:${line}: ${why}`);
4479
+ };
4480
+ if (ext === "gpl") {
4481
+ if (!/^GIMP Palette\s*$/.test(lines[0]?.trim() ?? "")) fail(1, 'a .gpl palette starts with "GIMP Palette"');
4482
+ lines.slice(1).forEach((raw, index) => {
4483
+ const line = raw.trim();
4484
+ if (!line || line.startsWith("#") || /^(Name|Columns):/i.test(line)) return;
4485
+ const match = /^(\d{1,3})\s+(\d{1,3})\s+(\d{1,3})(\s|$)/.exec(line);
4486
+ if (!match) return fail(index + 2, `expected "R G B", got "${line}"`);
4487
+ const channels = match.slice(1, 4).map(Number);
4488
+ if (channels.some((value) => value > 255)) fail(index + 2, `channel above 255 in "${line}"`);
4489
+ colors.push(`#${channels.map((value) => value.toString(16).padStart(2, "0")).join("")}`);
4490
+ });
4491
+ } else if (ext === "hex" || ext === "txt") {
4492
+ lines.forEach((raw, index) => {
4493
+ const line = raw.trim();
4494
+ if (!line || ext === "txt" && line.startsWith(";")) return;
4495
+ const match = ext === "hex" ? /^#?([0-9a-f]{6})$/i.exec(line) : /^[0-9a-f]{2}([0-9a-f]{6})$/i.exec(line);
4496
+ if (!match) fail(index + 1, `expected ${ext === "hex" ? "rrggbb" : "aarrggbb"}, got "${line}"`);
4497
+ colors.push(`#${match[1].toLowerCase()}`);
4498
+ });
4499
+ } else {
4500
+ throw new Error(`${fileName}: palette files are .hex, .gpl, or .txt (Paint.NET)`);
4501
+ }
4502
+ if (!colors.length) throw new Error(`${fileName}: no colours found`);
4503
+ return colors;
4504
+ }
4451
4505
 
4452
4506
  // src/paperdoll.ts
4453
4507
  var at = (image, x, y) => (y * image.width + x) * 4;
@@ -16471,8 +16525,20 @@ async function loadManifest(manifestPath, opts = {}) {
16471
16525
  throw new ProjectError(`Manifest at ${abs} is invalid:
16472
16526
  ${expansion.issues.map((i) => ` ${i}`).join("\n")}`);
16473
16527
  }
16474
- if (!opts.lenient) return loadExpanded(abs, expansion);
16528
+ const paletteIssues = await readPaletteFiles(expansion.raw, path19.dirname(abs));
16529
+ if (!opts.lenient) {
16530
+ if (paletteIssues.length) {
16531
+ throw new ProjectError(
16532
+ `Manifest at ${abs} is invalid:
16533
+ ${paletteIssues.flatMap((entry) => entry.issues).map((i) => ` ${i}`).join("\n")}`
16534
+ );
16535
+ }
16536
+ return loadExpanded(abs, expansion);
16537
+ }
16475
16538
  const invalid = [];
16539
+ for (const entry of paletteIssues) {
16540
+ if (dropEntry(expansion.raw, entry)) invalid.push(entry);
16541
+ }
16476
16542
  const raw = pruneInvalidEntries(expansion.raw, invalid);
16477
16543
  for (let round2 = 0; ; round2++) {
16478
16544
  try {
@@ -16486,6 +16552,37 @@ ${expansion.issues.map((i) => ` ${i}`).join("\n")}`);
16486
16552
  }
16487
16553
  }
16488
16554
  }
16555
+ async function readPaletteFiles(raw, manifestDir) {
16556
+ const styles = entryRecord(raw, "style");
16557
+ if (!styles) return [];
16558
+ const issues = [];
16559
+ for (const [id, value] of Object.entries(styles)) {
16560
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
16561
+ const style = value;
16562
+ const file = style.paletteFile;
16563
+ if (file === void 0) continue;
16564
+ const fail = (why) => issues.push({ kind: "style", id, issues: [`styles.${id}.paletteFile: ${why}`] });
16565
+ if (typeof file !== "string" || !file) {
16566
+ fail("expected a path to a .hex, .gpl, or .txt palette");
16567
+ continue;
16568
+ }
16569
+ if (style.palette !== void 0) {
16570
+ fail("set palette or paletteFile, not both");
16571
+ continue;
16572
+ }
16573
+ const abs = path19.resolve(manifestDir, file);
16574
+ if (!existsSync14(abs)) {
16575
+ fail(`no file at ${file}`);
16576
+ continue;
16577
+ }
16578
+ try {
16579
+ style.palette = parsePaletteFile(await readFile10(abs, "utf8"), file);
16580
+ } catch (error) {
16581
+ fail(error instanceof Error ? error.message : String(error));
16582
+ }
16583
+ }
16584
+ return issues;
16585
+ }
16489
16586
  function entryRecord(raw, kind) {
16490
16587
  const record = raw?.[kind === "style" ? "styles" : "assets"];
16491
16588
  return record && typeof record === "object" && !Array.isArray(record) ? record : null;
@@ -35759,19 +35856,26 @@ async function resolveParallaxSet(manifest, manifestDir, lock, setId) {
35759
35856
  const finish = (picture, keepWidth) => finishPicture(picture, { foot: layer.foot, tint: layer.tint, palette, keepWidth }, `parallax ${setId}: ${name}`);
35760
35857
  let png;
35761
35858
  let source;
35859
+ let loop;
35762
35860
  if (layer.sky) {
35763
35861
  png = skyBands(viewW, viewH + Math.ceil(climb * speedY), layer.sky);
35764
35862
  source = { kind: "sky", colors: layer.sky };
35765
35863
  } else if (layer.run) {
35766
35864
  const sprites = await Promise.all(layer.run.map((sprite) => readPicture(manifest, manifestDir, lock, setId, name, sprite, warnings)));
35767
35865
  const seed = layer.seed ?? seedFromName(name);
35768
- const loop = layer.repeat ?? true;
35769
- const width = layer.width ?? Math.max(1, viewW + Math.ceil(travel * layer.speed) - (loop ? 0 : layer.x ?? 0));
35770
- png = layRun(sprites.map((sprite) => finish(sprite.png, false)), width, { seed, step: layer.step, gap: layer.gap, jitter: layer.jitter, loop });
35866
+ const loop2 = layer.repeat ?? true;
35867
+ const width = layer.width ?? Math.max(1, viewW + Math.ceil(travel * layer.speed) - (loop2 ? 0 : layer.x ?? 0));
35868
+ png = layRun(sprites.map((sprite) => finish(sprite.png, false)), width, { seed, step: layer.step, gap: layer.gap, jitter: layer.jitter, loop: loop2 });
35771
35869
  source = { kind: "run", seed, sprites: sprites.map((sprite) => sprite.source) };
35772
35870
  } else {
35773
35871
  const picture = await readPicture(manifest, manifestDir, lock, setId, name, layer, warnings);
35774
- png = finish(picture.png, repeat);
35872
+ png = picture.png;
35873
+ if (layer.loop) {
35874
+ const looped = loopPicture(png, layer.loop, `parallax ${setId}: ${name}`);
35875
+ png = looped.png;
35876
+ loop = looped.loop;
35877
+ }
35878
+ png = finish(png, repeat);
35775
35879
  source = picture.source;
35776
35880
  }
35777
35881
  let bottom = (layer.bottom ?? viewH) + (layer.run ? layer.jitter ?? 0 : 0);
@@ -35792,11 +35896,12 @@ async function resolveParallaxSet(manifest, manifestDir, lock, setId) {
35792
35896
  source
35793
35897
  };
35794
35898
  if (layer.foot !== void 0 || layer.tint) image.finish = { foot: layer.foot, tint: layer.tint };
35899
+ if (loop) image.loop = loop;
35795
35900
  if (repeat && source.kind !== "sky" && source.kind !== "run") {
35796
35901
  image.seamRatio = seamRatio(png);
35797
35902
  if (travel * layer.speed > 0 && image.seamRatio > SEAM_WARN_RATIO) {
35798
35903
  warnings.push(
35799
- `${name}: its sideways join is ${image.seamRatio.toFixed(1)} times rougher than the picture's own steps; loop it first (research/scripts/parallax.py loop) or set repeat: false`
35904
+ `${name}: its sideways join is ${image.seamRatio.toFixed(1)} times rougher than the picture's own steps; ` + (layer.loop ? `the ${layer.loop} loop did not smooth it; try another, or set repeat: false` : 'set "loop": "cut" to smooth it, or set repeat: false')
35800
35905
  );
35801
35906
  }
35802
35907
  }
@@ -35919,6 +36024,88 @@ function roundHalfEven(value) {
35919
36024
  if (rest < 0.5) return floor;
35920
36025
  return floor % 2 === 0 ? floor : floor + 1;
35921
36026
  }
36027
+ function loopPicture(png, method, where = "picture") {
36028
+ const { width: w, height: h } = png;
36029
+ if (w < 8) throw new Error(`${where}: ${w} px wide is too narrow to loop; loop needs at least 8 columns`);
36030
+ const columns = (left, right) => {
36031
+ const out = Buffer.alloc((right - left) * h * 4);
36032
+ for (let y = 0; y < h; y++) png.pixels.copy(out, y * (right - left) * 4, (y * w + left) * 4, (y * w + right) * 4);
36033
+ return { width: right - left, height: h, pixels: out };
36034
+ };
36035
+ if (method === "cut") {
36036
+ const pre = new Int32Array(w * h * 4);
36037
+ for (let x = 0; x < w; x++) {
36038
+ for (let y = 0; y < h; y++) {
36039
+ const p = (y * w + x) * 4;
36040
+ const q = (x * h + y) * 4;
36041
+ const alpha = png.pixels[p + 3];
36042
+ for (let c = 0; c < 3; c++) pre[q + c] = Math.floor(png.pixels[p + c] * alpha / 255);
36043
+ pre[q + 3] = alpha;
36044
+ }
36045
+ }
36046
+ const span = h * 4;
36047
+ const diff = (a, b) => {
36048
+ let sum = 0;
36049
+ for (let k = 0; k < span; k++) sum += Math.abs(pre[a * span + k] - pre[b * span + k]);
36050
+ return sum;
36051
+ };
36052
+ let best = Infinity;
36053
+ let cut = [0, w];
36054
+ const apart = Math.floor(w * 0.6);
36055
+ for (let i = 0; i < w; i++) {
36056
+ for (let j = i + apart; j <= w; j++) {
36057
+ const d = diff(j - 1, i);
36058
+ if (d < best) {
36059
+ best = d;
36060
+ cut = [i, j];
36061
+ }
36062
+ }
36063
+ }
36064
+ return { png: columns(cut[0], cut[1]), loop: { method, from: w, columns: cut } };
36065
+ }
36066
+ if (method === "crossfade") {
36067
+ const k = Math.floor(w / 8);
36068
+ const out = columns(0, w - k);
36069
+ const seen = /* @__PURE__ */ new Map();
36070
+ for (let p = 0; p < png.pixels.length; p += 4) {
36071
+ seen.set(png.pixels[p] << 16 | png.pixels[p + 1] << 8 | png.pixels[p + 2], [png.pixels[p], png.pixels[p + 1], png.pixels[p + 2]]);
36072
+ }
36073
+ const colours = [...seen.values()].sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
36074
+ const nearest = /* @__PURE__ */ new Map();
36075
+ for (let x = 0; x < k; x++) {
36076
+ const t = (x + 0.5) / k;
36077
+ for (let y = 0; y < h; y++) {
36078
+ const head = (y * w + x) * 4;
36079
+ const tail = (y * w + w - k + x) * 4;
36080
+ const mixed = [0, 1, 2].map((c) => roundHalfEven(png.pixels[tail + c] * (1 - t) + png.pixels[head + c] * t));
36081
+ const key3 = mixed[0] << 16 | mixed[1] << 8 | mixed[2];
36082
+ let snapped = nearest.get(key3);
36083
+ if (!snapped) {
36084
+ let bestDistance = Infinity;
36085
+ for (const colour of colours) {
36086
+ const d = (mixed[0] - colour[0]) ** 2 + (mixed[1] - colour[1]) ** 2 + (mixed[2] - colour[2]) ** 2;
36087
+ if (d < bestDistance) {
36088
+ bestDistance = d;
36089
+ snapped = colour;
36090
+ }
36091
+ }
36092
+ nearest.set(key3, snapped);
36093
+ }
36094
+ const o = (y * out.width + x) * 4;
36095
+ out.pixels[o] = snapped[0];
36096
+ out.pixels[o + 1] = snapped[1];
36097
+ out.pixels[o + 2] = snapped[2];
36098
+ }
36099
+ }
36100
+ return { png: out, loop: { method, from: w } };
36101
+ }
36102
+ const pixels = Buffer.alloc(w * 2 * h * 4);
36103
+ for (let y = 0; y < h; y++) {
36104
+ png.pixels.copy(pixels, y * w * 2 * 4, y * w * 4, (y + 1) * w * 4);
36105
+ for (let x = 0; x < w; x++) png.pixels.copy(pixels, (y * w * 2 + w + x) * 4, (y * w + w - 1 - x) * 4, (y * w + w - x) * 4);
36106
+ }
36107
+ return { png: { width: w * 2, height: h, pixels }, loop: { method, from: w } };
36108
+ }
35922
36109
  async function readPicture(manifest, manifestDir, lock, setId, name, ref, warnings) {
35923
36110
  if (ref.file) {
35924
36111
  const file2 = path73.resolve(manifestDir, ref.file);
@@ -36545,6 +36732,7 @@ function setOptions(set) {
36545
36732
  repeatY: layer.repeatY,
36546
36733
  ...layer.source.kind === "sky" ? { sky: layer.source.colors } : {},
36547
36734
  ...layer.source.kind === "run" ? { run: { seed: layer.source.seed, sprites: layer.source.sprites.length, width: layer.png.width } } : {},
36735
+ ...layer.loop ? { loop: layer.loop } : {},
36548
36736
  ...layer.finish ?? {}
36549
36737
  })),
36550
36738
  ...set.palette ? { palette: set.palette } : {}