pixelkiln 0.144.1 → 0.145.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
@@ -2327,7 +2327,7 @@ var CharacterAnimationSchema = z.object({
2327
2327
  });
2328
2328
  }
2329
2329
  const sentence = animation.mode === "skeleton-v3" && !animation.template;
2330
- if (animation.frames !== void 0 && !sentence) {
2330
+ if (animation.frames !== void 0 && !sentence && animation.mode !== "pro") {
2331
2331
  if (animation.frames % 2 !== 0) {
2332
2332
  context.addIssue({ code: z.ZodIssueCode.custom, message: "frames must be even", path: ["frames"] });
2333
2333
  } else if (animation.frames < 4) {
@@ -3638,6 +3638,13 @@ var ParallaxLayerSchema = z.object({
3638
3638
  ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["extend"], message: "extend repeats the bottom row, which foot thins out; use one or the other" });
3639
3639
  }
3640
3640
  });
3641
+ var ParallaxTimeSchema = z.object({
3642
+ /** A style id, for that style's palette, or a list of colours. */
3643
+ palette: z.union([z.string().min(1), z.array(HexColorSchema).min(2).max(256)]),
3644
+ /** Map only onto colours whose blue is at least their red, which leaves out a night palette's lamps and moon. */
3645
+ cool: z.boolean().optional()
3646
+ }).strict();
3647
+ var ParallaxTimeIdSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,31}$/, "a time is letters, digits, - and _, starting with a letter");
3641
3648
  var ParallaxSetSchema = z.object({
3642
3649
  /** The game's view in pixels, [width, height]. */
3643
3650
  view: z.tuple([z.number().int().min(8).max(4096), z.number().int().min(8).max(4096)]),
@@ -3651,8 +3658,21 @@ var ParallaxSetSchema = z.object({
3651
3658
  * the picture, so it adds none.
3652
3659
  */
3653
3660
  palette: z.union([z.string().min(1), z.array(HexColorSchema).min(2).max(256)]).optional(),
3661
+ /**
3662
+ * Other times of day for the same set, by name: each swaps the set's
3663
+ * `palette` for another by luminance rank. Godot exports carry them in
3664
+ * one shader; Tiled and LDtk get a map per time.
3665
+ */
3666
+ times: z.record(ParallaxTimeIdSchema, ParallaxTimeSchema).optional(),
3654
3667
  layers: z.array(ParallaxLayerSchema).min(1).max(32)
3655
- }).strict();
3668
+ }).strict().superRefine((set, ctx) => {
3669
+ if (set.times && Object.keys(set.times).length && set.palette === void 0) {
3670
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["times"], message: "times swap the set's palette, so the set needs a palette" });
3671
+ }
3672
+ if (set.times && Object.keys(set.times).length > 15) {
3673
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["times"], message: "at most 15 times" });
3674
+ }
3675
+ });
3656
3676
  var ParallaxSetIdSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/, "a set id is letters, digits, - and _, starting with a letter or digit");
3657
3677
  var ManifestSchema = z.object({
3658
3678
  $schema: z.string().optional(),
@@ -9371,6 +9391,13 @@ function targetPaletteBody(palette) {
9371
9391
  }
9372
9392
  var NORMAL_MAP_MODES = ["lite", "pro"];
9373
9393
  var NORMAL_MAP_KINDS = ["character", "object", "topdown", "side", "iso", "ui"];
9394
+ function deleteSucceeded(body, what) {
9395
+ if (body && typeof body === "object" && body.success === false) {
9396
+ const reason = body.error;
9397
+ throw new PixelLabError(`${what} \u2192 200 but success: false${typeof reason === "string" && reason ? ` (${reason})` : ""}`, 200, JSON.stringify(body));
9398
+ }
9399
+ return body;
9400
+ }
9374
9401
  var PixelLabClient = class {
9375
9402
  constructor(apiKey, timeoutMs = 12e4) {
9376
9403
  this.apiKey = apiKey;
@@ -9920,9 +9947,14 @@ var PixelLabClient = class {
9920
9947
  });
9921
9948
  return validateResponse(SelectFramesSchema, raw, "select frames");
9922
9949
  }
9923
- /** Irreversible. Only reached via `purge`, behind an explicit confirmation. */
9924
- deleteObject(objectId) {
9925
- return this.request(`/objects/${objectId}`, { method: "DELETE" });
9950
+ /**
9951
+ * Irreversible. Only reached via `purge`, behind an explicit confirmation.
9952
+ * PixelLab can answer 200 with `success: false` (an object a dismissed
9953
+ * review already removed came back `"error": "Object not found"`), so the
9954
+ * body is checked, not only the status.
9955
+ */
9956
+ async deleteObject(objectId) {
9957
+ return deleteSucceeded(await this.request(`/objects/${objectId}`, { method: "DELETE" }), `DELETE /objects/${objectId}`);
9926
9958
  }
9927
9959
  dismissReview(objectId) {
9928
9960
  return this.request(`/objects/${objectId}/dismiss-review`, { method: "POST" });
@@ -10887,9 +10919,19 @@ var PixelLabClient = class {
10887
10919
  if (bytes.length > MAX_DOWNLOAD_BYTES) throw new Error(`export ${pathname} exceeds the ${MAX_DOWNLOAD_BYTES}-byte safety limit`);
10888
10920
  return bytes;
10889
10921
  }
10890
- /** `GET /generate-font-pro/{job_id}`: status, then no-auth atlas and `.ttf` URLs once completed. */
10922
+ /**
10923
+ * `GET /generate-font-pro/{job_id}`: status, then no-auth atlas and `.ttf`
10924
+ * URLs once completed. PixelLab answers 423 ("Job is still processing")
10925
+ * while the font draws, so that reads as `status: "processing"`.
10926
+ */
10891
10927
  async getFontJob(jobId) {
10892
- const raw = await this.request(`/generate-font-pro/${encodeURIComponent(jobId)}`);
10928
+ let raw;
10929
+ try {
10930
+ raw = await this.request(`/generate-font-pro/${encodeURIComponent(jobId)}`);
10931
+ } catch (error) {
10932
+ if (error instanceof PixelLabError && error.status === 423) return { job_id: jobId, status: "processing" };
10933
+ throw error;
10934
+ }
10893
10935
  return validateResponse(FontJobSchema, raw, "generate-font-pro/{job_id}");
10894
10936
  }
10895
10937
  /**
@@ -11056,9 +11098,10 @@ var PixelLabClient = class {
11056
11098
  );
11057
11099
  return validateResponse(DeleteAnimationsSchema, raw, "characters/{id}/animations");
11058
11100
  }
11059
- /** Irreversible: the character, its states are separate records, and its animations. */
11060
- deleteCharacter(characterId) {
11061
- return this.request(`/characters/${encodeURIComponent(characterId)}`, { method: "DELETE" });
11101
+ /** Irreversible: the character, its states are separate records, and its animations. Checks `success` like `deleteObject`. */
11102
+ async deleteCharacter(characterId) {
11103
+ const path79 = `/characters/${encodeURIComponent(characterId)}`;
11104
+ return deleteSucceeded(await this.request(path79, { method: "DELETE" }), `DELETE ${path79}`);
11062
11105
  }
11063
11106
  setCharacterTags(characterId, tags) {
11064
11107
  return this.request(`/characters/${encodeURIComponent(characterId)}/tags`, {
@@ -11775,7 +11818,7 @@ async function generateFont(client2, opts) {
11775
11818
  }
11776
11819
  const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
11777
11820
  const interval = opts.intervalMs ?? 5e3;
11778
- const timeout = opts.timeoutMs ?? 10 * 6e4;
11821
+ const timeout = opts.timeoutMs ?? 15 * 6e4;
11779
11822
  const submitted = await client2.generateFontPro({
11780
11823
  description: opts.description,
11781
11824
  weight: opts.weight,
@@ -12219,9 +12262,9 @@ function characterCost(spec) {
12219
12262
  if (animation.mode === "template") return 1;
12220
12263
  if (animation.mode === "skeleton-v3") return 4;
12221
12264
  if (animation.mode === "v3") return Math.max(1, Math.ceil(px * animation.frames / 65536));
12222
- return generationCost(spec.width, spec.height, "1dir");
12265
+ return proCharacterTierCost(spec.width, spec.height);
12223
12266
  }
12224
- if (character.kind === "state" || character.kind === "portrait") return generationCost(spec.width, spec.height, "1dir");
12267
+ if (character.kind === "state" || character.kind === "portrait") return proCharacterTierCost(spec.width, spec.height);
12225
12268
  if (character.kind === "outfit") {
12226
12269
  return PRO_TIER_PRICES[0];
12227
12270
  }
@@ -12238,7 +12281,13 @@ function characterCost(spec) {
12238
12281
  const south = character.reference?.south;
12239
12282
  return south ? proFlashCharacterCost(south.width, south.height, true) : proFlashCharacterCost(spec.width, spec.height, false);
12240
12283
  }
12241
- return generationCost(spec.width, spec.height, "1dir");
12284
+ return proCharacterTierCost(spec.width, spec.height);
12285
+ }
12286
+ function proCharacterTierCost(width, height) {
12287
+ const side = Math.max(width, height);
12288
+ if (side <= 85) return PRO_TIER_PRICES[0];
12289
+ if (side <= 113) return PRO_TIER_PRICES[1];
12290
+ return PRO_TIER_PRICES[2];
12242
12291
  }
12243
12292
  function proFlashCharacterCost(width, height, fromReference) {
12244
12293
  const side = Math.max(32, Math.ceil(Math.max(width, height) / 4) * 4);
@@ -16750,6 +16799,12 @@ ${issues}`);
16750
16799
  if (!style) unknownReferences.push(`parallax.${setId}.palette: unknown style "${set.palette}"`);
16751
16800
  else if (style.palette.length < 2) unknownReferences.push(`parallax.${setId}.palette: style "${set.palette}" has no palette`);
16752
16801
  }
16802
+ for (const [time, spec] of Object.entries(set.times ?? {})) {
16803
+ if (typeof spec.palette !== "string") continue;
16804
+ const style = parsed.data.styles[spec.palette];
16805
+ if (!style) unknownReferences.push(`parallax.${setId}.times.${time}.palette: unknown style "${spec.palette}"`);
16806
+ else if (style.palette.length < 2) unknownReferences.push(`parallax.${setId}.times.${time}.palette: style "${spec.palette}" has no palette`);
16807
+ }
16753
16808
  set.layers.forEach((layer, index) => {
16754
16809
  const at2 = `parallax.${setId}.layers.${index}`;
16755
16810
  const checkAsset = (where, ref) => {
@@ -17466,6 +17521,21 @@ async function resolveSpecs(loaded, filter) {
17466
17521
  // A state and its animations keep the base's own rotation count.
17467
17522
  directions: resolved.objectPro.kind === "base" ? resolved.objectPro.directions : parentSpec.objectPro.directions
17468
17523
  };
17524
+ const animation = resolved.objectPro.animation;
17525
+ if (animation?.mode === "pro") {
17526
+ const canvas = Math.max(parentSpec.width, parentSpec.height);
17527
+ const allowed = objectProAnimationFrames(canvas);
17528
+ if (!allowed) {
17529
+ throw new Error(`assets.${assetId}: a pro object animation needs a canvas of 170px or less; ${characterParent} is ${canvas}px, so use mode "v3"`);
17530
+ }
17531
+ if (asset.animation?.frames === void 0) {
17532
+ resolved.objectPro = { ...resolved.objectPro, animation: { ...animation, frames: allowed[0] } };
17533
+ } else if (!allowed.includes(asset.animation.frames)) {
17534
+ throw new Error(
17535
+ `assets.${assetId}: a pro object animation on a ${canvas}px canvas takes ${allowed.join(", ")} frames, got ${asset.animation.frames}; leave frames out to use ${allowed[0]}`
17536
+ );
17537
+ }
17538
+ }
17469
17539
  }
17470
17540
  if (asset.outfit) {
17471
17541
  if (asset.outfit.of === assetId) throw new Error(`assets.${assetId}: an asset cannot re-clothe itself`);
@@ -18073,6 +18143,12 @@ async function resolveCharacterShape(asset, style, kind, files) {
18073
18143
  }
18074
18144
  return shape;
18075
18145
  }
18146
+ function objectProAnimationFrames(canvas) {
18147
+ if (canvas <= 64) return [16];
18148
+ if (canvas <= 128) return [4, 9, 16];
18149
+ if (canvas <= 170) return [9];
18150
+ return null;
18151
+ }
18076
18152
  async function resolveObjectProShape(assetId, asset, style, kind, files) {
18077
18153
  const directions = style.objectDirections ?? 8;
18078
18154
  const shape = {
@@ -35925,7 +36001,14 @@ async function resolveParallaxSet(manifest, manifestDir, lock, setId) {
35925
36001
  }
35926
36002
  layers.push(image);
35927
36003
  }
35928
- return { id: setId, view: [viewW, viewH], travel, climb, ...palette ? { palette } : {}, layers, warnings };
36004
+ const times = Object.entries(set.times ?? {}).map(([name, time]) => {
36005
+ const colours = typeof time.palette === "string" ? manifest.styles[time.palette]?.palette : time.palette;
36006
+ if (!colours?.length) throw new Error(`parallax ${setId}: time ${name}: style "${time.palette}" has no palette`);
36007
+ const resolved = { name, palette: colours, cool: time.cool ?? false };
36008
+ paletteSwap(palette, resolved, `parallax ${setId}: time ${name}`);
36009
+ return resolved;
36010
+ });
36011
+ return { id: setId, view: [viewW, viewH], travel, climb, ...palette ? { palette } : {}, ...times.length ? { times } : {}, layers, warnings };
35929
36012
  }
35930
36013
  function finishPicture(png, options, where = "picture") {
35931
36014
  let out = png;
@@ -36106,6 +36189,83 @@ function loopPicture(png, method, where = "picture") {
36106
36189
  }
36107
36190
  return { png: { width: w * 2, height: h, pixels }, loop: { method, from: w } };
36108
36191
  }
36192
+ var rgbKey = (r, g, b) => r << 16 | g << 8 | b;
36193
+ function sortedRgb(hexes) {
36194
+ const seen = /* @__PURE__ */ new Map();
36195
+ for (const hex2 of hexes) {
36196
+ const { r, g, b } = parseHex(hex2);
36197
+ seen.set(rgbKey(r, g, b), [r, g, b]);
36198
+ }
36199
+ return [...seen.values()].sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
36200
+ }
36201
+ var luminance = (c) => c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722;
36202
+ function paletteSwap(from, time, where = "palette swap") {
36203
+ const source = sortedRgb(from);
36204
+ let target = sortedRgb(time.palette);
36205
+ if (time.cool) target = target.filter((c) => c[2] >= c[0]);
36206
+ if (!target.length) throw new Error(`${where}: no colour of the palette has blue at least its red, so cool leaves nothing to map onto`);
36207
+ const rank = (colours) => colours.map((c, i) => [i, luminance(c)]).sort((a, b) => a[1] - b[1] || a[0] - b[0]).map(([i]) => i);
36208
+ const fromOrder = rank(source);
36209
+ const toOrder = rank(target);
36210
+ const table = /* @__PURE__ */ new Map();
36211
+ fromOrder.forEach((i, r) => {
36212
+ const c = source[i];
36213
+ table.set(rgbKey(c[0], c[1], c[2]), target[toOrder[roundHalfEven(r / Math.max(fromOrder.length - 1, 1) * (toOrder.length - 1))]]);
36214
+ });
36215
+ return { source, table };
36216
+ }
36217
+ function nearestRgb(colours, r, g, b) {
36218
+ let best = colours[0];
36219
+ let bestDistance = Infinity;
36220
+ for (const c of colours) {
36221
+ const d = (r - c[0]) ** 2 + (g - c[1]) ** 2 + (b - c[2]) ** 2;
36222
+ if (d < bestDistance) {
36223
+ bestDistance = d;
36224
+ best = c;
36225
+ }
36226
+ }
36227
+ return best;
36228
+ }
36229
+ function recolourPicture(png, swap) {
36230
+ const pixels = Buffer.from(png.pixels);
36231
+ const done = /* @__PURE__ */ new Map();
36232
+ for (let p = 0; p < pixels.length; p += 4) {
36233
+ if (pixels[p + 3] === 0) continue;
36234
+ const key3 = rgbKey(pixels[p], pixels[p + 1], pixels[p + 2]);
36235
+ let out = done.get(key3);
36236
+ if (!out) {
36237
+ const snapped = nearestRgb(swap.source, pixels[p], pixels[p + 1], pixels[p + 2]);
36238
+ out = swap.table.get(rgbKey(snapped[0], snapped[1], snapped[2]));
36239
+ done.set(key3, out);
36240
+ }
36241
+ pixels[p] = out[0];
36242
+ pixels[p + 1] = out[1];
36243
+ pixels[p + 2] = out[2];
36244
+ }
36245
+ return { width: png.width, height: png.height, pixels };
36246
+ }
36247
+ function setAtTime(set, time) {
36248
+ const spec = set.times?.find((t) => t.name === time);
36249
+ if (!spec) throw new Error(`parallax ${set.id}: no time "${time}". ${set.times?.length ? `Known: ${set.times.map((t) => t.name).join(", ")}` : "The set has no times."}`);
36250
+ const swap = paletteSwap(set.palette, spec);
36251
+ return { ...set, id: `${set.id}.${time}`, times: void 0, layers: set.layers.map((layer) => ({ ...layer, png: recolourPicture(layer.png, swap) })) };
36252
+ }
36253
+ function timeColours(set) {
36254
+ const used = /* @__PURE__ */ new Map();
36255
+ for (const layer of set.layers) {
36256
+ const px = layer.png.pixels;
36257
+ for (let p = 0; p < px.length; p += 4) if (px[p + 3] !== 0) used.set(rgbKey(px[p], px[p + 1], px[p + 2]), [px[p], px[p + 1], px[p + 2]]);
36258
+ }
36259
+ const columns = [...used.values()].sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
36260
+ const rows = [columns, ...(set.times ?? []).map((time) => {
36261
+ const swap = paletteSwap(set.palette, time);
36262
+ return columns.map((c) => swap.table.get(rgbKey(...nearestRgb(swap.source, c[0], c[1], c[2]))));
36263
+ })];
36264
+ const width = Math.max(1, columns.length);
36265
+ const pixels = Buffer.alloc(width * rows.length * 4);
36266
+ rows.forEach((row, y) => row.forEach((c, x) => pixels.set([c[0], c[1], c[2], 255], (y * width + x) * 4)));
36267
+ return { width, height: rows.length, pixels };
36268
+ }
36109
36269
  async function readPicture(manifest, manifestDir, lock, setId, name, ref, warnings) {
36110
36270
  if (ref.file) {
36111
36271
  const file2 = path73.resolve(manifestDir, ref.file);
@@ -36296,11 +36456,23 @@ function godotNumber(value) {
36296
36456
  function exportGodot(set, base) {
36297
36457
  const [vw, vh] = set.view;
36298
36458
  const pictures = layerPngs(set, base);
36299
- const lines = [`[gd_scene load_steps=${pictures.length + 1} format=3]`, ""];
36459
+ const name = path73.basename(base);
36460
+ const times = set.times ?? [];
36461
+ const lines = [`[gd_scene load_steps=${pictures.length + 1 + (times.length ? 3 : 0)} format=3]`, ""];
36300
36462
  pictures.forEach(({ file }, index) => {
36301
36463
  lines.push(`[ext_resource type="Texture2D" path=${JSON.stringify(`./${file}`)} id="${index + 1}_layer"]`);
36302
36464
  });
36303
- lines.push("", `[node name=${JSON.stringify(path73.basename(base))} type="Node2D"]`, "texture_filter = 1");
36465
+ const extra = [];
36466
+ if (times.length) {
36467
+ const colours = timeColours(set);
36468
+ extra.push({ path: `${base}.colours.png`, data: encodeRgbaPng(colours.width, colours.height, colours.pixels) });
36469
+ extra.push({ path: `${base}.gdshader`, data: GODOT_TIMES_SHADER });
36470
+ lines.push(`[ext_resource type="Shader" path=${JSON.stringify(`./${name}.gdshader`)} id="times_shader"]`);
36471
+ lines.push(`[ext_resource type="Texture2D" path=${JSON.stringify(`./${name}.colours.png`)} id="times_colours"]`);
36472
+ lines.push("", '[sub_resource type="ShaderMaterial" id="times"]', 'shader = ExtResource("times_shader")', 'shader_parameter/colours = ExtResource("times_colours")');
36473
+ }
36474
+ lines.push("", `[node name=${JSON.stringify(name)} type="Node2D"]`, "texture_filter = 1");
36475
+ if (times.length) lines.push(`metadata/times = PackedStringArray(${times.map((t) => JSON.stringify(t.name)).join(", ")})`);
36304
36476
  pictures.forEach(({ layer }, index) => {
36305
36477
  lines.push("", `[node name=${JSON.stringify(layer.name)} type="Parallax2D" parent="."]`);
36306
36478
  lines.push(`scroll_scale = Vector2(${godotNumber(layer.speed)}, ${godotNumber(layer.speedY)})`);
@@ -36309,19 +36481,20 @@ function exportGodot(set, base) {
36309
36481
  if (layer.repeat || layer.repeatY) {
36310
36482
  lines.push(`repeat_size = Vector2(${layer.repeat ? layer.png.width : 0}, ${layer.repeatY ? layer.png.height : 0})`);
36311
36483
  const reach = (view, size) => 2 * (Math.ceil(view / size) + 1) - 1;
36312
- const times = Math.max(layer.repeat ? reach(vw, layer.png.width) : 1, layer.repeatY ? reach(vh, layer.png.height) : 1);
36313
- lines.push(`repeat_times = ${times}`);
36484
+ const times2 = Math.max(layer.repeat ? reach(vw, layer.png.width) : 1, layer.repeatY ? reach(vh, layer.png.height) : 1);
36485
+ lines.push(`repeat_times = ${times2}`);
36314
36486
  }
36315
36487
  lines.push("", `[node name="Sprite2D" type="Sprite2D" parent=${JSON.stringify(layer.name)}]`);
36316
36488
  lines.push(`texture = ExtResource("${index + 1}_layer")`, "centered = false");
36489
+ if (times.length) lines.push('material = SubResource("times")');
36317
36490
  const mod = (value, size) => (value % size + size) % size;
36318
36491
  const px = layer.repeat ? mod(layer.x, layer.png.width) : layer.x;
36319
36492
  const py = layer.repeatY ? mod(layer.y + set.climb, layer.png.height) : layer.y + set.climb;
36320
36493
  lines.push(`position = Vector2(${px}, ${py})`);
36321
36494
  });
36322
36495
  return {
36323
- files: [{ path: `${base}.tscn`, data: lines.join("\n") + "\n" }, ...pictures.map((p) => ({ path: path73.join(path73.dirname(base), p.file), data: p.png }))],
36324
- options: { format: "godot", start: [0, set.climb] }
36496
+ files: [{ path: `${base}.tscn`, data: lines.join("\n") + "\n" }, ...pictures.map((p) => ({ path: path73.join(path73.dirname(base), p.file), data: p.png })), ...extra],
36497
+ options: { format: "godot", start: [0, set.climb], ...times.length ? { shader: `${name}.gdshader` } : {} }
36325
36498
  };
36326
36499
  }
36327
36500
  function uuid(...parts) {
@@ -36560,15 +36733,52 @@ function tileEmpty(png, x0, y0, grid) {
36560
36733
  return true;
36561
36734
  }
36562
36735
  function exportParallax(set, format, base) {
36563
- if (format === "tiled") return exportTiled(set, base);
36564
36736
  if (format === "godot") return exportGodot(set, base);
36565
- return exportLdtk(set, base);
36737
+ const one = (s, b) => format === "tiled" ? exportTiled(s, b) : exportLdtk(s, b);
36738
+ const result = one({ ...set, times: void 0 }, base);
36739
+ if (!set.times?.length) return result;
36740
+ for (const time of set.times) {
36741
+ const timed = one(setAtTime(set, time.name), `${base}.${time.name}`);
36742
+ result.files.push(...timed.files);
36743
+ for (const warning of timed.options.warnings ?? []) {
36744
+ const warnings = result.options.warnings ?? [];
36745
+ if (!warnings.includes(warning)) result.options.warnings = [...warnings, warning];
36746
+ }
36747
+ }
36748
+ result.options.maps = [path73.basename(result.files[0].path), ...set.times.map((t) => `${path73.basename(base)}.${t.name}${path73.extname(result.files[0].path)}`)];
36749
+ return result;
36566
36750
  }
36751
+ var GODOT_TIMES_SHADER = `// Written by pixelkiln parallax export. Recolours the set to one of its times of day.
36752
+ // time = 0 draws the pictures as they are; time = n draws them at the n-th name in the
36753
+ // scene root's metadata/times. blend (0 to 1) mixes toward blend_to, for a fade between
36754
+ // two times. Every layer shares one material, so setting a parameter on it sets all of them.
36755
+ shader_type canvas_item;
36756
+
36757
+ uniform sampler2D colours : filter_nearest, repeat_disable;
36758
+ uniform int time = 0;
36759
+ uniform int blend_to = 0;
36760
+ uniform float blend : hint_range(0.0, 1.0) = 0.0;
36761
+
36762
+ void fragment() {
36763
+ vec4 drawn = texture(TEXTURE, UV);
36764
+ COLOR = drawn;
36765
+ int columns = textureSize(colours, 0).x;
36766
+ for (int i = 0; i < columns; i++) {
36767
+ if (all(lessThan(abs(texelFetch(colours, ivec2(i, 0), 0).rgb - drawn.rgb), vec3(0.5 / 255.0)))) {
36768
+ vec3 now = texelFetch(colours, ivec2(i, time), 0).rgb;
36769
+ vec3 next = texelFetch(colours, ivec2(i, blend_to), 0).rgb;
36770
+ COLOR = vec4(mix(now, next, blend), drawn.a);
36771
+ break;
36772
+ }
36773
+ }
36774
+ }
36775
+ `;
36567
36776
  function previewHtml(set, scale2 = 3) {
36568
36777
  const [vw, vh] = set.view;
36569
- const layers = set.layers.map((layer) => ({
36778
+ const timed = [set, ...(set.times ?? []).map((time) => setAtTime(set, time.name))];
36779
+ const layers = set.layers.map((layer, index) => ({
36570
36780
  name: layer.name,
36571
- src: `data:image/png;base64,${encodeRgbaPng(layer.png.width, layer.png.height, layer.png.pixels).toString("base64")}`,
36781
+ srcs: timed.map((s) => `data:image/png;base64,${encodeRgbaPng(s.layers[index].png.width, s.layers[index].png.height, s.layers[index].png.pixels).toString("base64")}`),
36572
36782
  w: layer.png.width,
36573
36783
  h: layer.png.height,
36574
36784
  x: layer.x,
@@ -36578,7 +36788,8 @@ function previewHtml(set, scale2 = 3) {
36578
36788
  repeat: layer.repeat,
36579
36789
  repeatY: layer.repeatY
36580
36790
  }));
36581
- const data = JSON.stringify({ view: [vw, vh], travel: set.travel, climb: set.climb, layers }).replace(/</g, "\\u003c");
36791
+ const times = ["as drawn", ...(set.times ?? []).map((time) => time.name)];
36792
+ const data = JSON.stringify({ view: [vw, vh], travel: set.travel, climb: set.climb, times, layers }).replace(/</g, "\\u003c");
36582
36793
  return `<!doctype html>
36583
36794
  <html lang="en">
36584
36795
  <head>
@@ -36600,13 +36811,17 @@ function previewHtml(set, scale2 = 3) {
36600
36811
  <main>
36601
36812
  <canvas id="view" width="${vw}" height="${vh}"></canvas>
36602
36813
  <label><button id="play" type="button">Pause</button> camera <input id="cam" type="range" min="0" max="1000" value="0"> <output id="pos"></output></label>
36814
+ <label id="times" hidden>time <select id="time"></select></label>
36603
36815
  <table><thead><tr><th>Layer</th><th>speed</th><th>speedY</th><th>repeat</th></tr></thead><tbody id="rows"></tbody></table>
36604
36816
  </main>
36605
36817
  <script>
36606
36818
  const set = ${data};
36607
36819
  const ctx = document.getElementById("view").getContext("2d");
36608
36820
  ctx.imageSmoothingEnabled = false;
36609
- const images = set.layers.map((layer) => Object.assign(new Image(), { src: layer.src }));
36821
+ const images = set.layers.map((layer) => layer.srcs.map((src) => Object.assign(new Image(), { src })));
36822
+ const pick = document.getElementById("time");
36823
+ set.times.forEach((name, i) => pick.add(new Option(name, i)));
36824
+ document.getElementById("times").hidden = set.times.length < 2;
36610
36825
  const rows = document.getElementById("rows");
36611
36826
  for (const layer of set.layers) {
36612
36827
  const tr = rows.insertRow();
@@ -36635,7 +36850,7 @@ function draw(u) {
36635
36850
  if (layer.repeat) for (let x = ((left % layer.w) + layer.w) % layer.w - layer.w; x < set.view[0]; x += layer.w) xs.push(x);
36636
36851
  const ys = layer.repeatY ? [] : [top];
36637
36852
  if (layer.repeatY) for (let y = ((top % layer.h) + layer.h) % layer.h - layer.h; y < set.view[1]; y += layer.h) ys.push(y);
36638
- for (const y of ys) for (const x of xs) ctx.drawImage(images[i], x, y);
36853
+ for (const y of ys) for (const x of xs) ctx.drawImage(images[i][pick.value | 0], x, y);
36639
36854
  });
36640
36855
  }
36641
36856
  function frame(now) {
@@ -36647,7 +36862,7 @@ function frame(now) {
36647
36862
  draw(slider.value / 1000);
36648
36863
  requestAnimationFrame(frame);
36649
36864
  }
36650
- Promise.all(images.map((image) => image.decode())).then(() => requestAnimationFrame(frame));
36865
+ Promise.all(images.flat().map((image) => image.decode())).then(() => requestAnimationFrame(frame));
36651
36866
  </script>
36652
36867
  </body>
36653
36868
  </html>
@@ -36688,27 +36903,30 @@ async function runParallax(args) {
36688
36903
  sources,
36689
36904
  options: { set: id, ...describe2, ...result.options }
36690
36905
  }, { force: args.force });
36691
- log(` ${id} (${format}): ${path74.relative(process.cwd(), result.files[0].path)} + ${result.files.length - 1} picture(s)`);
36906
+ log(` ${id} (${format}): ${path74.relative(process.cwd(), result.files[0].path)} + ${result.files.length - 1} more file(s)`);
36692
36907
  for (const warning of result.options.warnings ?? []) log(` warning: ${warning}`);
36693
36908
  }
36694
36909
  } else {
36695
36910
  const frames = args.frames ?? 3;
36696
- const strip = joinStripPng(
36697
- cameraPath(set, frames).map(([x, y]) => {
36698
- const frame = composeParallaxFrame(set, x, y);
36911
+ const strip = (s) => joinStripPng(
36912
+ cameraPath(s, frames).map(([x, y]) => {
36913
+ const frame = composeParallaxFrame(s, x, y);
36699
36914
  return encodeRgbaPng(frame.width, frame.height, frame.pixels);
36700
36915
  })
36701
36916
  );
36702
36917
  const base = path74.join(root, `${id}.preview`);
36703
36918
  await writeManagedArtifactBundle(`${base}.pixelkiln.json`, [
36704
36919
  { path: `${base}.html`, data: Buffer.from(previewHtml(set)) },
36705
- { path: `${base}.png`, data: strip }
36920
+ { path: `${base}.png`, data: strip(set) },
36921
+ // A strip for each time of day too, the same frames recoloured.
36922
+ ...(set.times ?? []).map((time) => ({ path: `${base}.${time.name}.png`, data: strip(setAtTime(set, time.name)) }))
36706
36923
  ], {
36707
36924
  kind: "parallax",
36708
36925
  sources,
36709
36926
  options: { set: id, ...describe2, preview: { frames } }
36710
36927
  }, { force: args.force });
36711
36928
  log(` ${id}: ${path74.relative(process.cwd(), base)}.html (scrolls in a browser) + .png (${frames} frames, start to end)`);
36929
+ if (set.times?.length) log(` times: ${set.times.map((time) => `${time.name} (${path74.basename(base)}.${time.name}.png)`).join(", ")}`);
36712
36930
  }
36713
36931
  for (const layer of set.layers) {
36714
36932
  const seam = (layer.seamRatio === void 0 ? "" : `, seam ${layer.seamRatio.toFixed(1)}`) + (layer.seamRatioY === void 0 ? "" : `, vertical seam ${layer.seamRatioY.toFixed(1)}`);
@@ -36735,7 +36953,8 @@ function setOptions(set) {
36735
36953
  ...layer.loop ? { loop: layer.loop } : {},
36736
36954
  ...layer.finish ?? {}
36737
36955
  })),
36738
- ...set.palette ? { palette: set.palette } : {}
36956
+ ...set.palette ? { palette: set.palette } : {},
36957
+ ...set.times ? { times: Object.fromEntries(set.times.map((time) => [time.name, { palette: time.palette, cool: time.cool }])) } : {}
36739
36958
  };
36740
36959
  }
36741
36960