pixelkiln 0.109.0 → 0.111.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.
@@ -49,7 +49,13 @@
49
49
  selected: /* @__PURE__ */ new Set(),
50
50
  drawerTab: "overview",
51
51
  tags: /* @__PURE__ */ new Set(),
52
- size: "m"
52
+ size: "m",
53
+ model: null,
54
+ modelSide: "edited",
55
+ modelReference: "guide",
56
+ sheetWidth: 0,
57
+ sideWidth: 0,
58
+ side3d: true
53
59
  };
54
60
  var CARD_SIZES = {
55
61
  s: { box: [112, 80], tile: [48, 36] },
@@ -58,7 +64,7 @@
58
64
  };
59
65
  var declaredTags = (item) => item.asset && Array.isArray(item.asset.tags) ? item.asset.tags : [];
60
66
  var PREFS_KEY = "pixelkiln.gallery.prefs";
61
- var PREF_NAMES = ["playLoops", "backdrop", "notify", "onion", "drawerTab", "size"];
67
+ var PREF_NAMES = ["playLoops", "backdrop", "notify", "onion", "drawerTab", "size", "modelReference", "sheetWidth", "sideWidth", "side3d"];
62
68
  function loadPrefs() {
63
69
  try {
64
70
  const saved = JSON.parse(localStorage.getItem(PREFS_KEY) || "{}");
@@ -660,6 +666,2353 @@
660
666
  return form;
661
667
  }
662
668
 
669
+ // src/glb.ts
670
+ var MAGIC = 1179937895;
671
+ var CHUNK_JSON = 1313821514;
672
+ var CHUNK_BIN = 5130562;
673
+ var pad4 = (n) => n + 3 & ~3;
674
+ function parseGlb(bytes) {
675
+ if (bytes.length < 20) throw new Error("invalid glb: shorter than a header and one chunk");
676
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
677
+ if (view.getUint32(0, true) !== MAGIC) throw new Error("invalid glb: missing the glTF signature");
678
+ const version = view.getUint32(4, true);
679
+ if (version !== 2) throw new Error(`invalid glb: container version ${version}; only version 2 is supported`);
680
+ const total = view.getUint32(8, true);
681
+ if (total > bytes.length) throw new Error(`invalid glb: header says ${total} bytes, the file has ${bytes.length}`);
682
+ let offset = 12;
683
+ let json = null;
684
+ let bin = null;
685
+ const extraChunks = [];
686
+ while (offset + 8 <= total) {
687
+ const length = view.getUint32(offset, true);
688
+ const type = view.getUint32(offset + 4, true);
689
+ const start = offset + 8;
690
+ if (start + length > total) throw new Error("invalid glb: a chunk runs past the end of the file");
691
+ const data = bytes.subarray(start, start + length);
692
+ if (type === CHUNK_JSON && !json) {
693
+ let parsed;
694
+ try {
695
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(data));
696
+ } catch (error) {
697
+ throw new Error(`invalid glb: the JSON chunk does not parse (${error instanceof Error ? error.message : String(error)})`);
698
+ }
699
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("invalid glb: the JSON chunk is not an object");
700
+ json = parsed;
701
+ } else if (type === CHUNK_BIN && !bin) {
702
+ bin = data;
703
+ } else {
704
+ extraChunks.push({ type, data });
705
+ }
706
+ offset = start + pad4(length);
707
+ }
708
+ if (!json) throw new Error("invalid glb: no JSON chunk");
709
+ if (!json.asset || typeof json.asset.version !== "string") throw new Error("invalid glb: the JSON has no asset.version");
710
+ const declared = json.buffers?.[0]?.byteLength;
711
+ if (bin && typeof declared === "number") {
712
+ if (declared > bin.length) throw new Error(`invalid glb: buffer 0 declares ${declared} bytes, the BIN chunk has ${bin.length}`);
713
+ bin = bin.subarray(0, declared);
714
+ }
715
+ const document2 = { json, bin: bin ?? new Uint8Array(0), extraChunks };
716
+ for (const [index, bufferView] of (json.bufferViews ?? []).entries()) {
717
+ if (bufferView.buffer !== 0) continue;
718
+ const start = bufferView.byteOffset ?? 0;
719
+ if (start < 0 || bufferView.byteLength < 0 || start + bufferView.byteLength > document2.bin.length) {
720
+ throw new Error(`invalid glb: bufferView ${index} runs past the end of the buffer`);
721
+ }
722
+ }
723
+ return document2;
724
+ }
725
+ function glbImageBytes(document2, imageIndex) {
726
+ const image = document2.json.images?.[imageIndex];
727
+ if (!image) throw new Error(`the model has no image ${imageIndex}`);
728
+ if (typeof image.bufferView !== "number") {
729
+ throw new Error(`image ${imageIndex} is not embedded in the file (it names ${image.uri ? "a uri" : "no data"})`);
730
+ }
731
+ const bufferView = document2.json.bufferViews?.[image.bufferView];
732
+ if (!bufferView || bufferView.buffer !== 0) throw new Error(`image ${imageIndex} points at a bufferView the file does not hold`);
733
+ const start = bufferView.byteOffset ?? 0;
734
+ return { bytes: document2.bin.subarray(start, start + bufferView.byteLength), mimeType: image.mimeType ?? null };
735
+ }
736
+ var COMPONENTS = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 };
737
+ function readAccessor(document2, accessorIndex) {
738
+ const accessor = document2.json.accessors?.[accessorIndex];
739
+ if (!accessor) throw new Error(`the model has no accessor ${accessorIndex}`);
740
+ if (accessor.sparse) throw new Error(`accessor ${accessorIndex} is sparse, which is not supported`);
741
+ const size = COMPONENTS[accessor.type];
742
+ if (!size) throw new Error(`accessor ${accessorIndex} has unknown type ${accessor.type}`);
743
+ const bytesPer = { 5120: 1, 5121: 1, 5122: 2, 5123: 2, 5125: 4, 5126: 4 }[accessor.componentType];
744
+ if (!bytesPer) throw new Error(`accessor ${accessorIndex} has unknown component type ${accessor.componentType}`);
745
+ const float = accessor.componentType === 5126 || accessor.normalized === true;
746
+ const out = float ? new Float32Array(accessor.count * size) : new Uint32Array(accessor.count * size);
747
+ if (typeof accessor.bufferView !== "number") return { data: out, size, count: accessor.count };
748
+ const bufferView = document2.json.bufferViews?.[accessor.bufferView];
749
+ if (!bufferView || bufferView.buffer !== 0) throw new Error(`accessor ${accessorIndex} points at a bufferView the file does not hold`);
750
+ const stride = bufferView.byteStride || bytesPer * size;
751
+ const start = (bufferView.byteOffset ?? 0) + (accessor.byteOffset ?? 0);
752
+ if (accessor.count && start + stride * (accessor.count - 1) + bytesPer * size > document2.bin.length) {
753
+ throw new Error(`accessor ${accessorIndex} runs past the end of the buffer`);
754
+ }
755
+ const view = new DataView(document2.bin.buffer, document2.bin.byteOffset, document2.bin.byteLength);
756
+ for (let element = 0; element < accessor.count; element++) {
757
+ for (let component = 0; component < size; component++) {
758
+ const at = start + element * stride + component * bytesPer;
759
+ let value;
760
+ switch (accessor.componentType) {
761
+ case 5120:
762
+ value = view.getInt8(at);
763
+ if (accessor.normalized) value = Math.max(value / 127, -1);
764
+ break;
765
+ case 5121:
766
+ value = view.getUint8(at);
767
+ if (accessor.normalized) value /= 255;
768
+ break;
769
+ case 5122:
770
+ value = view.getInt16(at, true);
771
+ if (accessor.normalized) value = Math.max(value / 32767, -1);
772
+ break;
773
+ case 5123:
774
+ value = view.getUint16(at, true);
775
+ if (accessor.normalized) value /= 65535;
776
+ break;
777
+ case 5125:
778
+ value = view.getUint32(at, true);
779
+ break;
780
+ default:
781
+ value = view.getFloat32(at, true);
782
+ }
783
+ out[element * size + component] = value;
784
+ }
785
+ }
786
+ return { data: out, size, count: accessor.count };
787
+ }
788
+ function isBodyNode(node) {
789
+ return Array.isArray(node.extras?.hiddenBy) || node.extras?.body === true;
790
+ }
791
+
792
+ // src/glb-guide.ts
793
+ function regionName(name) {
794
+ let text = name.trim().replace(/^.*[:|]/, "").replace(/^(DEF|ORG|MCH)[-_]/i, "");
795
+ let side = "";
796
+ const suffix = /[._\- ](l|r|left|right)$/i.exec(text);
797
+ if (suffix) {
798
+ side = suffix[1].toLowerCase().startsWith("l") ? "left" : "right";
799
+ text = text.slice(0, suffix.index);
800
+ }
801
+ const words = text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/[_.\-]+/g, " ").replace(/([a-zA-Z])(\d)/g, "$1 $2").toLowerCase().split(/\s+/).filter(Boolean);
802
+ if (!side && (words[0] === "left" || words[0] === "right" || words[0] === "l" || words[0] === "r") && words.length > 1) {
803
+ side = words.shift().startsWith("l") ? "left" : "right";
804
+ }
805
+ const phrase = [side, ...words].filter(Boolean).join(" ") || name.trim() || "piece";
806
+ return phrase.charAt(0).toUpperCase() + phrase.slice(1);
807
+ }
808
+ function primitivesUsingImage(json, imageIndex) {
809
+ const materials = /* @__PURE__ */ new Set();
810
+ for (const [index, material] of (json.materials ?? []).entries()) {
811
+ const infos = [
812
+ material.pbrMetallicRoughness?.baseColorTexture,
813
+ material.pbrMetallicRoughness?.metallicRoughnessTexture,
814
+ material.normalTexture,
815
+ material.occlusionTexture,
816
+ material.emissiveTexture
817
+ ];
818
+ if (infos.some((info) => info && json.textures?.[info.index]?.source === imageIndex)) materials.add(index);
819
+ }
820
+ const found = [];
821
+ for (const [meshIndex, mesh] of (json.meshes ?? []).entries()) {
822
+ for (const [primitiveIndex, primitive] of (mesh.primitives ?? []).entries()) {
823
+ if (typeof primitive.material === "number" && materials.has(primitive.material) && (primitive.mode ?? 4) === 4) {
824
+ found.push({ mesh: meshIndex, primitive: primitiveIndex });
825
+ }
826
+ }
827
+ }
828
+ return found;
829
+ }
830
+ var WELD = 1 << 16;
831
+ function uvGuide(document2, imageIndex) {
832
+ const json = document2.json;
833
+ const pointOf = /* @__PURE__ */ new Map();
834
+ const us = [];
835
+ const vs = [];
836
+ const parent = [];
837
+ const find = (a) => {
838
+ let root = a;
839
+ while (parent[root] !== root) root = parent[root];
840
+ while (parent[a] !== root) {
841
+ const next = parent[a];
842
+ parent[a] = root;
843
+ a = next;
844
+ }
845
+ return root;
846
+ };
847
+ const triangles = [];
848
+ for (const { mesh: meshIndex, primitive: primitiveIndex } of primitivesUsingImage(json, imageIndex)) {
849
+ const mesh = json.meshes[meshIndex];
850
+ const primitive = mesh.primitives[primitiveIndex];
851
+ const meshName = mesh.name ?? `mesh ${meshIndex}`;
852
+ if (typeof primitive.attributes.TEXCOORD_0 !== "number") continue;
853
+ const uv = readAccessor(document2, primitive.attributes.TEXCOORD_0);
854
+ if (uv.size < 2) continue;
855
+ const indices = typeof primitive.indices === "number" ? readAccessor(document2, primitive.indices).data : Uint32Array.from({ length: uv.count }, (_, index) => index);
856
+ const joints = typeof primitive.attributes.JOINTS_0 === "number" ? readAccessor(document2, primitive.attributes.JOINTS_0) : null;
857
+ const weights = typeof primitive.attributes.WEIGHTS_0 === "number" ? readAccessor(document2, primitive.attributes.WEIGHTS_0) : null;
858
+ const normals = typeof primitive.attributes.NORMAL === "number" ? readAccessor(document2, primitive.attributes.NORMAL) : null;
859
+ const node = (json.nodes ?? []).find((candidate) => candidate.mesh === meshIndex);
860
+ const skinJoints = typeof node?.skin === "number" ? json.skins?.[node.skin]?.joints ?? null : null;
861
+ const boneName = (joint) => {
862
+ const nodeIndex = skinJoints?.[joint];
863
+ return nodeIndex === void 0 ? null : json.nodes?.[nodeIndex]?.name ?? `bone ${joint}`;
864
+ };
865
+ const local = new Int32Array(uv.count);
866
+ for (let vertex = 0; vertex < uv.count; vertex++) {
867
+ const u = uv.data[vertex * uv.size];
868
+ const v = uv.data[vertex * uv.size + 1];
869
+ const key = Math.round(u * WELD) * (WELD * 4) + Math.round(v * WELD);
870
+ let point = pointOf.get(key);
871
+ if (point === void 0) {
872
+ point = us.length;
873
+ pointOf.set(key, point);
874
+ us.push(u);
875
+ vs.push(v);
876
+ parent.push(point);
877
+ }
878
+ local[vertex] = point;
879
+ }
880
+ for (let at = 0; at + 2 < indices.length; at += 3) {
881
+ const corners = [indices[at], indices[at + 1], indices[at + 2]];
882
+ if (corners.some((corner) => corner >= uv.count)) continue;
883
+ const [a, b, c] = corners.map((corner) => local[corner]);
884
+ const area = Math.abs((us[b] - us[a]) * (vs[c] - vs[a]) - (us[c] - us[a]) * (vs[b] - vs[a])) / 2;
885
+ const bones = /* @__PURE__ */ new Map();
886
+ if (joints && weights && skinJoints) {
887
+ for (const corner of corners) {
888
+ for (let slot = 0; slot < Math.min(joints.size, weights.size); slot++) {
889
+ const weight = weights.data[corner * weights.size + slot];
890
+ if (!(weight > 0)) continue;
891
+ const name = boneName(joints.data[corner * joints.size + slot]);
892
+ if (name) bones.set(name, (bones.get(name) ?? 0) + weight);
893
+ }
894
+ }
895
+ }
896
+ const normal = [0, 0, 0];
897
+ if (normals && normals.size >= 3) {
898
+ for (const corner of corners) for (let axis = 0; axis < 3; axis++) normal[axis] += normals.data[corner * normals.size + axis];
899
+ }
900
+ triangles.push({ a, b, c, area, mesh: meshName, bones: [...bones], normal });
901
+ parent[find(a)] = find(b);
902
+ parent[find(b)] = find(c);
903
+ }
904
+ }
905
+ const groups = /* @__PURE__ */ new Map();
906
+ const points = us.length;
907
+ for (const triangle of triangles) {
908
+ const root = find(triangle.a);
909
+ let group = groups.get(root);
910
+ if (!group) groups.set(root, group = { triangles: [], edges: /* @__PURE__ */ new Map() });
911
+ group.triangles.push(triangle);
912
+ for (const [from, to] of [[triangle.a, triangle.b], [triangle.b, triangle.c], [triangle.c, triangle.a]]) {
913
+ if (from === to) continue;
914
+ const key = Math.min(from, to) * points + Math.max(from, to);
915
+ group.edges.set(key, (group.edges.get(key) ?? 0) + 1);
916
+ }
917
+ }
918
+ const pieces = [];
919
+ for (const group of groups.values()) {
920
+ let area = 0;
921
+ let minU = Infinity, minV = Infinity, maxU = -Infinity, maxV = -Infinity;
922
+ let centreU = 0, centreV = 0;
923
+ const bones = /* @__PURE__ */ new Map();
924
+ const meshes = [];
925
+ let largest = group.triangles[0];
926
+ const normal = [0, 0, 0];
927
+ for (const triangle of group.triangles) {
928
+ for (let axis = 0; axis < 3; axis++) normal[axis] += triangle.normal[axis] * (triangle.area + 1e-9);
929
+ area += triangle.area;
930
+ if (triangle.area > largest.area) largest = triangle;
931
+ if (!meshes.includes(triangle.mesh)) meshes.push(triangle.mesh);
932
+ for (const point of [triangle.a, triangle.b, triangle.c]) {
933
+ minU = Math.min(minU, us[point]);
934
+ maxU = Math.max(maxU, us[point]);
935
+ minV = Math.min(minV, vs[point]);
936
+ maxV = Math.max(maxV, vs[point]);
937
+ }
938
+ centreU += triangle.area * (us[triangle.a] + us[triangle.b] + us[triangle.c]) / 3;
939
+ centreV += triangle.area * (vs[triangle.a] + vs[triangle.b] + vs[triangle.c]) / 3;
940
+ for (const [name, weight] of triangle.bones) bones.set(name, (bones.get(name) ?? 0) + weight * (triangle.area + 1e-9));
941
+ }
942
+ const centre = area > 0 ? [centreU / area, centreV / area] : [us[largest.a], vs[largest.a]];
943
+ const inside = (triangle, [u, v]) => {
944
+ const sign = (p, q) => (u - us[q]) * (vs[p] - vs[q]) - (us[p] - us[q]) * (v - vs[q]);
945
+ const d1 = sign(triangle.a, triangle.b), d2 = sign(triangle.b, triangle.c), d3 = sign(triangle.c, triangle.a);
946
+ return !((d1 < 0 || d2 < 0 || d3 < 0) && (d1 > 0 || d2 > 0 || d3 > 0));
947
+ };
948
+ const anchor = group.triangles.some((triangle) => inside(triangle, centre)) ? centre : [(us[largest.a] + us[largest.b] + us[largest.c]) / 3, (vs[largest.a] + vs[largest.b] + vs[largest.c]) / 3];
949
+ const outline = [];
950
+ for (const [key, count] of group.edges) {
951
+ if (count !== 1) continue;
952
+ const from = Math.floor(key / points);
953
+ const to = key - from * points;
954
+ outline.push(us[from], vs[from], us[to], vs[to]);
955
+ }
956
+ let bone = null;
957
+ let most = 0;
958
+ for (const [name, weight] of [...bones].sort(([x], [y]) => x.localeCompare(y))) {
959
+ if (weight > most) {
960
+ most = weight;
961
+ bone = name;
962
+ }
963
+ }
964
+ pieces.push({
965
+ id: 0,
966
+ region: regionName(bone ?? meshes[0] ?? "piece"),
967
+ bone,
968
+ facing: facingOf(normal),
969
+ meshes: meshes.sort(),
970
+ bounds: [minU, minV, maxU, maxV],
971
+ area,
972
+ anchor,
973
+ outline,
974
+ triangles: group.triangles.length
975
+ });
976
+ }
977
+ pieces.sort((x, y) => y.area - x.area || x.bounds[1] - y.bounds[1] || x.bounds[0] - y.bounds[0]);
978
+ pieces.forEach((piece, index) => {
979
+ piece.id = index;
980
+ });
981
+ const regionArea = /* @__PURE__ */ new Map();
982
+ for (const piece of pieces) regionArea.set(piece.region, (regionArea.get(piece.region) ?? 0) + piece.area);
983
+ const regions = [...regionArea].sort(([x, a], [y, b]) => b - a || x.localeCompare(y)).map(([name]) => name);
984
+ return { pieces, regions };
985
+ }
986
+ function facingOf(normal) {
987
+ const length = Math.hypot(...normal);
988
+ if (!(length > 0)) return null;
989
+ const [x, y, z] = normal.map((value) => value / length);
990
+ const strongest = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
991
+ if (strongest < 0.6) return null;
992
+ if (strongest === Math.abs(z)) return z > 0 ? "front" : "back";
993
+ if (strongest === Math.abs(y)) return y > 0 ? "top" : "underside";
994
+ return x > 0 ? "left" : "right";
995
+ }
996
+ function pieceLabel(piece) {
997
+ return piece.facing ? `${piece.region}, ${piece.facing}` : piece.region;
998
+ }
999
+ function regionColour(index) {
1000
+ const hue = index * 137.508 % 360;
1001
+ const lightness = index % 2 ? 62 : 52;
1002
+ return `hsl(${hue.toFixed(0)} 95% ${lightness}%)`;
1003
+ }
1004
+
1005
+ // src/gallery/client/src/hand-edit.ts
1006
+ var EDIT_STATUS_TEXT = {
1007
+ same: "The generated art’s pixels, not changed yet. Open it in your editor and save.",
1008
+ edited: "Differs from the generated art. mount and pack place this file; the generated file stays as the record.",
1009
+ "regenerated-since": "The generated art changed after this edit was saved; the edit is based on an older generation.",
1010
+ missing: "The declared file is not on disk."
1011
+ };
1012
+ async function postHandEdit(item, action, extra) {
1013
+ const pr = projectOf(item);
1014
+ const body = { action, assetId: item.assetId, styleId: item.styleId, expectedSha256: pr.manifestSha256, ...extra };
1015
+ if (item.project) body.project = item.project;
1016
+ S.snap = await postEdit(body);
1017
+ }
1018
+ var editableOutputs = (item) => item.outputs.length && item.outputs.every((o) => o.exists && o.mediaType === "image/png");
1019
+ var memberNoun = (item, n) => isFrameSet(item) ? n === 1 ? "frame" : "frames" : item.outputs.every((o) => o.role && /^tile/i.test(o.role)) ? n === 1 ? "tile" : "tiles" : n === 1 ? "member" : "members";
1020
+ function handEditSection(item) {
1021
+ const canStart = EDITABLE && item.declared && item.asset && projectOf(item)?.manifestSha256 && editableOutputs(item);
1022
+ if (!item.edit && !canStart) return null;
1023
+ const set = item.edits.length > 1;
1024
+ const s = el("section", "meta");
1025
+ s.append(el("h3", null, set ? "Hand edit (" + item.edits.length + " " + memberNoun(item, item.edits.length) + ")" : "Hand edit"));
1026
+ if (item.edit) {
1027
+ const pair = el("div", "pair");
1028
+ const shared = displayScale(item.width, item.height, 200, 160);
1029
+ const fig = (out, label) => {
1030
+ const f = el("figure");
1031
+ if (out && out.url) {
1032
+ const img = el("img");
1033
+ img.src = out.url;
1034
+ img.alt = label;
1035
+ if (shared >= 1) {
1036
+ img.width = item.width * shared;
1037
+ img.height = item.height * shared;
1038
+ }
1039
+ f.append(img);
1040
+ } else f.append(el("span", "state-dim", "not on disk"));
1041
+ f.append(el("figcaption", null, label));
1042
+ return f;
1043
+ };
1044
+ const at = set ? Math.min(ui.member, item.edits.length - 1) : 0;
1045
+ const which = set ? " · " + (item.outputs[at].role || memberNoun(item, 1) + " " + (at + 1)) : "";
1046
+ pair.append(fig(item.outputs[at], "generated" + which), fig(item.edits[at], "edit" + which));
1047
+ s.append(pair);
1048
+ const dl = el("dl");
1049
+ const tone = item.editStatus === "edited" ? "ok" : item.editStatus === "same" ? "dim" : "warn";
1050
+ const st = el("span", "state-" + tone);
1051
+ st.append(el("i", "dot " + tone), document.createTextNode(" " + item.editStatus));
1052
+ row(dl, "status", st);
1053
+ row(dl, "why", EDIT_STATUS_TEXT[item.editStatus] || "");
1054
+ if (set) {
1055
+ row(dl, "files", item.source + ", one per " + memberNoun(item, 1) + ": " + item.edits.map((e) => e.path.split("/").pop()).join(", "), { mono: true, copy: item.edits.map((e) => e.absolutePath).join("\n") });
1056
+ const differing = item.editChanged.filter(Boolean).length;
1057
+ row(dl, "changed", differing + " of " + item.edits.length + " " + memberNoun(item, item.edits.length) + " differ from the generated art" + (differing ? ": " + item.edits.filter((e, i) => item.editChanged[i]).map((e) => item.outputs[item.edits.indexOf(e)].role || e.path.split("/").pop()).join(", ") : ""));
1058
+ } else {
1059
+ row(dl, "file", item.edit.path, { mono: true, copy: item.edit.absolutePath });
1060
+ if (item.edit.sha256) row(dl, "sha256", item.edit.sha256.slice(0, 16) + "…", { mono: true, copy: item.edit.sha256 });
1061
+ }
1062
+ row(dl, "saved", fmtWhen(item.edits.reduce((latest, e) => e.modifiedAt && (!latest || e.modifiedAt > latest) ? e.modifiedAt : latest, null)));
1063
+ if (item.editMeta) {
1064
+ row(dl, "editor", item.editMeta.editor + ", " + fmtWhen(item.editMeta.savedAt) + (item.editMeta.changedSince ? "; a file changed since" : ""));
1065
+ if (item.editMeta.basedOn && !set) row(dl, "based on", item.editMeta.basedOn.slice(0, 16) + "…", { mono: true, copy: item.editMeta.basedOn });
1066
+ if (item.editMeta.project) row(dl, "layers", item.editMeta.project, { mono: true });
1067
+ }
1068
+ s.append(dl);
1069
+ } else {
1070
+ s.append(el("div", "state-dim", item.outputs.length > 1 ? "Touch the " + memberNoun(item, 2) + " up in your own editor or in the browser, where they open as " + (isFrameSet(item) ? "one animation" : "the frames of one project") + ". The generated files stay untouched; the edit is one sibling file per " + memberNoun(item, 1) + " that the manifest points at, and mount, pack, and export place those instead." : "Touch it up in your own editor. The generated file stays untouched; the edit is a sibling file the manifest points at, and mount and pack place that instead."));
1071
+ }
1072
+ if (EDITABLE && item.declared && projectOf(item)?.manifestSha256) {
1073
+ const acts = el("div", "hand-actions");
1074
+ const msg = el("span", "msg");
1075
+ const go = async (label, action, extra, done) => {
1076
+ const b = el("button", label === "Detach edit" || EDITOR && S.ED && S.ED.installed ? null : "primary", label);
1077
+ b.type = "button";
1078
+ b.onclick = async () => {
1079
+ b.disabled = true;
1080
+ msg.className = "msg";
1081
+ msg.textContent = "…";
1082
+ try {
1083
+ await postHandEdit(item, action, extra);
1084
+ ui.notice = { id: item.id, text: done };
1085
+ render();
1086
+ } catch (err) {
1087
+ showSaveError(msg, b, err);
1088
+ }
1089
+ };
1090
+ acts.append(b);
1091
+ };
1092
+ if (EDITOR && S.ED && (item.edit || canStart) && editorSource(item)) {
1093
+ if (S.ED.installed) {
1094
+ const b = el("button", "primary", "Edit in browser");
1095
+ b.type = "button";
1096
+ b.title = "Open in Pixelorama here; Save writes the edit file and declares it";
1097
+ b.onclick = () => openEditorSheet(item);
1098
+ acts.append(b);
1099
+ } else if (S.ED.release && !S.ED.installing) {
1100
+ const b = el("button", null, "Install editor to edit in browser");
1101
+ b.type = "button";
1102
+ b.onclick = () => {
1103
+ installEditor();
1104
+ window.scrollTo({ top: 0 });
1105
+ };
1106
+ acts.append(b);
1107
+ }
1108
+ }
1109
+ if (item.edit) {
1110
+ go("Open in desktop editor", "start-edit", { open: true }, "Opened " + item.edit.path + " in your editor. Save there, then Refresh.");
1111
+ go("Detach edit", "detach-edit", {}, "Detached. The file" + (set ? "s are" : " is") + " still at " + item.source + "; the generated art is placed again.");
1112
+ } else if (canStart) {
1113
+ const many = item.outputs.length > 1;
1114
+ go("Edit by hand", "start-edit", { open: true }, "Created the edit file" + (many ? "s and opened the first " + memberNoun(item, 1) : " and opened it") + " in your editor. Save there, then Refresh to see it here.");
1115
+ go("Create edit file" + (many ? "s" : "") + " only", "start-edit", { open: false }, "Created the edit file" + (many ? "s" : "") + " and declared " + (many ? "them" : "it") + " in the manifest.");
1116
+ }
1117
+ acts.append(msg);
1118
+ s.append(acts);
1119
+ }
1120
+ return s;
1121
+ }
1122
+
1123
+ // src/gallery/client/src/sheet.ts
1124
+ var editorSources = (item) => {
1125
+ if (item.edits.length && item.edits.every((e) => e.exists)) return { files: item.edits, fromEdit: true };
1126
+ if (editableOutputs(item)) return { files: item.outputs, fromEdit: false };
1127
+ return null;
1128
+ };
1129
+ var editorSource = (item) => {
1130
+ const s = editorSources(item);
1131
+ return s ? s.files[0] : null;
1132
+ };
1133
+ var toBase64 = (buf) => new Promise((resolve, reject) => {
1134
+ const r = new FileReader();
1135
+ r.onload = () => resolve(String(r.result).slice(String(r.result).indexOf(",") + 1));
1136
+ r.onerror = () => reject(r.error);
1137
+ r.readAsDataURL(new Blob([buf]));
1138
+ });
1139
+ function sheetStatus(tone, text) {
1140
+ if (!S.SHEET) return;
1141
+ S.SHEET.status.textContent = "";
1142
+ S.SHEET.status.append(el("i", "dot " + tone), document.createTextNode(text));
1143
+ }
1144
+ function sheetButtons() {
1145
+ if (!S.SHEET) return;
1146
+ const busy = !S.SHEET.opened || S.SHEET.pending !== null;
1147
+ S.SHEET.save.disabled = busy || !S.SHEET.dirty;
1148
+ S.SHEET.saveClose.disabled = busy;
1149
+ }
1150
+ function openEditorSheet(item, custom = null) {
1151
+ if (S.SHEET) return;
1152
+ const src = custom ? null : editorSource(item);
1153
+ const host = $("dialog-host");
1154
+ host.textContent = "";
1155
+ const scrim = el("div", "sheet-scrim");
1156
+ scrim.onclick = () => closeEditorSheet();
1157
+ const panel = el("div", "sheet editor-host");
1158
+ const bar = el("div", "rbar");
1159
+ const close = el("button", null, "Close");
1160
+ close.type = "button";
1161
+ close.onclick = () => closeEditorSheet();
1162
+ const title = el("b", null, custom ? custom.title : (item.project ? item.project + ":" : "") + item.styleId + "/" + item.assetId + " · " + item.width + "×" + item.height + (item.outputs.length > 1 ? " · " + item.outputs.length + " " + memberNoun(item, item.outputs.length) : ""));
1163
+ const status = el("span", "st");
1164
+ const acts = el("div", "acts");
1165
+ const msg = el("span", "msg");
1166
+ const compare = el("label", "chip");
1167
+ compare.hidden = true;
1168
+ compare.title = custom?.referenceTitle ?? "The generated art on a locked layer at 50%, for comparison; never part of the saved file";
1169
+ const compareBox = el("input");
1170
+ compareBox.type = "checkbox";
1171
+ compareBox.checked = true;
1172
+ compareBox.onchange = () => showReference(compareBox.checked);
1173
+ compare.append(compareBox, document.createTextNode(" " + (custom?.referenceLabel ?? "show generated")));
1174
+ const save = el("button", "primary", "Save to project");
1175
+ save.type = "button";
1176
+ save.onclick = () => requestEditorSave(false);
1177
+ const saveClose = el("button", null, "Save & close");
1178
+ saveClose.type = "button";
1179
+ saveClose.onclick = () => requestEditorSave(true);
1180
+ let sideToggle = null;
1181
+ if (custom?.side) {
1182
+ sideToggle = el("label", "chip");
1183
+ const box = el("input");
1184
+ box.type = "checkbox";
1185
+ box.checked = custom.side.shown();
1186
+ box.onchange = () => {
1187
+ custom.side.setShown(box.checked);
1188
+ layoutSide();
1189
+ };
1190
+ sideToggle.append(box, document.createTextNode(" " + custom.side.label));
1191
+ }
1192
+ const layerToggles = (custom?.layers ?? []).map((layer) => {
1193
+ const label = el("label", "chip");
1194
+ label.hidden = true;
1195
+ label.title = layer.title;
1196
+ label.dataset.layer = layer.name;
1197
+ const box = el("input");
1198
+ box.type = "checkbox";
1199
+ box.checked = true;
1200
+ box.onchange = () => {
1201
+ if (S.SHEET?.opened) S.SHEET.frame.contentWindow.postMessage({ type: "pixelkiln:layer", name: layer.name, visible: box.checked }, location.origin);
1202
+ };
1203
+ label.append(box, document.createTextNode(" " + layer.label));
1204
+ return label;
1205
+ });
1206
+ acts.append(msg, ...sideToggle ? [sideToggle] : [], ...layerToggles, compare, save, saveClose);
1207
+ bar.append(close, title, status, acts);
1208
+ const stage = el("div", "stage");
1209
+ const frame = el("iframe");
1210
+ frame.title = "Pixelorama";
1211
+ frame.src = S.ED.url;
1212
+ const loading = el("div", "loading");
1213
+ const loadText = el("div");
1214
+ loadText.append(el("b", null, "Loading the editor"), document.createTextNode("The first open compiles a 40 MB build; later opens come from the browser cache."));
1215
+ loading.append(loadText);
1216
+ stage.append(frame, loading);
1217
+ if (custom?.below) {
1218
+ panel.classList.add("with-legend");
1219
+ custom.below.classList.add("sheet-below");
1220
+ }
1221
+ panel.append(bar);
1222
+ if (custom?.below) panel.append(custom.below);
1223
+ const divider = el("div", "sheet-divider");
1224
+ divider.setAttribute("role", "separator");
1225
+ divider.setAttribute("aria-orientation", "vertical");
1226
+ divider.title = "Drag to share the width between the 3D view and the editor";
1227
+ if (custom?.side) panel.append(custom.side.element, divider);
1228
+ panel.append(stage);
1229
+ const edge = el("div", "sheet-edge");
1230
+ edge.title = "Drag to resize";
1231
+ panel.append(edge);
1232
+ const layoutSide = () => {
1233
+ const on = !!custom?.side && custom.side.shown();
1234
+ panel.classList.toggle("with-side", on);
1235
+ if (custom?.side) {
1236
+ custom.side.element.hidden = !on;
1237
+ divider.hidden = !on;
1238
+ }
1239
+ };
1240
+ const applyWidths = () => {
1241
+ if (ui.sheetWidth) panel.style.width = Math.min(ui.sheetWidth, innerWidth - 24) + "px";
1242
+ if (ui.sideWidth) panel.style.setProperty("--side-w", Math.max(180, Math.min(ui.sideWidth, panel.clientWidth - 360)) + "px");
1243
+ };
1244
+ dragResize(panel, edge, (x) => {
1245
+ ui.sheetWidth = Math.max(560, Math.min(innerWidth - 24, innerWidth - x));
1246
+ applyWidths();
1247
+ });
1248
+ dragResize(panel, divider, (x) => {
1249
+ ui.sideWidth = x - panel.getBoundingClientRect().left;
1250
+ applyWidths();
1251
+ });
1252
+ layoutSide();
1253
+ host.append(scrim, panel);
1254
+ applyWidths();
1255
+ S.SHEET = { layerToggles, previewing: null, previewTimer: null, lastKind: null, custom, item, frame, loading, status, msg, save, saveClose, compare, dirty: false, opened: false, ready: null, pending: null, requests: 0, source: src, sentProject: false, sentReference: false, reference: false, roles: null };
1256
+ sheetStatus("cool", "loading");
1257
+ sheetButtons();
1258
+ close.focus({ preventScroll: true });
1259
+ }
1260
+ async function sendOpen() {
1261
+ const { item } = S.SHEET;
1262
+ const sources = editorSources(item);
1263
+ const style = S.snap.styles.find((s) => s.id === item.styleId && s.project === item.project);
1264
+ const projectUrl = sources.fromEdit && item.editMeta && item.editMeta.projectUrl && S.SHEET.ready.version >= 2 ? item.editMeta.projectUrl : null;
1265
+ const set = sources.files.length > 1;
1266
+ if (set && S.SHEET.ready.version < 3) {
1267
+ S.SHEET.msg.textContent = "This editor build cannot open sets; reinstall it with pixelkiln tools install editor.";
1268
+ sheetStatus("bad", "unsupported");
1269
+ return;
1270
+ }
1271
+ const referenceFiles = sources.fromEdit && S.SHEET.ready.version >= 4 && item.outputs.every((o) => o.exists && o.url) ? item.outputs : null;
1272
+ const pngs = [];
1273
+ const reference = [];
1274
+ let pxo = null;
1275
+ try {
1276
+ for (const file of sources.files) {
1277
+ const res = await fetch(file.url, { cache: "no-store" });
1278
+ if (!res.ok) throw new Error(await res.text());
1279
+ pngs.push(await res.arrayBuffer());
1280
+ }
1281
+ if (projectUrl) {
1282
+ const p = await fetch(projectUrl, { cache: "no-store" });
1283
+ if (p.ok) pxo = await p.arrayBuffer();
1284
+ }
1285
+ for (const file of referenceFiles || []) {
1286
+ const res = await fetch(file.url, { cache: "no-store" });
1287
+ if (res.ok) reference.push({ role: file.role || null, png: await res.arrayBuffer() });
1288
+ }
1289
+ } catch (err) {
1290
+ if (S.SHEET) {
1291
+ S.SHEET.msg.textContent = "Could not load the image: " + err.message;
1292
+ sheetStatus("bad", "failed");
1293
+ }
1294
+ return;
1295
+ }
1296
+ if (!S.SHEET) return;
1297
+ const request = "open-" + ++S.SHEET.requests;
1298
+ S.SHEET.sentProject = !!pxo;
1299
+ S.SHEET.roles = set ? item.outputs.map((o) => o.role || null) : null;
1300
+ const message = {
1301
+ type: "pixelkiln:open",
1302
+ request,
1303
+ asset: { key: item.styleId + "/" + item.assetId, id: item.id, name: item.assetId, width: item.width, height: item.height },
1304
+ png: pngs[0],
1305
+ palette: style ? style.palette : []
1306
+ };
1307
+ const transfer = [pngs[0]];
1308
+ if (set) {
1309
+ message.frames = pngs.map((png, i) => ({ role: S.SHEET.roles[i], png }));
1310
+ message.fps = isFrameSet(item) ? item.fps || 12 : 1;
1311
+ for (const png of pngs.slice(1)) transfer.push(png);
1312
+ message.png = pngs[0].slice(0);
1313
+ transfer.push(message.png);
1314
+ }
1315
+ if (pxo) {
1316
+ message.pxo = pxo;
1317
+ transfer.push(pxo);
1318
+ }
1319
+ if (reference.length === (referenceFiles || []).length && reference.length) {
1320
+ message.reference = reference;
1321
+ for (const r of reference) transfer.push(r.png);
1322
+ }
1323
+ S.SHEET.sentReference = !!message.reference;
1324
+ S.SHEET.frame.contentWindow.postMessage(message, location.origin, transfer);
1325
+ sheetStatus("cool", "opening");
1326
+ }
1327
+ function showReference(visible) {
1328
+ if (!S.SHEET || !S.SHEET.opened || !S.SHEET.reference) return;
1329
+ S.SHEET.frame.contentWindow.postMessage({ type: "pixelkiln:reference", visible }, location.origin);
1330
+ }
1331
+ function requestEditorSave(close) {
1332
+ if (!S.SHEET || !S.SHEET.opened || S.SHEET.pending) return;
1333
+ const request = "save-" + ++S.SHEET.requests;
1334
+ S.SHEET.pending = { request, close };
1335
+ S.SHEET.lastKind = "save";
1336
+ S.SHEET.msg.textContent = "";
1337
+ sheetStatus("cool", "saving");
1338
+ sheetButtons();
1339
+ S.SHEET.frame.contentWindow.postMessage({ type: "pixelkiln:request-save", request }, location.origin);
1340
+ }
1341
+ async function onEditorMessage(m) {
1342
+ switch (m.type) {
1343
+ case "pixelkiln:ready":
1344
+ S.SHEET.ready = m;
1345
+ if (m.version !== S.ED.protocol) {
1346
+ S.SHEET.msg.textContent = "The editor speaks protocol " + m.version + "; this gallery expects " + S.ED.protocol + ". Reinstall it with pixelkiln tools install editor.";
1347
+ sheetStatus("bad", "mismatch");
1348
+ return;
1349
+ }
1350
+ if (S.SHEET.custom) {
1351
+ try {
1352
+ await S.SHEET.custom.open();
1353
+ } catch (err) {
1354
+ if (S.SHEET) {
1355
+ S.SHEET.msg.textContent = "Could not load the image: " + err.message;
1356
+ sheetStatus("bad", "failed");
1357
+ }
1358
+ }
1359
+ } else sendOpen();
1360
+ break;
1361
+ case "pixelkiln:opened":
1362
+ S.SHEET.opened = true;
1363
+ S.SHEET.loading.remove();
1364
+ S.SHEET.reference = !!m.reference;
1365
+ S.SHEET.compare.hidden = !S.SHEET.reference;
1366
+ for (const toggle of S.SHEET.layerToggles) toggle.hidden = !(Array.isArray(m.guides) && m.guides.includes(toggle.dataset.layer));
1367
+ if (S.SHEET.custom) {
1368
+ sheetStatus(S.SHEET.sentProject && m.source !== "pxo" ? "warn" : "ok", S.SHEET.custom.opened(m));
1369
+ sheetButtons();
1370
+ break;
1371
+ }
1372
+ if (m.source === "pxo") sheetStatus("ok", "editing the edit file" + (m.frames > 1 ? "s" : "") + " with " + (m.layers === 1 ? "the layer" : m.layers + " layers") + (m.frames > 1 ? " and " + m.frames + " " + memberNoun(S.SHEET.item, m.frames) : "") + " restored");
1373
+ else if (S.SHEET.sentProject) sheetStatus("warn", "editing the flattened edit file" + (m.frames > 1 ? "s" : "") + "; the layer file could not be opened");
1374
+ else if (m.source === "frames") sheetStatus("ok", (S.SHEET.item.edits.length ? "editing the edit files" : "editing a copy of the generated " + memberNoun(S.SHEET.item, m.frames)) + " as " + m.frames + " frames" + (isFrameSet(S.SHEET.item) ? "" : ", one per " + memberNoun(S.SHEET.item, 1)));
1375
+ else sheetStatus("ok", S.SHEET.item.edit && S.SHEET.item.edit.exists ? "editing the edit file" : "editing a copy of the generated art");
1376
+ if (S.SHEET.reference) S.SHEET.status.append(document.createTextNode(" · generated art shown through at 50%"));
1377
+ sheetButtons();
1378
+ break;
1379
+ case "pixelkiln:dirty":
1380
+ if (!m.dirty && S.SHEET.lastKind === "preview") {
1381
+ if (S.SHEET.dirty) schedulePreview();
1382
+ break;
1383
+ }
1384
+ S.SHEET.dirty = !!m.dirty;
1385
+ if (m.dirty) schedulePreview();
1386
+ if (S.SHEET.opened && !S.SHEET.pending) sheetStatus(S.SHEET.dirty ? "warn" : "ok", S.SHEET.dirty ? "unsaved changes" : "saved");
1387
+ sheetButtons();
1388
+ break;
1389
+ case "pixelkiln:save": {
1390
+ if (S.SHEET.previewing && m.request === S.SHEET.previewing) {
1391
+ S.SHEET.previewing = null;
1392
+ try {
1393
+ await S.SHEET.custom?.live?.(m.png);
1394
+ } catch {
1395
+ }
1396
+ break;
1397
+ }
1398
+ const pending = S.SHEET.pending;
1399
+ if (!pending || pending.request !== m.request) return;
1400
+ try {
1401
+ if (S.SHEET.custom) {
1402
+ await S.SHEET.custom.save(m);
1403
+ S.SHEET.dirty = false;
1404
+ S.SHEET.pending = null;
1405
+ render();
1406
+ if (pending.close) {
1407
+ closeEditorSheet(true);
1408
+ return;
1409
+ }
1410
+ sheetStatus("ok", "saved");
1411
+ sheetButtons();
1412
+ break;
1413
+ }
1414
+ const body = { editor: S.SHEET.ready.editor, protocol: S.SHEET.ready.version };
1415
+ if (S.SHEET.roles) {
1416
+ if (!Array.isArray(m.frames)) throw new Error("the editor returned no frames");
1417
+ body.frames = [];
1418
+ for (const f of m.frames) body.frames.push({ role: f.role === void 0 ? null : f.role, png: await toBase64(f.png) });
1419
+ } else {
1420
+ body.png = await toBase64(m.png);
1421
+ }
1422
+ if (m.pxo && m.pxo.byteLength) body.pxo = await toBase64(m.pxo);
1423
+ await postHandEdit(S.SHEET.item, "save-edit", body);
1424
+ const saved = S.snap.items.find((i) => i.id === S.SHEET.item.id);
1425
+ if (saved) S.SHEET.item = saved;
1426
+ S.SHEET.dirty = false;
1427
+ S.SHEET.pending = null;
1428
+ ui.notice = { id: S.SHEET.item.id, text: "Saved " + (saved && saved.edits.length > 1 ? saved.edits.length + " " + memberNoun(saved, saved.edits.length) + " to " + saved.source : saved && saved.edit ? saved.edit.path : "the edit") + ". mount and pack place " + (saved && saved.edits.length > 1 ? "them" : "it") + " in place of the generated art." };
1429
+ render();
1430
+ if (pending.close) {
1431
+ closeEditorSheet(true);
1432
+ return;
1433
+ }
1434
+ sheetStatus("ok", "saved");
1435
+ } catch (err) {
1436
+ S.SHEET.pending = null;
1437
+ S.SHEET.msg.textContent = err.message + (err.status === 409 ? " Press Refresh, then save again." : "");
1438
+ sheetStatus("bad", "not saved");
1439
+ }
1440
+ sheetButtons();
1441
+ break;
1442
+ }
1443
+ case "pixelkiln:error":
1444
+ S.SHEET.msg.textContent = m.message || "The editor reported an error.";
1445
+ if (S.SHEET.pending) {
1446
+ S.SHEET.pending = null;
1447
+ sheetStatus("bad", "not saved");
1448
+ sheetButtons();
1449
+ }
1450
+ break;
1451
+ }
1452
+ }
1453
+ function schedulePreview() {
1454
+ const sheet = S.SHEET;
1455
+ if (!sheet || !sheet.custom?.live || !sheet.opened) return;
1456
+ clearTimeout(sheet.previewTimer);
1457
+ sheet.previewTimer = setTimeout(() => {
1458
+ if (S.SHEET !== sheet || sheet.pending) return;
1459
+ if (sheet.previewing) {
1460
+ schedulePreview();
1461
+ return;
1462
+ }
1463
+ const request = "preview-" + ++sheet.requests;
1464
+ sheet.previewing = request;
1465
+ sheet.lastKind = "preview";
1466
+ sheet.frame.contentWindow.postMessage({ type: "pixelkiln:request-save", request }, location.origin);
1467
+ }, 450);
1468
+ }
1469
+ function dragResize(panel, handle, move) {
1470
+ handle.addEventListener("pointerdown", (e) => {
1471
+ e.preventDefault();
1472
+ handle.setPointerCapture(e.pointerId);
1473
+ panel.classList.add("resizing");
1474
+ const onMove = (ev) => move(ev.clientX);
1475
+ const done = () => {
1476
+ panel.classList.remove("resizing");
1477
+ handle.removeEventListener("pointermove", onMove);
1478
+ handle.removeEventListener("pointerup", done);
1479
+ handle.removeEventListener("pointercancel", done);
1480
+ savePrefs();
1481
+ };
1482
+ handle.addEventListener("pointermove", onMove);
1483
+ handle.addEventListener("pointerup", done);
1484
+ handle.addEventListener("pointercancel", done);
1485
+ });
1486
+ }
1487
+ function closeEditorSheet(force) {
1488
+ if (!S.SHEET) return;
1489
+ clearTimeout(S.SHEET.previewTimer);
1490
+ if (S.SHEET.dirty && !force && !confirm("Discard unsaved changes in the editor?")) return;
1491
+ S.SHEET = null;
1492
+ $("dialog-host").textContent = "";
1493
+ refresh();
1494
+ }
1495
+ window.addEventListener("beforeunload", (e) => {
1496
+ if (S.SHEET && S.SHEET.dirty) {
1497
+ e.preventDefault();
1498
+ e.returnValue = "";
1499
+ }
1500
+ });
1501
+
1502
+ // src/gallery/client/src/viewer.ts
1503
+ var identity = () => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
1504
+ function multiply(a, b, out = new Float32Array(16)) {
1505
+ for (let column2 = 0; column2 < 4; column2++) {
1506
+ const b0 = b[column2 * 4], b1 = b[column2 * 4 + 1], b2 = b[column2 * 4 + 2], b3 = b[column2 * 4 + 3];
1507
+ for (let row2 = 0; row2 < 4; row2++) {
1508
+ out[column2 * 4 + row2] = a[row2] * b0 + a[4 + row2] * b1 + a[8 + row2] * b2 + a[12 + row2] * b3;
1509
+ }
1510
+ }
1511
+ return out;
1512
+ }
1513
+ function compose(t, q, s, out) {
1514
+ const x = q[0], y = q[1], z = q[2], w = q[3];
1515
+ const xx = x * x, yy = y * y, zz = z * z, xy = x * y, xz = x * z, yz = y * z, wx = w * x, wy = w * y, wz = w * z;
1516
+ out[0] = (1 - 2 * (yy + zz)) * s[0];
1517
+ out[1] = 2 * (xy + wz) * s[0];
1518
+ out[2] = 2 * (xz - wy) * s[0];
1519
+ out[3] = 0;
1520
+ out[4] = 2 * (xy - wz) * s[1];
1521
+ out[5] = (1 - 2 * (xx + zz)) * s[1];
1522
+ out[6] = 2 * (yz + wx) * s[1];
1523
+ out[7] = 0;
1524
+ out[8] = 2 * (xz + wy) * s[2];
1525
+ out[9] = 2 * (yz - wx) * s[2];
1526
+ out[10] = (1 - 2 * (xx + yy)) * s[2];
1527
+ out[11] = 0;
1528
+ out[12] = t[0];
1529
+ out[13] = t[1];
1530
+ out[14] = t[2];
1531
+ out[15] = 1;
1532
+ return out;
1533
+ }
1534
+ function perspective(fovY, aspect, near, far) {
1535
+ const f = 1 / Math.tan(fovY / 2);
1536
+ const out = new Float32Array(16);
1537
+ out[0] = f / aspect;
1538
+ out[5] = f;
1539
+ out[10] = (far + near) / (near - far);
1540
+ out[11] = -1;
1541
+ out[14] = 2 * far * near / (near - far);
1542
+ return out;
1543
+ }
1544
+ function lookAt(eye, target) {
1545
+ let zx = eye[0] - target[0], zy = eye[1] - target[1], zz = eye[2] - target[2];
1546
+ const zl = Math.hypot(zx, zy, zz) || 1;
1547
+ zx /= zl;
1548
+ zy /= zl;
1549
+ zz /= zl;
1550
+ let xx = zz, xy = 0, xz = -zx;
1551
+ const xl = Math.hypot(xx, xy, xz) || 1;
1552
+ xx /= xl;
1553
+ xy /= xl;
1554
+ xz /= xl;
1555
+ const yx = zy * xz - zz * xy, yy = zz * xx - zx * xz, yz = zx * xy - zy * xx;
1556
+ return new Float32Array([
1557
+ xx,
1558
+ yx,
1559
+ zx,
1560
+ 0,
1561
+ xy,
1562
+ yy,
1563
+ zy,
1564
+ 0,
1565
+ xz,
1566
+ yz,
1567
+ zz,
1568
+ 0,
1569
+ -(xx * eye[0] + xy * eye[1] + xz * eye[2]),
1570
+ -(yx * eye[0] + yy * eye[1] + yz * eye[2]),
1571
+ -(zx * eye[0] + zy * eye[1] + zz * eye[2]),
1572
+ 1
1573
+ ]);
1574
+ }
1575
+ function slerp(a, ai, b, bi, t, out) {
1576
+ let bx = b[bi], by = b[bi + 1], bz = b[bi + 2], bw = b[bi + 3];
1577
+ const ax = a[ai], ay = a[ai + 1], az = a[ai + 2], aw = a[ai + 3];
1578
+ let cos = ax * bx + ay * by + az * bz + aw * bw;
1579
+ if (cos < 0) {
1580
+ cos = -cos;
1581
+ bx = -bx;
1582
+ by = -by;
1583
+ bz = -bz;
1584
+ bw = -bw;
1585
+ }
1586
+ let wa = 1 - t, wb = t;
1587
+ if (cos < 0.9995) {
1588
+ const angle = Math.acos(cos), sin = Math.sin(angle);
1589
+ wa = Math.sin((1 - t) * angle) / sin;
1590
+ wb = Math.sin(t * angle) / sin;
1591
+ }
1592
+ out[0] = ax * wa + bx * wb;
1593
+ out[1] = ay * wa + by * wb;
1594
+ out[2] = az * wa + bz * wb;
1595
+ out[3] = aw * wa + bw * wb;
1596
+ const length = Math.hypot(out[0], out[1], out[2], out[3]) || 1;
1597
+ out[0] /= length;
1598
+ out[1] /= length;
1599
+ out[2] /= length;
1600
+ out[3] /= length;
1601
+ }
1602
+ var VERTEX = `#version 300 es
1603
+ layout(location=0) in vec3 aPosition;
1604
+ layout(location=1) in vec3 aNormal;
1605
+ layout(location=2) in vec2 aUv;
1606
+ layout(location=3) in vec4 aJoints;
1607
+ layout(location=4) in vec4 aWeights;
1608
+ layout(location=5) in vec4 aTangent;
1609
+ uniform mat4 uViewProjection;
1610
+ uniform mat4 uModel;
1611
+ uniform bool uSkinned;
1612
+ uniform mat4 uJoints[JOINTS];
1613
+ out vec2 vUv;
1614
+ out vec3 vNormal;
1615
+ out vec4 vTangent;
1616
+ void main() {
1617
+ mat4 model = uModel;
1618
+ if (uSkinned) {
1619
+ model = aWeights.x * uJoints[int(aJoints.x)] + aWeights.y * uJoints[int(aJoints.y)]
1620
+ + aWeights.z * uJoints[int(aJoints.z)] + aWeights.w * uJoints[int(aJoints.w)];
1621
+ }
1622
+ vUv = aUv;
1623
+ vNormal = mat3(model) * aNormal;
1624
+ vTangent = vec4(mat3(model) * aTangent.xyz, aTangent.w);
1625
+ gl_Position = uViewProjection * model * vec4(aPosition, 1.0);
1626
+ }`;
1627
+ var FRAGMENT = `#version 300 es
1628
+ precision highp float;
1629
+ in vec2 vUv;
1630
+ in vec3 vNormal;
1631
+ in vec4 vTangent;
1632
+ uniform sampler2D uColour;
1633
+ uniform sampler2D uNormalMap;
1634
+ uniform bool uHasColour;
1635
+ uniform bool uHasNormalMap;
1636
+ uniform vec4 uTint;
1637
+ uniform vec3 uLight;
1638
+ out vec4 colour;
1639
+ void main() {
1640
+ vec4 base = uTint;
1641
+ if (uHasColour) base *= texture(uColour, vUv);
1642
+ if (base.a < 0.05) discard;
1643
+ vec3 normal = normalize(vNormal);
1644
+ if (!gl_FrontFacing) normal = -normal;
1645
+ if (uHasNormalMap && dot(vTangent.xyz, vTangent.xyz) > 0.0) {
1646
+ vec3 tangent = normalize(vTangent.xyz - normal * dot(normal, vTangent.xyz));
1647
+ vec3 bitangent = cross(normal, tangent) * vTangent.w;
1648
+ vec3 mapped = texture(uNormalMap, vUv).xyz * 2.0 - 1.0;
1649
+ normal = normalize(mat3(tangent, bitangent, normal) * mapped);
1650
+ }
1651
+ // Three flat bands of light.
1652
+ float lit = dot(normal, uLight) * 0.5 + 0.5;
1653
+ float band = lit < 0.34 ? 0.59 : lit < 0.67 ? 0.80 : 1.0;
1654
+ colour = vec4(base.rgb * band, 1.0);
1655
+ }`;
1656
+ function createModelViewer(host) {
1657
+ const canvas = document.createElement("canvas");
1658
+ canvas.className = "model-canvas";
1659
+ const context = canvas.getContext("webgl2", { antialias: true, alpha: true, premultipliedAlpha: false });
1660
+ if (!context) return null;
1661
+ host.append(canvas);
1662
+ return buildViewer(host, canvas, context);
1663
+ }
1664
+ function buildViewer(host, canvas, gl) {
1665
+ const jointLimit = Math.max(4, Math.min(128, Math.floor((gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS) - 24) / 4)));
1666
+ const shader = (type, source) => {
1667
+ const s = gl.createShader(type);
1668
+ gl.shaderSource(s, source);
1669
+ gl.compileShader(s);
1670
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s) || "shader failed to compile");
1671
+ return s;
1672
+ };
1673
+ const program = gl.createProgram();
1674
+ gl.attachShader(program, shader(gl.VERTEX_SHADER, VERTEX.replace("JOINTS", String(jointLimit))));
1675
+ gl.attachShader(program, shader(gl.FRAGMENT_SHADER, FRAGMENT));
1676
+ gl.linkProgram(program);
1677
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program) || "program failed to link");
1678
+ const uniform = (name) => gl.getUniformLocation(program, name);
1679
+ const U = {
1680
+ viewProjection: uniform("uViewProjection"),
1681
+ model: uniform("uModel"),
1682
+ skinned: uniform("uSkinned"),
1683
+ joints: uniform("uJoints"),
1684
+ colour: uniform("uColour"),
1685
+ normalMap: uniform("uNormalMap"),
1686
+ hasColour: uniform("uHasColour"),
1687
+ hasNormalMap: uniform("uHasNormalMap"),
1688
+ tint: uniform("uTint"),
1689
+ light: uniform("uLight")
1690
+ };
1691
+ let doc = null;
1692
+ let meshNodes = [];
1693
+ let clips = [];
1694
+ let parents = new Int32Array(0);
1695
+ let order = [];
1696
+ let rest2 = [];
1697
+ let pose = [];
1698
+ let world = [];
1699
+ let skins = [];
1700
+ let materials = [];
1701
+ let bitmaps = [];
1702
+ let byImage = /* @__PURE__ */ new Map();
1703
+ let owned = { buffers: [], vaos: [], textures: [] };
1704
+ let centre = [0, 1, 0];
1705
+ let radius = 1;
1706
+ let yaw = 0.5, pitch = 0.18, distance = 0, framed = false;
1707
+ let activeClip = null;
1708
+ let time = 0;
1709
+ let playing = !matchMedia("(prefers-reduced-motion: reduce)").matches;
1710
+ const shown = /* @__PURE__ */ new Map();
1711
+ let disposed = false;
1712
+ let generation = 0;
1713
+ const release = () => {
1714
+ for (const b of owned.buffers) gl.deleteBuffer(b);
1715
+ for (const v of owned.vaos) gl.deleteVertexArray(v);
1716
+ for (const t of owned.textures) gl.deleteTexture(t);
1717
+ for (const bitmap of bitmaps) bitmap?.close();
1718
+ owned = { buffers: [], vaos: [], textures: [] };
1719
+ byImage = /* @__PURE__ */ new Map();
1720
+ bitmaps = [];
1721
+ };
1722
+ const applyVisibility = () => {
1723
+ for (const mesh of meshNodes) {
1724
+ mesh.visible = mesh.hiddenBy ? !mesh.hiddenBy.some((item) => shown.get(item) ?? true) : shown.get(mesh.name) ?? true;
1725
+ }
1726
+ };
1727
+ async function show(next) {
1728
+ const mine = ++generation;
1729
+ const json = next.json;
1730
+ const decoded = await Promise.all((json.images ?? []).map(async (_, index) => {
1731
+ try {
1732
+ const { bytes, mimeType } = glbImageBytes(next, index);
1733
+ return await createImageBitmap(new Blob([bytes.slice()], { type: mimeType || "image/png" }), { premultiplyAlpha: "none", colorSpaceConversion: "none" });
1734
+ } catch {
1735
+ return null;
1736
+ }
1737
+ }));
1738
+ if (disposed || mine !== generation) {
1739
+ for (const bitmap of decoded) bitmap?.close();
1740
+ return { items: [], clips: [], note: null };
1741
+ }
1742
+ release();
1743
+ doc = next;
1744
+ bitmaps = decoded;
1745
+ let note = null;
1746
+ const nodes = json.nodes ?? [];
1747
+ parents = new Int32Array(nodes.length).fill(-1);
1748
+ nodes.forEach((node, index) => {
1749
+ for (const child of node.children ?? []) if (child < nodes.length) parents[child] = index;
1750
+ });
1751
+ order = [];
1752
+ const visit = (index) => {
1753
+ order.push(index);
1754
+ for (const child of nodes[index].children ?? []) if (child < nodes.length) visit(child);
1755
+ };
1756
+ nodes.forEach((_, index) => {
1757
+ if (parents[index] < 0) visit(index);
1758
+ });
1759
+ rest2 = nodes.map((node) => ({
1760
+ t: node.translation ? [...node.translation] : [0, 0, 0],
1761
+ r: node.rotation ? [...node.rotation] : [0, 0, 0, 1],
1762
+ s: node.scale ? [...node.scale] : [1, 1, 1],
1763
+ matrix: node.matrix ? new Float32Array(node.matrix) : null
1764
+ }));
1765
+ pose = rest2.map((entry) => ({ t: [...entry.t], r: [...entry.r], s: [...entry.s] }));
1766
+ world = nodes.map(() => identity());
1767
+ skins = (json.skins ?? []).map((skin) => {
1768
+ const inverse = typeof skin.inverseBindMatrices === "number" ? readAccessor(next, skin.inverseBindMatrices).data : (() => {
1769
+ const all = new Float32Array(skin.joints.length * 16);
1770
+ for (let i = 0; i < skin.joints.length; i++) all.set(identity(), i * 16);
1771
+ return all;
1772
+ })();
1773
+ if (skin.joints.length > jointLimit) note = "This skeleton has " + skin.joints.length + " bones; this browser draws up to " + jointLimit + ", so the model is shown in its rest pose.";
1774
+ return { joints: skin.joints, inverse, matrices: new Float32Array(Math.min(skin.joints.length, jointLimit) * 16) };
1775
+ });
1776
+ const texture = (imageIndex) => {
1777
+ const bitmap = imageIndex === void 0 ? null : bitmaps[imageIndex];
1778
+ if (!bitmap) return null;
1779
+ const t = gl.createTexture();
1780
+ owned.textures.push(t);
1781
+ gl.bindTexture(gl.TEXTURE_2D, t);
1782
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
1783
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
1784
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
1785
+ gl.generateMipmap(gl.TEXTURE_2D);
1786
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
1787
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
1788
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1789
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1790
+ byImage.set(imageIndex, [...byImage.get(imageIndex) ?? [], t]);
1791
+ return t;
1792
+ };
1793
+ const sourceOf = (info) => info ? json.textures?.[info.index]?.source : void 0;
1794
+ materials = (json.materials ?? []).map((material) => ({
1795
+ colour: texture(sourceOf(material.pbrMetallicRoughness?.baseColorTexture)),
1796
+ normal: texture(sourceOf(material.normalTexture)),
1797
+ tint: Array.isArray(material.pbrMetallicRoughness?.baseColorFactor) ? material.pbrMetallicRoughness.baseColorFactor : [1, 1, 1, 1],
1798
+ doubleSided: material.doubleSided === true
1799
+ }));
1800
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
1801
+ const built = /* @__PURE__ */ new Map();
1802
+ const buildMesh = (meshIndex) => {
1803
+ const cached = built.get(meshIndex);
1804
+ if (cached) return cached;
1805
+ const primitives = [];
1806
+ for (const primitive of json.meshes?.[meshIndex]?.primitives ?? []) {
1807
+ if ((primitive.mode ?? 4) !== 4 || typeof primitive.attributes.POSITION !== "number") continue;
1808
+ const vao = gl.createVertexArray();
1809
+ owned.vaos.push(vao);
1810
+ gl.bindVertexArray(vao);
1811
+ const attribute = (location2, name, fallback) => {
1812
+ const accessorIndex = primitive.attributes[name];
1813
+ if (typeof accessorIndex !== "number") {
1814
+ if (fallback) gl.vertexAttrib4f(location2, fallback[0], fallback[1], fallback[2], fallback[3]);
1815
+ return null;
1816
+ }
1817
+ const { data, size } = readAccessor(next, accessorIndex);
1818
+ const buffer = gl.createBuffer();
1819
+ owned.buffers.push(buffer);
1820
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
1821
+ gl.bufferData(gl.ARRAY_BUFFER, data instanceof Float32Array ? data : Float32Array.from(data), gl.STATIC_DRAW);
1822
+ gl.enableVertexAttribArray(location2);
1823
+ gl.vertexAttribPointer(location2, size, gl.FLOAT, false, 0, 0);
1824
+ return data;
1825
+ };
1826
+ const positions = attribute(0, "POSITION", null);
1827
+ attribute(1, "NORMAL", [0, 0, 1, 0]);
1828
+ attribute(2, "TEXCOORD_0", [0, 0, 0, 0]);
1829
+ const joints = attribute(3, "JOINTS_0", [0, 0, 0, 0]);
1830
+ const weights = attribute(4, "WEIGHTS_0", [1, 0, 0, 0]);
1831
+ attribute(5, "TANGENT", [0, 0, 0, 0]);
1832
+ for (let at = 0; at < positions.length; at += 3) {
1833
+ for (let axis = 0; axis < 3; axis++) {
1834
+ min[axis] = Math.min(min[axis], positions[at + axis]);
1835
+ max[axis] = Math.max(max[axis], positions[at + axis]);
1836
+ }
1837
+ }
1838
+ let count = positions.length / 3;
1839
+ let indexType = 0;
1840
+ if (typeof primitive.indices === "number") {
1841
+ const indices = readAccessor(next, primitive.indices).data;
1842
+ const buffer = gl.createBuffer();
1843
+ owned.buffers.push(buffer);
1844
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);
1845
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
1846
+ count = indices.length;
1847
+ indexType = gl.UNSIGNED_INT;
1848
+ }
1849
+ primitives.push({ vao, count, indexType, material: typeof primitive.material === "number" ? primitive.material : -1, skinnedData: Boolean(joints && weights) });
1850
+ }
1851
+ gl.bindVertexArray(null);
1852
+ built.set(meshIndex, primitives);
1853
+ return primitives;
1854
+ };
1855
+ const hasBody = nodes.some((node) => typeof node.mesh === "number" && isBodyNode(node));
1856
+ meshNodes = [];
1857
+ nodes.forEach((node, index) => {
1858
+ if (typeof node.mesh !== "number") return;
1859
+ const hiddenBy = Array.isArray(node.extras?.hiddenBy) ? node.extras.hiddenBy.map(String) : null;
1860
+ meshNodes.push({
1861
+ node: index,
1862
+ name: node.name ?? "part " + (meshNodes.length + 1),
1863
+ skin: typeof node.skin === "number" && skins[node.skin] && skins[node.skin].joints.length <= jointLimit ? node.skin : -1,
1864
+ primitives: buildMesh(node.mesh),
1865
+ visible: true,
1866
+ hiddenBy: hiddenBy ?? (hasBody && isBodyNode(node) ? [] : null)
1867
+ });
1868
+ });
1869
+ const items = meshNodes.filter((mesh) => !mesh.hiddenBy).map((mesh) => mesh.name);
1870
+ const toggles = hasBody ? items : items.length > 1 ? items : [];
1871
+ for (const name of [...shown.keys()]) if (!toggles.includes(name)) shown.delete(name);
1872
+ applyVisibility();
1873
+ clips = (json.animations ?? []).map((animation, index) => {
1874
+ const channels = [];
1875
+ let duration = 0;
1876
+ for (const channel of animation.channels ?? []) {
1877
+ const sampler = animation.samplers?.[channel.sampler];
1878
+ const node = channel.target?.node;
1879
+ const path = channel.target?.path;
1880
+ if (!sampler || typeof node !== "number" || node >= nodes.length || !["translation", "rotation", "scale"].includes(path)) continue;
1881
+ try {
1882
+ const times = readAccessor(next, sampler.input).data;
1883
+ const output = readAccessor(next, sampler.output);
1884
+ if (!times.length) continue;
1885
+ duration = Math.max(duration, times[times.length - 1]);
1886
+ channels.push({ node, path, times, values: output.data, width: path === "rotation" ? 4 : 3, mode: sampler.interpolation ?? "LINEAR" });
1887
+ } catch {
1888
+ }
1889
+ }
1890
+ return { name: animation.name ?? "animation " + index, duration, channels };
1891
+ }).filter((clip) => clip.channels.length);
1892
+ if (!clips.some((clip) => clip.name === activeClip)) {
1893
+ activeClip = (clips.find((clip) => /idle/i.test(clip.name)) ?? clips.find((clip) => /walk/i.test(clip.name)) ?? clips[0])?.name ?? null;
1894
+ time = 0;
1895
+ }
1896
+ if (min[0] <= max[0]) {
1897
+ centre = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2];
1898
+ radius = Math.max(0.01, Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]) / 2);
1899
+ }
1900
+ if (!framed) {
1901
+ distance = radius / Math.sin(30 * Math.PI / 180 / 2) * 1.05;
1902
+ framed = true;
1903
+ }
1904
+ return { items: toggles, clips: clips.map((clip) => clip.name), note };
1905
+ }
1906
+ const scratch = [0, 0, 0, 0];
1907
+ function animate() {
1908
+ for (let i = 0; i < pose.length; i++) {
1909
+ const p = pose[i], r = rest2[i];
1910
+ p.t[0] = r.t[0];
1911
+ p.t[1] = r.t[1];
1912
+ p.t[2] = r.t[2];
1913
+ p.r[0] = r.r[0];
1914
+ p.r[1] = r.r[1];
1915
+ p.r[2] = r.r[2];
1916
+ p.r[3] = r.r[3];
1917
+ p.s[0] = r.s[0];
1918
+ p.s[1] = r.s[1];
1919
+ p.s[2] = r.s[2];
1920
+ }
1921
+ const clip = clips.find((candidate) => candidate.name === activeClip);
1922
+ if (clip) {
1923
+ const at = clip.duration > 0 ? time % clip.duration : 0;
1924
+ for (const channel of clip.channels) {
1925
+ const { times, values, width } = channel;
1926
+ let hi = 0;
1927
+ while (hi < times.length && times[hi] <= at) hi++;
1928
+ const lo = Math.max(0, hi - 1);
1929
+ hi = Math.min(times.length - 1, hi);
1930
+ const span = times[hi] - times[lo];
1931
+ const t = channel.mode === "STEP" || span <= 0 ? 0 : Math.min(1, Math.max(0, (at - times[lo]) / span));
1932
+ const stride = channel.mode === "CUBICSPLINE" ? width * 3 : width;
1933
+ const offset = channel.mode === "CUBICSPLINE" ? width : 0;
1934
+ const a = lo * stride + offset, b = hi * stride + offset;
1935
+ const target = channel.path === "translation" ? pose[channel.node].t : channel.path === "rotation" ? pose[channel.node].r : pose[channel.node].s;
1936
+ if (channel.path === "rotation") {
1937
+ slerp(values, a, values, b, t, scratch);
1938
+ target[0] = scratch[0];
1939
+ target[1] = scratch[1];
1940
+ target[2] = scratch[2];
1941
+ target[3] = scratch[3];
1942
+ } else for (let i = 0; i < 3; i++) target[i] = values[a + i] + (values[b + i] - values[a + i]) * t;
1943
+ }
1944
+ }
1945
+ const local = new Float32Array(16);
1946
+ for (const index of order) {
1947
+ const matrix = rest2[index].matrix;
1948
+ const own = matrix ?? compose(pose[index].t, pose[index].r, pose[index].s, local);
1949
+ if (parents[index] >= 0) multiply(world[parents[index]], own, world[index]);
1950
+ else world[index].set(own);
1951
+ }
1952
+ const joint = new Float32Array(16);
1953
+ for (const skin of skins) {
1954
+ const drawn = skin.matrices.length / 16;
1955
+ for (let i = 0; i < drawn; i++) {
1956
+ multiply(world[skin.joints[i]], skin.inverse.subarray(i * 16, i * 16 + 16), joint);
1957
+ skin.matrices.set(joint, i * 16);
1958
+ }
1959
+ }
1960
+ }
1961
+ function draw() {
1962
+ const width = canvas.width, height = canvas.height;
1963
+ gl.viewport(0, 0, width, height);
1964
+ gl.clearColor(0, 0, 0, 0);
1965
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
1966
+ if (!doc || !width || !height) return;
1967
+ animate();
1968
+ gl.enable(gl.DEPTH_TEST);
1969
+ gl.useProgram(program);
1970
+ const eye = [
1971
+ centre[0] + distance * Math.cos(pitch) * Math.sin(yaw),
1972
+ centre[1] + distance * Math.sin(pitch),
1973
+ centre[2] + distance * Math.cos(pitch) * Math.cos(yaw)
1974
+ ];
1975
+ const projection = perspective(30 * Math.PI / 180, width / height, Math.max(0.01, distance - radius * 4), distance + radius * 4);
1976
+ gl.uniformMatrix4fv(U.viewProjection, false, multiply(projection, lookAt(eye, centre)));
1977
+ const lx = Math.sin(yaw - 0.7) * 0.75, lz = Math.cos(yaw - 0.7) * 0.75;
1978
+ const ll = Math.hypot(lx, 0.7, lz);
1979
+ gl.uniform3f(U.light, lx / ll, 0.7 / ll, lz / ll);
1980
+ gl.uniform1i(U.colour, 0);
1981
+ gl.uniform1i(U.normalMap, 1);
1982
+ for (const mesh of meshNodes) {
1983
+ if (!mesh.visible) continue;
1984
+ const skin = mesh.skin >= 0 ? skins[mesh.skin] : null;
1985
+ if (skin) gl.uniformMatrix4fv(U.joints, false, skin.matrices);
1986
+ gl.uniformMatrix4fv(U.model, false, world[mesh.node]);
1987
+ for (const primitive of mesh.primitives) {
1988
+ const material = materials[primitive.material];
1989
+ gl.uniform1i(U.skinned, skin && primitive.skinnedData ? 1 : 0);
1990
+ gl.uniform4fv(U.tint, material ? material.tint : [1, 1, 1, 1]);
1991
+ gl.uniform1i(U.hasColour, material?.colour ? 1 : 0);
1992
+ gl.uniform1i(U.hasNormalMap, material?.normal ? 1 : 0);
1993
+ gl.activeTexture(gl.TEXTURE0);
1994
+ gl.bindTexture(gl.TEXTURE_2D, material?.colour ?? null);
1995
+ gl.activeTexture(gl.TEXTURE1);
1996
+ gl.bindTexture(gl.TEXTURE_2D, material?.normal ?? null);
1997
+ if (material?.doubleSided) gl.disable(gl.CULL_FACE);
1998
+ else gl.enable(gl.CULL_FACE);
1999
+ gl.bindVertexArray(primitive.vao);
2000
+ if (primitive.indexType) gl.drawElements(gl.TRIANGLES, primitive.count, primitive.indexType, 0);
2001
+ else gl.drawArrays(gl.TRIANGLES, 0, primitive.count);
2002
+ }
2003
+ }
2004
+ gl.bindVertexArray(null);
2005
+ }
2006
+ const resize = () => {
2007
+ const ratio = Math.min(window.devicePixelRatio || 1, 2);
2008
+ const width = Math.max(1, Math.round(host.clientWidth * ratio)), height = Math.max(1, Math.round(host.clientHeight * ratio));
2009
+ if (canvas.width !== width || canvas.height !== height) {
2010
+ canvas.width = width;
2011
+ canvas.height = height;
2012
+ }
2013
+ };
2014
+ const observer = new ResizeObserver(resize);
2015
+ observer.observe(host);
2016
+ resize();
2017
+ let frame = 0;
2018
+ let last = performance.now();
2019
+ const tick3 = (now) => {
2020
+ if (disposed) return;
2021
+ if (!canvas.isConnected) {
2022
+ dispose();
2023
+ return;
2024
+ }
2025
+ frame = requestAnimationFrame(tick3);
2026
+ const delta = Math.min(0.1, (now - last) / 1e3);
2027
+ last = now;
2028
+ if (playing) time += delta;
2029
+ draw();
2030
+ };
2031
+ frame = requestAnimationFrame(tick3);
2032
+ let dragging = null;
2033
+ canvas.addEventListener("pointerdown", (e) => {
2034
+ dragging = { x: e.clientX, y: e.clientY };
2035
+ canvas.setPointerCapture(e.pointerId);
2036
+ });
2037
+ canvas.addEventListener("pointermove", (e) => {
2038
+ if (!dragging) return;
2039
+ yaw -= (e.clientX - dragging.x) * 0.01;
2040
+ pitch = Math.max(-1.4, Math.min(1.4, pitch + (e.clientY - dragging.y) * 0.01));
2041
+ dragging = { x: e.clientX, y: e.clientY };
2042
+ });
2043
+ const release2 = () => {
2044
+ dragging = null;
2045
+ };
2046
+ canvas.addEventListener("pointerup", release2);
2047
+ canvas.addEventListener("pointercancel", release2);
2048
+ canvas.addEventListener("keydown", (e) => {
2049
+ if (e.key === "ArrowLeft") {
2050
+ yaw -= 0.15;
2051
+ e.preventDefault();
2052
+ e.stopPropagation();
2053
+ } else if (e.key === "ArrowRight") {
2054
+ yaw += 0.15;
2055
+ e.preventDefault();
2056
+ e.stopPropagation();
2057
+ }
2058
+ });
2059
+ canvas.tabIndex = 0;
2060
+ function dispose() {
2061
+ if (disposed) return;
2062
+ disposed = true;
2063
+ cancelAnimationFrame(frame);
2064
+ observer.disconnect();
2065
+ release();
2066
+ gl.deleteProgram(program);
2067
+ canvas.remove();
2068
+ }
2069
+ return {
2070
+ canvas,
2071
+ show,
2072
+ setClip: (name) => {
2073
+ if (name !== activeClip) {
2074
+ activeClip = name;
2075
+ time = 0;
2076
+ }
2077
+ },
2078
+ clip: () => activeClip,
2079
+ setPlaying: (on) => {
2080
+ playing = on;
2081
+ },
2082
+ playing: () => playing,
2083
+ setItem: (name, on) => {
2084
+ shown.set(name, on);
2085
+ applyVisibility();
2086
+ },
2087
+ itemShown: (name) => shown.get(name) ?? true,
2088
+ zoom: (factor) => {
2089
+ distance = Math.max(radius * 0.6, Math.min(radius * 30, distance * factor));
2090
+ },
2091
+ resetCamera: () => {
2092
+ yaw = 0.5;
2093
+ pitch = 0.18;
2094
+ distance = radius / Math.sin(30 * Math.PI / 180 / 2) * 1.05;
2095
+ },
2096
+ coverage: () => {
2097
+ draw();
2098
+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);
2099
+ gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
2100
+ let covered = 0;
2101
+ for (let at = 3; at < pixels.length; at += 4) if (pixels[at] > 0) covered++;
2102
+ return pixels.length ? covered / (pixels.length / 4) : 0;
2103
+ },
2104
+ image: (index) => bitmaps[index] ?? null,
2105
+ snapshot: () => {
2106
+ resize();
2107
+ draw();
2108
+ return canvas.toDataURL("image/png");
2109
+ },
2110
+ setImage: (index, source) => {
2111
+ for (const t of byImage.get(index) ?? []) {
2112
+ gl.bindTexture(gl.TEXTURE_2D, t);
2113
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
2114
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);
2115
+ gl.generateMipmap(gl.TEXTURE_2D);
2116
+ }
2117
+ },
2118
+ dispose
2119
+ };
2120
+ }
2121
+
2122
+ // src/gallery/client/src/models.ts
2123
+ var EDIT_STATUS = {
2124
+ edited: ["ok", "An edited copy of the model as it is now. The model as built is untouched."],
2125
+ "rebuilt-since": ["warn", "The model was rebuilt after this edit was made; the edit is based on the older build."],
2126
+ unrecorded: ["dim", "A file placed at the edit path by hand; nothing records what it was based on."]
2127
+ };
2128
+ var GUIDE_LAYER = "Unwrap guide";
2129
+ var REFERENCE_CHOICES = [
2130
+ ["guide", "the guide"],
2131
+ ["guide+original", "the guide over the texture as built"],
2132
+ ["original", "the texture as built"],
2133
+ ["none", "nothing"]
2134
+ ];
2135
+ var live = null;
2136
+ var modelState = () => live && {
2137
+ id: live.id,
2138
+ url: live.url,
2139
+ loading: live.loading,
2140
+ error: live.error,
2141
+ scene: live.scene,
2142
+ coverage: live.viewer ? live.viewer.coverage() : 0,
2143
+ clip: live.viewer?.clip() ?? null,
2144
+ viewer: live.viewer
2145
+ };
2146
+ var docs = /* @__PURE__ */ new Map();
2147
+ function fetchDoc(url) {
2148
+ let doc = docs.get(url);
2149
+ if (!doc) {
2150
+ doc = fetch(url, { cache: "no-store" }).then(async (res) => {
2151
+ if (!res.ok) throw new Error(await res.text());
2152
+ return parseGlb(new Uint8Array(await res.arrayBuffer()));
2153
+ });
2154
+ doc.catch(() => docs.delete(url));
2155
+ docs.set(url, doc);
2156
+ while (docs.size > 6) docs.delete(docs.keys().next().value);
2157
+ }
2158
+ return doc;
2159
+ }
2160
+ var modelOf = (id) => S.snap.models.find((m) => m.id === id);
2161
+ var canWrite = () => EDITABLE;
2162
+ var thumbs = /* @__PURE__ */ new Map();
2163
+ var queued = [];
2164
+ var thumbViewer;
2165
+ var drawing = false;
2166
+ var thumbSource = (model) => model.edit ?? model.file;
2167
+ function thumbFor(model) {
2168
+ if (model.error) return null;
2169
+ const url = thumbs.get(thumbSource(model).url);
2170
+ if (url) return url;
2171
+ if (!queued.some((m) => thumbSource(m).url === thumbSource(model).url)) queued.push(model);
2172
+ void drainThumbs();
2173
+ return null;
2174
+ }
2175
+ async function drainThumbs() {
2176
+ if (drawing) return;
2177
+ drawing = true;
2178
+ try {
2179
+ while (queued.length) {
2180
+ const model = queued.shift();
2181
+ const source = thumbSource(model).url;
2182
+ if (thumbs.has(source)) continue;
2183
+ if (thumbViewer === void 0) {
2184
+ const host = el("div", "model-thumb-host");
2185
+ host.setAttribute("aria-hidden", "true");
2186
+ document.body.append(host);
2187
+ try {
2188
+ thumbViewer = createModelViewer(host);
2189
+ } catch {
2190
+ thumbViewer = null;
2191
+ }
2192
+ }
2193
+ if (!thumbViewer) return;
2194
+ try {
2195
+ await thumbViewer.show(await fetchDoc(source));
2196
+ const clip = thumbViewer.clip();
2197
+ thumbViewer.setPlaying(false);
2198
+ thumbViewer.setClip(null);
2199
+ thumbViewer.setClip(clip);
2200
+ thumbViewer.resetCamera();
2201
+ thumbs.set(source, await cropToModel(thumbViewer.snapshot()));
2202
+ } catch {
2203
+ continue;
2204
+ }
2205
+ const card2 = document.querySelector('.card.model-card[data-key="' + CSS.escape(model.id) + '"] .cell');
2206
+ if (card2 && !card2.querySelector("img.model-thumb")) {
2207
+ const img = el("img", "model-thumb");
2208
+ img.src = thumbs.get(source);
2209
+ img.alt = model.name;
2210
+ card2.prepend(img);
2211
+ card2.querySelector(".model-glyph").hidden = true;
2212
+ }
2213
+ }
2214
+ } finally {
2215
+ drawing = false;
2216
+ }
2217
+ }
2218
+ async function cropToModel(dataUrl) {
2219
+ const img = new Image();
2220
+ img.src = dataUrl;
2221
+ await img.decode();
2222
+ const work = el("canvas");
2223
+ work.width = img.width;
2224
+ work.height = img.height;
2225
+ const ctx = work.getContext("2d");
2226
+ ctx.drawImage(img, 0, 0);
2227
+ const { data, width, height } = ctx.getImageData(0, 0, work.width, work.height);
2228
+ let left = width, top = height, right = -1, bottom = -1;
2229
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
2230
+ if (data[(y * width + x) * 4 + 3] > 8) {
2231
+ if (x < left) left = x;
2232
+ if (x > right) right = x;
2233
+ if (y < top) top = y;
2234
+ if (y > bottom) bottom = y;
2235
+ }
2236
+ }
2237
+ if (right < 0) return dataUrl;
2238
+ const pad = 0.06;
2239
+ let w = (right - left + 1) * (1 + pad * 2), h = (bottom - top + 1) * (1 + pad * 2);
2240
+ if (w / h < 4 / 3) w = h * 4 / 3;
2241
+ else h = w * 3 / 4;
2242
+ const cx = (left + right + 1) / 2, cy = (top + bottom + 1) / 2;
2243
+ const out = el("canvas");
2244
+ out.width = 320;
2245
+ out.height = 240;
2246
+ out.getContext("2d").drawImage(work, cx - w / 2, cy - h / 2, w, h, 0, 0, out.width, out.height);
2247
+ return out.toDataURL("image/png");
2248
+ }
2249
+ var thumbCount = () => thumbs.size;
2250
+ function visibleModels() {
2251
+ const q = ui.q.trim().toLowerCase();
2252
+ return S.snap.models.filter((m) => (!ui.projects.size || ui.projects.has(m.project ?? "")) && (!q || (m.id + " " + m.file.path + " " + m.styleId).toLowerCase().includes(q)));
2253
+ }
2254
+ function modelCard(model) {
2255
+ const c = el("button", "card model-card" + (ui.model === model.id ? " active" : ""));
2256
+ c.type = "button";
2257
+ c.dataset.key = model.id;
2258
+ c.setAttribute("aria-label", "3D model " + model.name + (model.edit ? ", edited" : ""));
2259
+ const cell = el("div", "cell");
2260
+ const thumbUrl = thumbFor(model);
2261
+ if (thumbUrl) {
2262
+ const img = el("img", "model-thumb");
2263
+ img.src = thumbUrl;
2264
+ img.alt = model.name;
2265
+ cell.append(img);
2266
+ }
2267
+ const glyph = el("div", "model-glyph");
2268
+ if (thumbUrl) glyph.hidden = true;
2269
+ glyph.append(el("b", null, ".glb"));
2270
+ if (model.summary) {
2271
+ const tris = model.summary.meshes.reduce((sum, mesh) => sum + mesh.triangles, 0);
2272
+ glyph.append(el("span", null, model.summary.meshes.length + (model.summary.meshes.length === 1 ? " mesh" : " meshes") + " · " + tris.toLocaleString() + " triangles"));
2273
+ if (model.summary.animations.length) glyph.append(el("span", null, model.summary.animations.length + (model.summary.animations.length === 1 ? " animation" : " animations")));
2274
+ } else glyph.append(el("span", null, "could not be read"));
2275
+ cell.append(glyph, el("span", "badge", "3D"));
2276
+ if (model.edit) {
2277
+ const pen = el("span", "pen", "✎");
2278
+ pen.title = "has an edited copy";
2279
+ cell.append(pen);
2280
+ }
2281
+ const body = el("div", "cbody");
2282
+ body.append(el("div", "aid", model.name));
2283
+ const meta = el("div", "cmeta");
2284
+ meta.append(el("span", null, model.styleId), el("span", null, fmtBytes(model.file.bytes)));
2285
+ body.append(meta);
2286
+ c.append(cell, body);
2287
+ c.onclick = () => openModel(model.id);
2288
+ return c;
2289
+ }
2290
+ function modelSections() {
2291
+ const models = visibleModels();
2292
+ if (!models.length) return [];
2293
+ const projects = [...new Set(models.map((m) => m.project))];
2294
+ return projects.map((project) => {
2295
+ const mine = models.filter((m) => m.project === project);
2296
+ const wrap = el("section", "style models");
2297
+ const head = el("div", "shead");
2298
+ head.append(el("h2", null, (project ? project + " · " : "") + "3D models"));
2299
+ const meta = el("div", "meta");
2300
+ meta.append(
2301
+ el("span", null, mine.length + (mine.length === 1 ? " model" : " models")),
2302
+ el("span", null, ".glb files under the styles’ output folders; not manifest assets, so they have no plan state or cost")
2303
+ );
2304
+ head.append(meta);
2305
+ const grid = el("div", "grid");
2306
+ for (const model of mine) grid.append(modelCard(model));
2307
+ wrap.append(head, grid);
2308
+ return wrap;
2309
+ });
2310
+ }
2311
+ function openModel(id) {
2312
+ ui.open = null;
2313
+ ui.editing = null;
2314
+ if (ui.model !== id) {
2315
+ ui.notice = null;
2316
+ ui.modelSide = "edited";
2317
+ }
2318
+ ui.model = id;
2319
+ syncHash();
2320
+ markActive(id);
2321
+ $("drawer-host").textContent = "";
2322
+ renderModelDrawer();
2323
+ }
2324
+ function closeModel() {
2325
+ const id = ui.model;
2326
+ ui.model = null;
2327
+ ui.notice = null;
2328
+ syncHash();
2329
+ markActive(null);
2330
+ teardown();
2331
+ const focus = id && document.querySelector('.card[data-key="' + CSS.escape(id) + '"]');
2332
+ if (focus) focus.focus({ preventScroll: true });
2333
+ }
2334
+ function teardown() {
2335
+ if (!live) return;
2336
+ live.viewer?.dispose();
2337
+ live.drawer.remove();
2338
+ live.scrim.remove();
2339
+ live = null;
2340
+ }
2341
+ var shownFile = (model) => model.edit && ui.modelSide === "edited" ? model.edit : model.file;
2342
+ function renderModelDrawer() {
2343
+ const model = modelOf(ui.model);
2344
+ if (!model) {
2345
+ teardown();
2346
+ if (ui.model) {
2347
+ ui.model = null;
2348
+ syncHash();
2349
+ }
2350
+ return false;
2351
+ }
2352
+ const host = $("drawer-host");
2353
+ if (!live || live.id !== model.id || !live.drawer.isConnected) {
2354
+ teardown();
2355
+ host.textContent = "";
2356
+ const scrim = el("div", "scrim");
2357
+ scrim.onclick = () => closeModel();
2358
+ const drawer = el("aside", "drawer model-drawer");
2359
+ drawer.setAttribute("role", "dialog");
2360
+ drawer.setAttribute("aria-label", model.id);
2361
+ const head = el("div", "dhead");
2362
+ const title = el("div", "title");
2363
+ if (model.project) title.append(el("span", "sid project", model.project), " ");
2364
+ title.append(el("span", "sid", model.styleId), " ", el("span", "sid", "3D model"), el("div", "aid", model.name));
2365
+ const close = el("button", null, "Close");
2366
+ close.type = "button";
2367
+ close.onclick = () => closeModel();
2368
+ const nav = el("div", "nav");
2369
+ nav.append(close);
2370
+ head.append(title, nav);
2371
+ const body = el("div", "dbody");
2372
+ const stage = el("div", "preview model-stage");
2373
+ stage.setAttribute("role", "img");
2374
+ stage.setAttribute("aria-label", "A 3D view of " + model.name + ". Drag to turn it.");
2375
+ const controls = el("div", "model-controls");
2376
+ const info = el("div");
2377
+ body.append(stage, controls, info);
2378
+ drawer.append(head, body);
2379
+ host.append(scrim, drawer);
2380
+ let viewer = null;
2381
+ let error = null;
2382
+ try {
2383
+ viewer = createModelViewer(stage);
2384
+ } catch (err) {
2385
+ error = err.message;
2386
+ }
2387
+ if (!viewer) stage.append(el("div", "none", error ? "This browser could not draw the model: " + error : "This browser has no WebGL2, so the model cannot be drawn here. Its record is below."));
2388
+ live = { id: model.id, drawer, scrim, info, controls, stage, viewer, url: null, doc: null, scene: null, error, loading: false };
2389
+ close.focus({ preventScroll: true });
2390
+ }
2391
+ const state = live;
2392
+ const file = shownFile(model);
2393
+ if (state.viewer && !model.error && state.url !== file.url) {
2394
+ state.url = file.url;
2395
+ state.loading = true;
2396
+ state.error = null;
2397
+ const wanted = file.url;
2398
+ fetchDoc(wanted).then(async (doc) => {
2399
+ if (live !== state || state.url !== wanted) return;
2400
+ const scene = await state.viewer.show(doc);
2401
+ if (live !== state || state.url !== wanted) return;
2402
+ state.doc = doc;
2403
+ state.scene = scene;
2404
+ state.loading = false;
2405
+ renderControls(state);
2406
+ renderInfo(state);
2407
+ }).catch((err) => {
2408
+ if (live !== state || state.url !== wanted) return;
2409
+ state.loading = false;
2410
+ state.error = err.message;
2411
+ renderControls(state);
2412
+ renderInfo(state);
2413
+ });
2414
+ }
2415
+ renderControls(state);
2416
+ renderInfo(state);
2417
+ return true;
2418
+ }
2419
+ function renderControls(state) {
2420
+ const model = modelOf(state.id);
2421
+ const host = state.controls;
2422
+ host.textContent = "";
2423
+ if (!model) return;
2424
+ const viewer = state.viewer;
2425
+ if (state.loading && !state.scene) host.append(el("div", "state-dim", "Loading the model…"));
2426
+ if (state.error) host.append(el("div", "state-bad", "The model could not be drawn: " + state.error));
2427
+ if (!viewer || !state.scene) return;
2428
+ const scene = state.scene;
2429
+ const bar = el("div", "model-row");
2430
+ if (scene.clips.length) {
2431
+ const play = el("button", null, viewer.playing() ? "Pause" : "Play");
2432
+ play.type = "button";
2433
+ play.onclick = () => {
2434
+ viewer.setPlaying(!viewer.playing());
2435
+ renderControls(state);
2436
+ };
2437
+ const pick = el("select");
2438
+ pick.setAttribute("aria-label", "Animation");
2439
+ const none = el("option", null, "rest pose");
2440
+ none.value = "";
2441
+ pick.append(none);
2442
+ for (const name of scene.clips) {
2443
+ const o = el("option", null, name.replaceAll("_", " "));
2444
+ o.value = name;
2445
+ pick.append(o);
2446
+ }
2447
+ pick.value = viewer.clip() ?? "";
2448
+ pick.onchange = () => {
2449
+ viewer.setClip(pick.value || null);
2450
+ };
2451
+ bar.append(play, pick);
2452
+ } else bar.append(el("span", "state-dim", "no animations in this file"));
2453
+ const out = el("button", null, "−");
2454
+ out.type = "button";
2455
+ out.title = "Zoom out";
2456
+ out.setAttribute("aria-label", "Zoom out");
2457
+ out.onclick = () => viewer.zoom(1.25);
2458
+ const zin = el("button", null, "+");
2459
+ zin.type = "button";
2460
+ zin.title = "Zoom in";
2461
+ zin.setAttribute("aria-label", "Zoom in");
2462
+ zin.onclick = () => viewer.zoom(0.8);
2463
+ const reset = el("button", null, "Reset view");
2464
+ reset.type = "button";
2465
+ reset.onclick = () => viewer.resetCamera();
2466
+ bar.append(el("span", "grow"), out, zin, reset);
2467
+ host.append(bar);
2468
+ if (model.edit) {
2469
+ const sides = el("div", "model-row");
2470
+ sides.append(el("span", "lbl", "Showing"));
2471
+ const seg = el("span", "seg");
2472
+ for (const [side, label] of [["edited", "Edited"], ["original", "As built"]]) {
2473
+ const b = el("button", ui.modelSide === side ? "on" : null, label);
2474
+ b.type = "button";
2475
+ b.setAttribute("aria-pressed", String(ui.modelSide === side));
2476
+ b.onclick = () => {
2477
+ ui.modelSide = side;
2478
+ renderModelDrawer();
2479
+ };
2480
+ seg.append(b);
2481
+ }
2482
+ sides.append(seg);
2483
+ host.append(sides);
2484
+ }
2485
+ if (scene.items.length) {
2486
+ const worn = el("div", "model-row");
2487
+ worn.append(el("span", "lbl", "Parts"));
2488
+ for (const item of scene.items) {
2489
+ const on = viewer.itemShown(item);
2490
+ const b = el("button", "chip" + (on ? " on" : ""), item.replaceAll("_", " "));
2491
+ b.type = "button";
2492
+ b.setAttribute("aria-pressed", String(on));
2493
+ b.title = on ? "Hide " + item : "Show " + item;
2494
+ b.onclick = () => {
2495
+ viewer.setItem(item, !viewer.itemShown(item));
2496
+ renderControls(state);
2497
+ };
2498
+ worn.append(b);
2499
+ }
2500
+ host.append(worn);
2501
+ }
2502
+ if (scene.note) host.append(el("div", "state-warn", scene.note));
2503
+ host.append(el("div", "state-dim model-hint", "Drag to turn it."));
2504
+ }
2505
+ var section = (title) => {
2506
+ const s = el("section", "meta");
2507
+ s.append(el("h3", null, title));
2508
+ return s;
2509
+ };
2510
+ async function postModel(model, action, extra = {}) {
2511
+ const body = { action, path: model.file.path, ...extra };
2512
+ if (model.project) body.project = model.project;
2513
+ S.snap = await postEdit(body);
2514
+ }
2515
+ function renderInfo(state) {
2516
+ const model = modelOf(state.id);
2517
+ const host = state.info;
2518
+ host.textContent = "";
2519
+ if (!model) return;
2520
+ if (ui.notice && ui.notice.id === model.id) host.append(el("div", "notice", ui.notice.text));
2521
+ if (model.error) host.append(el("div", "state-bad", "This file could not be read as a model: " + model.error));
2522
+ const images = model.summary?.images ?? [];
2523
+ if (images.length) {
2524
+ const s = section("Textures");
2525
+ const editable = canWrite() && EDITOR && S.ED;
2526
+ if (canWrite() && EDITOR && S.ED && S.ED.installed && S.ED.protocol < 5) {
2527
+ const pickRow = el("label", "model-row");
2528
+ pickRow.append(el("span", "lbl", "Locked layer shows"));
2529
+ const pick = el("select");
2530
+ for (const [value, label] of REFERENCE_CHOICES) {
2531
+ const o = el("option", null, label);
2532
+ o.value = value;
2533
+ pick.append(o);
2534
+ }
2535
+ pick.value = REFERENCE_CHOICES.some(([value]) => value === ui.modelReference) ? ui.modelReference : "guide";
2536
+ pick.onchange = () => {
2537
+ ui.modelReference = pick.value;
2538
+ savePrefs();
2539
+ };
2540
+ pick.title = "What the editor’s locked reference layer carries, at 50%: the guide outlines each piece of the unwrap and names the body part it covers. It is never part of the saved texture.";
2541
+ pickRow.append(pick);
2542
+ s.append(pickRow);
2543
+ }
2544
+ const list = el("div", "model-textures");
2545
+ for (const image of images) {
2546
+ const paintable = (image.roles.includes("baseColor") || image.roles.includes("normal")) && image.embedded && image.width && image.height;
2547
+ const isNormal = !image.roles.includes("baseColor") && image.roles.includes("normal");
2548
+ const entry = el("div", "model-texture");
2549
+ const thumb2 = el("canvas");
2550
+ thumb2.width = 72;
2551
+ thumb2.height = 72;
2552
+ const bitmap = state.viewer?.image(image.index);
2553
+ if (bitmap) thumb2.getContext("2d").drawImage(bitmap, 0, 0, 72, 72);
2554
+ const text = el("div", "tx");
2555
+ const role = image.roles.map((r) => r === "baseColor" ? "base colour" : r === "normal" ? "normal map" : r).join(", ") || "not used by a material";
2556
+ text.append(el("b", null, (image.materials.join(", ") || "image " + image.index) + " · " + role));
2557
+ const guide = paintable && state.doc ? guideFor(state.doc, image.index) : null;
2558
+ text.append(el("span", null, (image.width ? image.width + "×" + image.height : "size unknown") + " · " + (image.mimeType || "unknown type").replace("image/", "") + " · " + fmtBytes(image.bytes) + (guide ? " · " + guide.pieces.length + (guide.pieces.length === 1 ? " piece over " : " pieces over ") + guide.regions.length + (guide.regions.length === 1 ? " region" : " regions") : "")));
2559
+ if (image.meshes.length) text.append(el("span", null, "on " + image.meshes.join(", ")));
2560
+ const edited = model.edit?.textures.find((t) => t.image === image.index);
2561
+ if (edited) text.append(el("span", "state-ok", "painted in " + edited.editor + ", " + fmtWhen(edited.savedAt) + (edited.project ? " · layers kept" : "")));
2562
+ entry.append(thumb2, text);
2563
+ if (paintable && editable) {
2564
+ const acts = el("div", "acts");
2565
+ if (S.ED.installed) {
2566
+ const b = el("button", isNormal ? null : "primary", isNormal ? "Edit normal map in browser" : "Edit texture in browser");
2567
+ b.type = "button";
2568
+ b.title = "Open this texture in Pixelorama here; Save writes an edited copy of the model under edits/";
2569
+ b.onclick = () => openTextureSheet(model, image.index);
2570
+ acts.append(b);
2571
+ } else if (S.ED.release && !S.ED.installing) {
2572
+ const b = el("button", null, "Install editor to paint");
2573
+ b.type = "button";
2574
+ b.onclick = () => {
2575
+ installEditor();
2576
+ window.scrollTo({ top: 0 });
2577
+ };
2578
+ acts.append(b);
2579
+ }
2580
+ entry.append(acts);
2581
+ }
2582
+ list.append(entry);
2583
+ }
2584
+ s.append(list);
2585
+ if (!canWrite()) s.append(el("div", "state-dim readonly-hint", "Start the gallery with --edit to paint a texture here or open the model in Blender."));
2586
+ host.append(s);
2587
+ }
2588
+ {
2589
+ const s = section("Edited copy");
2590
+ const dl = el("dl");
2591
+ if (model.edit) {
2592
+ const [tone, why] = EDIT_STATUS[model.edit.status];
2593
+ const st = el("span", "state-" + tone);
2594
+ st.append(el("i", "dot " + tone), document.createTextNode(" " + model.edit.status));
2595
+ row(dl, "status", st);
2596
+ row(dl, "why", why + (model.edit.changedSince ? " The file changed on disk after its record was written." : ""));
2597
+ row(dl, "file", model.edit.path, { mono: true, copy: model.edit.absolutePath });
2598
+ row(dl, "size", fmtBytes(model.edit.bytes));
2599
+ row(dl, "sha256", model.edit.sha256.slice(0, 16) + "…", { mono: true, copy: model.edit.sha256 });
2600
+ if (model.edit.editor) row(dl, "saved", model.edit.editor + ", " + fmtWhen(model.edit.savedAt));
2601
+ } else {
2602
+ s.append(el("div", "state-dim", "None yet. Painting a texture, or adopting an export from Blender, writes a copy of the model to " + model.editPath + "; the model as built stays as it is."));
2603
+ }
2604
+ row(dl, "export to", model.exportPath, { mono: true, copy: model.exportAbsolutePath });
2605
+ s.append(dl);
2606
+ if (canWrite()) {
2607
+ const acts = el("div", "hand-actions");
2608
+ const msg = el("span", "msg");
2609
+ const act = (label, primary, title, run) => {
2610
+ const b = el("button", primary ? "primary" : null, label);
2611
+ b.type = "button";
2612
+ b.title = title;
2613
+ b.onclick = async () => {
2614
+ b.disabled = true;
2615
+ msg.className = "msg";
2616
+ msg.textContent = "…";
2617
+ try {
2618
+ const done = await run();
2619
+ ui.notice = { id: model.id, text: done };
2620
+ render();
2621
+ } catch (err) {
2622
+ b.disabled = false;
2623
+ msg.className = "msg bad";
2624
+ msg.textContent = err.message;
2625
+ }
2626
+ };
2627
+ acts.append(b);
2628
+ return b;
2629
+ };
2630
+ const blender = act(
2631
+ "Open in Blender",
2632
+ false,
2633
+ "Start Blender with this model imported and File > Export > PixelKiln edit (.glb) added",
2634
+ async () => {
2635
+ await postModel(model, "open-model");
2636
+ return "Started Blender on " + (model.edit ? model.edit.path : model.file.path) + ". Paint there, then use File > Export > PixelKiln edit (.glb) and press Refresh here.";
2637
+ }
2638
+ );
2639
+ if (!S.snap.tools.blender) {
2640
+ blender.disabled = true;
2641
+ blender.title = "Blender was not found in its usual place. Set PIXELKILN_BLENDER to the program and start the gallery again.";
2642
+ }
2643
+ if (model.exportWaiting) {
2644
+ act(
2645
+ "Adopt the export’s textures",
2646
+ true,
2647
+ "Take the base colour textures from " + model.exportPath + " into a copy of the model as built; meshes, normal maps, and animations stay exactly as built",
2648
+ async () => {
2649
+ await postModel(model, "adopt-model-export", { mode: "textures" });
2650
+ ui.modelSide = "edited";
2651
+ return "Adopted the exported textures into " + model.editPath + ".";
2652
+ }
2653
+ );
2654
+ act(
2655
+ "Adopt the whole file",
2656
+ false,
2657
+ "Use " + model.exportPath + " as the edit exactly as exported",
2658
+ async () => {
2659
+ await postModel(model, "adopt-model-export", { mode: "whole" });
2660
+ ui.modelSide = "edited";
2661
+ return "Adopted the exported file as " + model.editPath + ".";
2662
+ }
2663
+ );
2664
+ }
2665
+ acts.append(msg);
2666
+ s.append(acts);
2667
+ if (model.exportWaiting) s.append(el("div", "state-cool", "An export is waiting at " + model.exportPath + " (" + fmtBytes(model.exportWaiting.bytes) + ", " + fmtWhen(model.exportWaiting.modifiedAt) + ")."));
2668
+ else if (!S.snap.tools.blender) s.append(el("div", "state-dim", "Blender was not found on this machine. Set PIXELKILN_BLENDER to start it from here, or export a .glb to the path above from any program and Refresh."));
2669
+ }
2670
+ host.append(s);
2671
+ }
2672
+ const normalImages = images.filter((image) => !image.roles.includes("baseColor") && image.roles.includes("normal") && image.width && image.height);
2673
+ if (canWrite() && normalImages.length) host.append(normalDetailSection(model, normalImages));
2674
+ {
2675
+ const s = section("Model");
2676
+ const dl = el("dl");
2677
+ row(dl, "file", model.file.path, { mono: true, copy: model.file.absolutePath });
2678
+ row(dl, "size", fmtBytes(model.file.bytes));
2679
+ row(dl, "sha256", model.file.sha256.slice(0, 16) + "…", { mono: true, copy: model.file.sha256 });
2680
+ row(dl, "modified", fmtWhen(model.file.modifiedAt));
2681
+ if (model.summary) {
2682
+ row(dl, "made by", model.summary.generator);
2683
+ row(dl, "meshes", model.summary.meshes.map((mesh) => mesh.name + " (" + mesh.triangles.toLocaleString() + " triangles)").join(", "));
2684
+ row(dl, "skeleton", model.summary.bones.length ? model.summary.bones.length + " bones: " + model.summary.bones.join(", ") : "none");
2685
+ row(dl, "animations", model.summary.animations.join(", ") || "none");
2686
+ }
2687
+ s.append(dl);
2688
+ host.append(s);
2689
+ }
2690
+ }
2691
+ var NORMAL_MAP_PRICE = 0.1;
2692
+ var DETAIL_VIEWS = 4;
2693
+ function normalDetailSection(model, normals) {
2694
+ const s = section("Normal map detail (PixelLab)");
2695
+ s.append(el("div", "state-dim", "Reads the painted light and dark as small bumps and adds them to " + (normals.length === 1 ? "the normal map" : "the " + normals.length + " normal maps") + ", on top of the relief already baked in. Written to the edited copy; the model as built is not touched."));
2696
+ const controls = el("div", "model-row");
2697
+ const source = el("select");
2698
+ const choices = [["views", "From the figure, drawn from 4 sides"], ["texture", "From each texture, as laid out"]];
2699
+ const spriteCount = model.sprites?.directions.length ?? 0;
2700
+ if (spriteCount) choices.push(["sprites", "From its " + spriteCount + " sprite" + (spriteCount === 1 ? "" : "s") + " in " + model.sprites.path]);
2701
+ for (const [value, label] of choices) {
2702
+ const o = el("option", null, label);
2703
+ o.value = value;
2704
+ source.append(o);
2705
+ }
2706
+ source.title = "From the figure: smooth and consistent across seams, coarser, and parts no side can see stay as they were. From each texture: finer and complete, but pieces of the unwrap can disagree where they meet." + (spriteCount ? " From its sprites: only where a sprite lines up with the model in colour, and only as fine as the sprite; best when the model was built to the sprites' proportions. pixelkiln model normal-map --source sprites --dry-run shows how each one lines up." : "");
2707
+ const amount = el("input");
2708
+ amount.type = "range";
2709
+ amount.min = "0";
2710
+ amount.max = "2";
2711
+ amount.step = "0.25";
2712
+ amount.value = "1";
2713
+ amount.title = "How much of the detail goes on: 1 as PixelLab drew it, 2 twice as deep";
2714
+ const amountLabel = el("span", "lbl", "blend 1");
2715
+ const replaceBox = el("label", "lbl");
2716
+ const replace = el("input");
2717
+ replace.type = "checkbox";
2718
+ replaceBox.append(replace, document.createTextNode(" replace the baked relief"));
2719
+ replaceBox.title = "Write PixelLab’s detail alone, dropping the relief the model was built with";
2720
+ controls.append(source, amountLabel, amount, replaceBox);
2721
+ s.append(controls);
2722
+ const acts = el("div", "hand-actions");
2723
+ const go = el("button", null, "");
2724
+ go.type = "button";
2725
+ const msg = el("span", "msg");
2726
+ const price = () => {
2727
+ const calls = source.value === "views" ? DETAIL_VIEWS : source.value === "sprites" ? spriteCount : normals.reduce((sum, image) => sum + Math.ceil(image.width / 512) * Math.ceil(image.height / 512), 0);
2728
+ return Math.round(calls * NORMAL_MAP_PRICE * 100) / 100;
2729
+ };
2730
+ const refresh2 = () => {
2731
+ amountLabel.textContent = "blend " + amount.value;
2732
+ go.textContent = "Generate · up to " + price() + " generations";
2733
+ go.disabled = !GENERATION;
2734
+ go.title = GENERATION ? "Ask PixelLab, after you confirm the price. Answers already fetched for the same pictures are reused for free." : "Start the gallery with --edit --budget <n> to spend PixelLab generations from here, or run pixelkiln model normal-map";
2735
+ };
2736
+ source.onchange = refresh2;
2737
+ amount.oninput = refresh2;
2738
+ go.onclick = async () => {
2739
+ const cost = price();
2740
+ if (!confirm("Spend up to " + cost + " PixelLab generations on normal map detail for " + model.name + "?")) return;
2741
+ go.disabled = true;
2742
+ msg.className = "msg";
2743
+ msg.textContent = "Asking PixelLab… (about 10 s a picture)";
2744
+ try {
2745
+ await postModel(model, "generate-model-normals", { source: source.value, amount: Number(amount.value), ...replace.checked ? { replace: true } : {}, maxCost: cost });
2746
+ ui.modelSide = "edited";
2747
+ ui.notice = { id: model.id, text: "Added PixelLab’s normal map detail to " + model.editPath + ". Drag the model to turn it in the light; Edited / As built compares." };
2748
+ render();
2749
+ } catch (err) {
2750
+ go.disabled = false;
2751
+ msg.className = "msg bad";
2752
+ msg.textContent = err.message;
2753
+ }
2754
+ };
2755
+ refresh2();
2756
+ acts.append(go, msg);
2757
+ s.append(acts);
2758
+ if (!GENERATION) s.append(el("div", "state-dim", "This gallery spends nothing: start it with --edit --budget <n>, or run pixelkiln model normal-map " + model.name + " in a terminal."));
2759
+ return s;
2760
+ }
2761
+ var guides = /* @__PURE__ */ new WeakMap();
2762
+ function guideFor(doc, image) {
2763
+ let perDoc = guides.get(doc);
2764
+ if (!perDoc) guides.set(doc, perDoc = /* @__PURE__ */ new Map());
2765
+ let guide = perDoc.get(image);
2766
+ if (!guide) {
2767
+ try {
2768
+ guide = uvGuide(doc, image);
2769
+ } catch {
2770
+ guide = { pieces: [], regions: [] };
2771
+ }
2772
+ perDoc.set(image, guide);
2773
+ }
2774
+ return guide;
2775
+ }
2776
+ function drawGuide(ctx, guide, width, height) {
2777
+ const line = Math.max(1, Math.round(width / 512));
2778
+ ctx.lineCap = "round";
2779
+ for (const pass of ["halo", "line"]) {
2780
+ for (const piece of guide.pieces) {
2781
+ ctx.beginPath();
2782
+ for (let at = 0; at < piece.outline.length; at += 4) {
2783
+ ctx.moveTo(piece.outline[at] * width, piece.outline[at + 1] * height);
2784
+ ctx.lineTo(piece.outline[at + 2] * width, piece.outline[at + 3] * height);
2785
+ }
2786
+ ctx.lineWidth = pass === "halo" ? line + 2 : line;
2787
+ ctx.strokeStyle = pass === "halo" ? "rgba(0,0,0,.85)" : regionColour(guide.regions.indexOf(piece.region));
2788
+ ctx.stroke();
2789
+ }
2790
+ }
2791
+ const size = Math.max(9, Math.min(18, Math.round(width / 56)));
2792
+ ctx.font = "600 " + size + "px ui-sans-serif, system-ui, sans-serif";
2793
+ ctx.textAlign = "center";
2794
+ ctx.textBaseline = "middle";
2795
+ ctx.lineJoin = "round";
2796
+ for (const piece of guide.pieces) {
2797
+ const boxW = (piece.bounds[2] - piece.bounds[0]) * width, boxH = (piece.bounds[3] - piece.bounds[1]) * height;
2798
+ const number = String(guide.regions.indexOf(piece.region) + 1);
2799
+ const candidates = [pieceLabel(piece), piece.region, number];
2800
+ const text = candidates.find((candidate) => ctx.measureText(candidate).width + 6 <= boxW && size + 4 <= boxH);
2801
+ if (!text) continue;
2802
+ const half = ctx.measureText(text).width / 2 + 2;
2803
+ const x = Math.max(half, Math.min(width - half, piece.anchor[0] * width));
2804
+ const y = Math.max(size / 2 + 1, Math.min(height - size / 2 - 1, piece.anchor[1] * height));
2805
+ ctx.lineWidth = 3;
2806
+ ctx.strokeStyle = "rgba(0,0,0,.9)";
2807
+ ctx.strokeText(text, x, y);
2808
+ ctx.fillStyle = "#fff";
2809
+ ctx.fillText(text, x, y);
2810
+ }
2811
+ }
2812
+ function legend(guide) {
2813
+ const strip = el("div", "model-legend");
2814
+ strip.title = "The guide’s colours and numbers: each piece of the unwrap is outlined in the colour of the body region that moves it";
2815
+ guide.regions.forEach((region, index) => {
2816
+ const item = el("span");
2817
+ const swatch = el("i");
2818
+ swatch.style.background = regionColour(index);
2819
+ item.append(swatch, document.createTextNode(index + 1 + " " + region));
2820
+ strip.append(item);
2821
+ });
2822
+ return strip;
2823
+ }
2824
+ var canvasPng = (canvas) => new Promise((resolve, reject) => {
2825
+ canvas.toBlob((blob) => blob ? blob.arrayBuffer().then(resolve, reject) : reject(new Error("the browser could not encode the image")), "image/png");
2826
+ });
2827
+ async function decode(doc, image) {
2828
+ const { bytes, mimeType } = glbImageBytes(doc, image);
2829
+ return createImageBitmap(new Blob([bytes.slice()], { type: mimeType || "image/png" }), { premultiplyAlpha: "none", colorSpaceConversion: "none" });
2830
+ }
2831
+ function openTextureSheet(model, image) {
2832
+ const summary = model.summary.images[image];
2833
+ const name = summary.materials[0] || "image " + image;
2834
+ const isNormal = !summary.roles.includes("baseColor") && summary.roles.includes("normal");
2835
+ const what = name + (isNormal ? " normal map" : " texture");
2836
+ const choice = REFERENCE_CHOICES.some(([value]) => value === ui.modelReference) ? ui.modelReference : "guide";
2837
+ const current = model.edit ?? model.file;
2838
+ const strip = el("div", "model-legend-host");
2839
+ const side = el("div", "sheet-side model-side");
2840
+ const sideStage = el("div", "model-side-stage");
2841
+ const sideBar = el("div", "model-row");
2842
+ const sideNote = el("div", "state-dim model-hint", "Loading the model…");
2843
+ side.append(sideStage, sideBar, sideNote);
2844
+ let viewer = null;
2845
+ let updates = 0;
2846
+ const sideControls = (scene) => {
2847
+ sideBar.textContent = "";
2848
+ if (!viewer) return;
2849
+ const v = viewer;
2850
+ if (scene.clips.length) {
2851
+ const play = el("button", null, v.playing() ? "Pause" : "Play");
2852
+ play.type = "button";
2853
+ play.onclick = () => {
2854
+ v.setPlaying(!v.playing());
2855
+ play.textContent = v.playing() ? "Pause" : "Play";
2856
+ };
2857
+ const pick = el("select");
2858
+ pick.setAttribute("aria-label", "Animation");
2859
+ const none = el("option", null, "rest pose");
2860
+ none.value = "";
2861
+ pick.append(none);
2862
+ for (const n of scene.clips) {
2863
+ const o = el("option", null, n.replaceAll("_", " "));
2864
+ o.value = n;
2865
+ pick.append(o);
2866
+ }
2867
+ pick.value = v.clip() ?? "";
2868
+ pick.onchange = () => v.setClip(pick.value || null);
2869
+ sideBar.append(play, pick);
2870
+ }
2871
+ for (const item of scene.items) {
2872
+ const b = el("button", "chip" + (v.itemShown(item) ? " on" : ""), item.replaceAll("_", " "));
2873
+ b.type = "button";
2874
+ b.onclick = () => {
2875
+ v.setItem(item, !v.itemShown(item));
2876
+ b.classList.toggle("on", v.itemShown(item));
2877
+ };
2878
+ sideBar.append(b);
2879
+ }
2880
+ };
2881
+ const custom = {
2882
+ title: (model.project ? model.project + ":" : "") + model.name + " · " + what + " · " + summary.width + "×" + summary.height,
2883
+ referenceLabel: S.ED.protocol >= 5 ? "show as built" : choice === "original" ? "show the texture as built" : choice === "guide" ? "show the guide" : "show the guide and the texture as built",
2884
+ layers: [{ name: GUIDE_LAYER, label: "show the guide", title: "The unwrap guide on its own locked layer: outlines and names of each piece. Never part of the saved texture." }],
2885
+ referenceTitle: "A locked layer at 50%, for finding your way; never part of the saved texture",
2886
+ below: S.ED.protocol >= 5 || choice === "guide" || choice === "guide+original" ? strip : null,
2887
+ side: {
2888
+ element: side,
2889
+ label: "3D view",
2890
+ shown: () => ui.side3d,
2891
+ setShown: (on) => {
2892
+ ui.side3d = on;
2893
+ savePrefs();
2894
+ }
2895
+ },
2896
+ async live(png) {
2897
+ if (!viewer) return;
2898
+ const bitmap = await createImageBitmap(new Blob([png], { type: "image/png" }), { premultiplyAlpha: "none", colorSpaceConversion: "none" });
2899
+ viewer.setImage(image, bitmap);
2900
+ bitmap.close();
2901
+ updates++;
2902
+ if (S.SHEET) S.SHEET.liveUpdates = updates;
2903
+ sideNote.textContent = "Drag to turn it. Follows the canvas as you paint (" + updates + (updates === 1 ? " update" : " updates") + "); nothing is written until you save.";
2904
+ },
2905
+ async open() {
2906
+ const sheet = S.SHEET;
2907
+ const [doc, original] = await Promise.all([fetchDoc(current.url), fetchDoc(model.file.url)]);
2908
+ try {
2909
+ viewer = createModelViewer(sideStage);
2910
+ } catch {
2911
+ viewer = null;
2912
+ }
2913
+ if (viewer) {
2914
+ viewer.show(doc).then((scene) => {
2915
+ sideControls(scene);
2916
+ sideNote.textContent = "Drag to turn it. Follows the canvas as you paint; nothing is written until you save.";
2917
+ });
2918
+ } else sideNote.textContent = "This browser has no WebGL2, so the model cannot be drawn here.";
2919
+ const width = summary.width, height = summary.height;
2920
+ const paint = el("canvas");
2921
+ paint.width = width;
2922
+ paint.height = height;
2923
+ const bitmap = await decode(doc, image);
2924
+ if (bitmap.width !== width || bitmap.height !== height) throw new Error("the edit’s texture is " + bitmap.width + "×" + bitmap.height + "; the model’s is " + width + "×" + height);
2925
+ paint.getContext("2d").drawImage(bitmap, 0, 0);
2926
+ bitmap.close();
2927
+ const png = await canvasPng(paint);
2928
+ let reference = null;
2929
+ let guidePng = null;
2930
+ if (sheet.ready.version >= 5) {
2931
+ const built = el("canvas");
2932
+ built.width = width;
2933
+ built.height = height;
2934
+ const source = await decode(original, image);
2935
+ built.getContext("2d").drawImage(source, 0, 0, width, height);
2936
+ source.close();
2937
+ reference = await canvasPng(built);
2938
+ const layer = el("canvas");
2939
+ layer.width = width;
2940
+ layer.height = height;
2941
+ const guide = guideFor(doc, image);
2942
+ drawGuide(layer.getContext("2d"), guide, width, height);
2943
+ strip.textContent = "";
2944
+ strip.append(legend(guide));
2945
+ guidePng = await canvasPng(layer);
2946
+ } else if (choice !== "none" && sheet.ready.version >= 4) {
2947
+ const layer = el("canvas");
2948
+ layer.width = width;
2949
+ layer.height = height;
2950
+ const ctx = layer.getContext("2d");
2951
+ if (choice !== "guide") {
2952
+ const built = await decode(original, image);
2953
+ ctx.drawImage(built, 0, 0, width, height);
2954
+ built.close();
2955
+ }
2956
+ if (choice !== "original") {
2957
+ const guide = guideFor(doc, image);
2958
+ drawGuide(ctx, guide, width, height);
2959
+ strip.textContent = "";
2960
+ strip.append(legend(guide));
2961
+ }
2962
+ reference = await canvasPng(layer);
2963
+ }
2964
+ let pxo = null;
2965
+ const kept = model.edit?.textures.find((t) => t.image === image);
2966
+ if (kept?.projectUrl) {
2967
+ const res = await fetch(kept.projectUrl, { cache: "no-store" });
2968
+ if (res.ok) pxo = await res.arrayBuffer();
2969
+ }
2970
+ if (S.SHEET !== sheet) return;
2971
+ const request = "open-" + ++sheet.requests;
2972
+ sheet.sentProject = !!pxo;
2973
+ const message = {
2974
+ type: "pixelkiln:open",
2975
+ request,
2976
+ asset: { key: model.id + "#image-" + image, id: model.id, name: (model.name + "-" + name).replace(/[^A-Za-z0-9._-]+/g, "-"), width, height },
2977
+ // A normal map is painted in directions, not colours: flat, and leaning 45° each way (OpenGL, green up).
2978
+ png,
2979
+ palette: isNormal ? ["#8080ff", "#da80da", "#2580da", "#80dada", "#8025da"] : []
2980
+ };
2981
+ const transfer = [png];
2982
+ if (pxo) {
2983
+ message.pxo = pxo;
2984
+ transfer.push(pxo);
2985
+ }
2986
+ if (reference) {
2987
+ message.reference = [{ role: null, png: reference }];
2988
+ transfer.push(reference);
2989
+ }
2990
+ if (guidePng) {
2991
+ message.guides = [{ name: GUIDE_LAYER, png: guidePng, opacity: 1 }];
2992
+ transfer.push(guidePng);
2993
+ }
2994
+ sheet.sentReference = !!reference;
2995
+ sheet.frame.contentWindow.postMessage(message, location.origin, transfer);
2996
+ sheet.status.textContent = "";
2997
+ sheet.status.append(el("i", "dot cool"), document.createTextNode("opening"));
2998
+ },
2999
+ opened(m) {
3000
+ const from = m.source === "pxo" ? "painting the " + what + " with " + (m.layers === 1 ? "its layer" : "its " + m.layers + " layers") + " restored" : S.SHEET.sentProject ? "painting the flattened " + what + "; its layer file could not be opened" : model.edit ? "painting the " + what + " of the edited copy" : "painting a copy of the " + what;
3001
+ if (Array.isArray(m.guides) && m.guides.includes(GUIDE_LAYER)) return from + " · guide on its own layer, texture as built at 50% under it";
3002
+ return from + (m.reference ? " · " + (choice === "original" ? "texture as built" : "guide") + " shown through at 50%" : "");
3003
+ },
3004
+ async save(m) {
3005
+ const body = { image, png: await toBase64(m.png), editor: S.SHEET.ready.editor, protocol: S.SHEET.ready.version };
3006
+ if (m.pxo && m.pxo.byteLength) body.pxo = await toBase64(m.pxo);
3007
+ await postModel(model, "save-model-texture", body);
3008
+ ui.modelSide = "edited";
3009
+ const saved = modelOf(model.id);
3010
+ ui.notice = { id: model.id, text: "Saved the " + what + " into " + (saved?.edit?.path ?? model.editPath) + ". The model as built is unchanged." };
3011
+ }
3012
+ };
3013
+ openEditorSheet(model, custom);
3014
+ }
3015
+
663
3016
  // src/gallery/client/src/mask-editor.ts
664
3017
  var HISTORY = 50;
665
3018
  var SCALE_BOX = 320;
@@ -2449,6 +4802,10 @@
2449
4802
  const root = $("root");
2450
4803
  root.textContent = "";
2451
4804
  pruneLoops();
4805
+ if (!S.snap.items.length && S.snap.models.length) {
4806
+ root.append(...modelSections());
4807
+ return;
4808
+ }
2452
4809
  if (!S.snap.items.length) {
2453
4810
  const e = el("div", "empty");
2454
4811
  e.append(el("p", null, "Nothing has been generated for this project yet."));
@@ -2463,7 +4820,7 @@
2463
4820
  b.type = "button";
2464
4821
  b.onclick = clearFilters;
2465
4822
  e.append(b);
2466
- root.append(e);
4823
+ root.append(e, ...modelSections());
2467
4824
  return;
2468
4825
  }
2469
4826
  const hidden = Math.max(0, items.length - ui.limit);
@@ -2518,876 +4875,519 @@
2518
4875
  if (s.outDir && s.candidates !== null) tools.append(candidatesControl(s));
2519
4876
  if (GENERATION && s.actionable.keys.length) {
2520
4877
  const g = el("button", "primary", "Generate " + s.actionable.keys.length + " · " + fmtCost(s.actionable.costUnit, Math.round(s.actionable.cost * 100) / 100));
2521
- g.type = "button";
2522
- g.onclick = () => generateDialog(S.snap.items.filter((i) => i.project === s.project && s.actionable.keys.includes(i.key)), { project: s.project });
2523
- tools.append(g);
2524
- }
2525
- const refreshable = S.snap.items.filter((i) => i.project === s.project && i.styleId === s.id && i.refreshable && i.upstreamUrl);
2526
- if (GENERATION && refreshable.length) {
2527
- const r = el("button", null, "Pull upstream " + refreshable.length);
2528
- r.type = "button";
2529
- r.title = "Re-download objects edited in the provider’s own editor; no cost";
2530
- r.onclick = () => generateDialog(refreshable, { project: s.project, refresh: true });
2531
- tools.append(r);
2532
- }
2533
- if (ui.selecting && ui.group !== "family") tools.append(selectAllButton(sec.items));
2534
- const styleKey = "style:" + (s.project || "") + ":" + s.id;
2535
- if (EDITABLE && s.outDir) {
2536
- const es = el("button", null, ui.editing === styleKey ? "Cancel" : "Edit style");
2537
- es.type = "button";
2538
- es.onclick = () => {
2539
- ui.editing = ui.editing === styleKey ? null : styleKey;
2540
- ui.notice = null;
2541
- render();
2542
- };
2543
- tools.append(es);
2544
- const add = el("button", "add", ui.editing === addKey ? "Cancel" : "+ Add asset");
2545
- add.type = "button";
2546
- add.onclick = () => {
2547
- ui.editing = ui.editing === addKey ? null : addKey;
2548
- render();
2549
- };
2550
- tools.append(add);
2551
- }
2552
- if (tools.childNodes.length) head.append(tools);
2553
- wrap.append(head);
2554
- if (ui.notice && ui.notice.id === styleKey) wrap.append(el("div", "notice", ui.notice.text));
2555
- if (ui.editing === styleKey) wrap.append(styleForm(s));
2556
- if (ui.editing === addKey) wrap.append(addAssetForm(s));
2557
- }
2558
- if (ui.group === "family") wrap.append(...familyGroups(sec.items));
2559
- else {
2560
- const grid = el("div", "grid");
2561
- for (const item of sec.items) grid.append(card(item));
2562
- wrap.append(grid);
2563
- }
2564
- root.append(wrap);
2565
- }
2566
- if (hidden) {
2567
- const more = el("div", "empty");
2568
- more.append(el("p", null, hidden + " more " + (hidden === 1 ? "generation is" : "generations are") + " not shown."));
2569
- const b = el("button", null, "Show all " + items.length);
2570
- b.type = "button";
2571
- b.onclick = () => {
2572
- ui.limit = Infinity;
2573
- render();
2574
- };
2575
- more.append(b);
2576
- root.append(more);
2577
- }
2578
- }
2579
- var KIND_ORDER = { base: 0, state: 1, animation: 2, portrait: 3, outfit: 4 };
2580
- var TURN = ["south", "south-east", "east", "north-east", "north", "north-west", "west", "south-west"];
2581
- function familyOrder(a, b) {
2582
- const ka = KIND_ORDER[a.character.kind] ?? 9, kb = KIND_ORDER[b.character.kind] ?? 9;
2583
- if (ka !== kb) return ka - kb;
2584
- if (a.character.kind === "animation") {
2585
- const la = loopName(a), lb = loopName(b);
2586
- if (la !== lb) return la < lb ? -1 : 1;
2587
- return TURN.indexOf(a.character.direction) - TURN.indexOf(b.character.direction);
2588
- }
2589
- return a.assetId < b.assetId ? -1 : a.assetId > b.assetId ? 1 : 0;
2590
- }
2591
- function familyGroups(items) {
2592
- const families = /* @__PURE__ */ new Map();
2593
- const loose = [];
2594
- for (const item of items) {
2595
- const root = item.character ? familyRoot(item) : null;
2596
- if (!root) {
2597
- loose.push(item);
2598
- continue;
2599
- }
2600
- if (!families.has(root.id)) families.set(root.id, { root, members: [] });
2601
- families.get(root.id).members.push(item);
2602
- }
2603
- const out = [];
2604
- for (const { root, members } of families.values()) {
2605
- members.sort(familyOrder);
2606
- const group = el("div", "fam-group");
2607
- const head = el("div", "fam-head");
2608
- head.append(el("b", "mono", root.assetId));
2609
- const counts = {};
2610
- for (const m of members) counts[m.state] = (counts[m.state] || 0) + 1;
2611
- const tally = el("span", "fam-tally");
2612
- const loops2 = new Set(members.filter((m) => m.character.kind === "animation").map(loopName)).size;
2613
- tally.append(document.createTextNode(members.length + (members.length === 1 ? " asset" : " assets") + (loops2 ? " · " + loops2 + (loops2 === 1 ? " loop" : " loops") : "")));
2614
- for (const [state, n] of Object.entries(counts)) {
2615
- const t = el("span", "st");
2616
- t.append(el("i", "dot " + STATE_TONE[state]), document.createTextNode(n + " " + state));
2617
- tally.append(t);
2618
- }
2619
- head.append(tally);
2620
- const tools = el("div", "tools");
2621
- if (ui.selecting) tools.append(selectAllButton(members));
2622
- const view = el("button", null, "Family view");
2623
- view.type = "button";
2624
- view.onclick = () => openFamily(root);
2625
- tools.append(view);
2626
- const everything = familyMembers(root);
2627
- const todo = everything.filter(actionable);
2628
- if (GENERATION && todo.length) {
2629
- const g = el("button", "primary", "Generate " + todo.length + " · " + priceOf(todo));
2630
- g.type = "button";
2631
- g.title = "One job for the family: parents first, then everything drawn from them";
2632
- g.onclick = () => generateDialog(todo, { project: root.project });
2633
- tools.append(g);
2634
- }
2635
- head.append(tools);
2636
- const grid = el("div", "grid");
2637
- for (const m of members) grid.append(card(m));
2638
- group.append(head, grid);
2639
- out.push(group);
2640
- }
2641
- if (loose.length) {
2642
- const group = el("div", "fam-group loose");
2643
- if (families.size) {
2644
- const head = el("div", "fam-head");
2645
- head.append(el("b", null, "Not in a family"), el("span", "fam-tally", loose.length + (loose.length === 1 ? " asset" : " assets")));
2646
- if (ui.selecting) {
2647
- const tools = el("div", "tools");
2648
- tools.append(selectAllButton(loose));
2649
- head.append(tools);
2650
- }
2651
- group.append(head);
2652
- }
2653
- const grid = el("div", "grid");
2654
- for (const item of loose) grid.append(card(item));
2655
- group.append(grid);
2656
- out.push(group);
2657
- }
2658
- return out;
2659
- }
2660
- var actionable = (item) => item.declared && item.currentSpecHash !== null && ["missing", "stale", "failed"].includes(item.state);
2661
- function priceOf(items) {
2662
- const totals = {};
2663
- for (const i of items) if (i.estimatedCost !== null) totals[i.costUnit] = (totals[i.costUnit] || 0) + i.estimatedCost;
2664
- return Object.entries(totals).map(([unit, n]) => fmtCost(unit, Math.round(n * 100) / 100)).join(" + ") || "free";
2665
- }
2666
- function projectHeader(pr, count) {
2667
- const head = el("section", "project");
2668
- const line = el("div", "phead");
2669
- line.append(el("h2", null, pr.id));
2670
- const meta = el("div", "meta");
2671
- if (pr.name !== pr.id) meta.append(el("span", null, pr.name));
2672
- meta.append(el("span", "mono", shortPath(pr.manifest)));
2673
- if (pr.account) meta.append(el("span", null, pr.account));
2674
- if (pr.error) {
2675
- meta.append(el("span", "state-bad", "unreadable: " + pr.error));
2676
- } else {
2677
- meta.append(el("span", null, count + " of " + pr.items + " shown · " + pr.entries + " lock " + (pr.entries === 1 ? "entry" : "entries")));
2678
- if (Object.keys(pr.spendByUnit).length) meta.append(el("span", null, fmtSpend(pr.spendByUnit)));
2679
- }
2680
- line.append(meta);
2681
- head.append(line);
2682
- return head;
2683
- }
2684
- function candidatesControl(style) {
2685
- const wrap = el("span", "cand");
2686
- const editKey = "cand:" + (style.project || "") + ":" + style.id;
2687
- const declared = S.snap.items.filter((i) => i.project === style.project && i.styleId === style.id && i.declared).length;
2688
- if (!(EDITABLE && style.candidatesEditable) || ui.editing !== editKey) {
2689
- wrap.append(el("span", null, style.candidates + (style.candidates === 1 ? " candidate" : " candidates") + " per generation"));
2690
- if (EDITABLE && style.candidatesEditable) {
2691
- const b = el("button", null, "change");
2692
- b.type = "button";
2693
- b.onclick = () => {
2694
- ui.editing = editKey;
2695
- render();
2696
- };
2697
- wrap.append(b);
2698
- } else if (style.provider === "pixellab") {
2699
- wrap.title = "PixelLab: map and pixflux return one image per generation; a 1dir style returns 4–64 for its size.";
2700
- }
2701
- return wrap;
2702
- }
2703
- const input = el("input");
2704
- input.type = "number";
2705
- input.min = "1";
2706
- input.max = "64";
2707
- input.value = String(style.candidates);
2708
- const save = el("button", "primary", "Save");
2709
- save.type = "button";
2710
- const cancel = el("button", null, "Cancel");
2711
- cancel.type = "button";
2712
- cancel.onclick = () => {
2713
- ui.editing = null;
2714
- render();
2715
- };
2716
- const note = el("span", null, "affects " + declared + (declared === 1 ? " asset, which becomes stale" : " assets, which become stale"));
2717
- save.onclick = async () => {
2718
- save.disabled = true;
2719
- try {
2720
- const pr = S.snap.workspace ? S.snap.workspace.projects.find((x) => x.id === style.project) : S.snap.project;
2721
- const body = { action: "patch-style", styleId: style.id, expectedSha256: pr.manifestSha256, patch: { candidates: Number(input.value) } };
2722
- if (style.project) body.project = style.project;
2723
- S.snap = await postEdit(body);
2724
- ui.editing = null;
2725
- render();
2726
- } catch (err) {
2727
- save.disabled = false;
2728
- note.textContent = err.message;
2729
- note.className = "state-bad";
2730
- }
2731
- };
2732
- wrap.append(input, save, cancel, note);
2733
- setTimeout(() => input.focus(), 0);
2734
- return wrap;
2735
- }
2736
- function historySection(item) {
2737
- const limit = projectOf(item)?.historyLimit;
2738
- if (!item.history.length && !((limit ?? 0) > 0 && item.status === "downloaded")) return null;
2739
- const s = el("section", "meta");
2740
- s.append(el("h3", null, item.history.length ? "Previous generations (" + item.history.length + ")" : "Previous generations"));
2741
- if (!item.history.length) {
2742
- s.append(el("div", "state-dim", "None yet. A regeneration keeps the generation it replaces, up to " + limit + " per asset (PIXELKILN_HISTORY, or the manifest’s history), so it can be brought back from here."));
2743
- return s;
2744
- }
2745
- const list = el("div", "versions");
2746
- const job = GENERATION ? activeJobFor(item) : null;
2747
- for (const g of item.history) {
2748
- const v = el("div", "version");
2749
- const thumb2 = el("div", "thumb");
2750
- const first = g.outputs[0];
2751
- if (first && first.url) {
2752
- const img = el("img");
2753
- img.src = first.url;
2754
- img.alt = "generation #" + g.index;
2755
- thumb2.append(img);
2756
- } else thumb2.append(el("span", null, g.cached ? "" : "not cached"));
2757
- const facts = el("div", "facts");
2758
- const head = el("div");
2759
- const billedNote = g.billed && (g.billed.unit !== g.costUnit || g.billed.amount !== g.cost) ? " (billed " + fmtCost(g.billed.unit, g.billed.amount) + ")" : "";
2760
- head.append(el("b", null, "#" + g.index), document.createTextNode(" · " + fmtWhen(g.downloadedAt || g.submittedAt) + " · " + fmtCost(g.costUnit, g.cost) + billedNote + (g.outputs.length > 1 ? " · " + g.outputs.length + " files" : "")));
2761
- facts.append(head);
2762
- const prompt = el("div", "prompt" + (g.promptDiffers ? " differs" : ""), (g.promptDiffers ? "prompt: " : "same prompt: ") + g.prompt);
2763
- prompt.title = g.prompt;
2764
- facts.append(prompt);
2765
- const meta = el("div", "meta");
2766
- meta.append(document.createTextNode((first ? first.sha256.slice(0, 12) + "…" : "") + (g.cached ? " · bytes cached locally" : " · not in the local cache; a restore re-downloads it")));
2767
- if (g.upstreamUrl) {
2768
- const a = el("a", null, "open in " + item.provider + " ↗");
2769
- a.href = g.upstreamUrl;
2770
- a.target = "_blank";
2771
- a.rel = "noopener";
2772
- meta.append(document.createTextNode(" · "), a);
4878
+ g.type = "button";
4879
+ g.onclick = () => generateDialog(S.snap.items.filter((i) => i.project === s.project && s.actionable.keys.includes(i.key)), { project: s.project });
4880
+ tools.append(g);
4881
+ }
4882
+ const refreshable = S.snap.items.filter((i) => i.project === s.project && i.styleId === s.id && i.refreshable && i.upstreamUrl);
4883
+ if (GENERATION && refreshable.length) {
4884
+ const r = el("button", null, "Pull upstream " + refreshable.length);
4885
+ r.type = "button";
4886
+ r.title = "Re-download objects edited in the provider’s own editor; no cost";
4887
+ r.onclick = () => generateDialog(refreshable, { project: s.project, refresh: true });
4888
+ tools.append(r);
4889
+ }
4890
+ if (ui.selecting && ui.group !== "family") tools.append(selectAllButton(sec.items));
4891
+ const styleKey = "style:" + (s.project || "") + ":" + s.id;
4892
+ if (EDITABLE && s.outDir) {
4893
+ const es = el("button", null, ui.editing === styleKey ? "Cancel" : "Edit style");
4894
+ es.type = "button";
4895
+ es.onclick = () => {
4896
+ ui.editing = ui.editing === styleKey ? null : styleKey;
4897
+ ui.notice = null;
4898
+ render();
4899
+ };
4900
+ tools.append(es);
4901
+ const add = el("button", "add", ui.editing === addKey ? "Cancel" : "+ Add asset");
4902
+ add.type = "button";
4903
+ add.onclick = () => {
4904
+ ui.editing = ui.editing === addKey ? null : addKey;
4905
+ render();
4906
+ };
4907
+ tools.append(add);
4908
+ }
4909
+ if (tools.childNodes.length) head.append(tools);
4910
+ wrap.append(head);
4911
+ if (ui.notice && ui.notice.id === styleKey) wrap.append(el("div", "notice", ui.notice.text));
4912
+ if (ui.editing === styleKey) wrap.append(styleForm(s));
4913
+ if (ui.editing === addKey) wrap.append(addAssetForm(s));
2773
4914
  }
2774
- facts.append(meta);
2775
- const acts = el("div", "acts");
2776
- if (GENERATION) {
2777
- const b = el("button", null, "Restore this one · no cost");
2778
- b.type = "button";
2779
- b.disabled = !!job;
2780
- b.title = job ? "Wait for the running job to finish" : "The current generation moves into history; this one becomes current and its bytes are written back";
2781
- b.onclick = () => generateDialog([item], { project: item.project, revert: String(g.index), generation: g });
2782
- acts.append(b);
4915
+ if (ui.group === "family") wrap.append(...familyGroups(sec.items));
4916
+ else {
4917
+ const grid = el("div", "grid");
4918
+ for (const item of sec.items) grid.append(card(item));
4919
+ wrap.append(grid);
2783
4920
  }
2784
- v.append(thumb2, facts, acts);
2785
- list.append(v);
2786
- }
2787
- s.append(list);
2788
- s.append(el("div", "state-dim", "Keeping up to " + limit + " per asset; a restore moves the current generation into this list, so it can be undone the same way." + (GENERATION ? "" : " Restoring needs the gallery started with --budget (any amount; nothing is spent).")));
2789
- return s;
2790
- }
2791
- function upstreamSection(item) {
2792
- if (!item.upstreamUrl && !(GENERATION && item.refreshable)) return null;
2793
- const s = el("section", "meta");
2794
- s.append(el("h3", null, "Upstream"));
2795
- const dl = el("dl");
2796
- if (item.upstreamUrl) {
2797
- const a = el("a", null, "Open in " + item.provider + " ↗");
2798
- a.href = item.upstreamUrl;
2799
- a.target = "_blank";
2800
- a.rel = "noopener";
2801
- const tiles = item.generator === "tiles";
2802
- row(dl, tiles ? "tile set" : "object", a);
2803
- row(dl, "note", item.provider === "pixellab" ? tiles ? "The tile set this generation was chosen from. Edit it there with PixelLab’s editor, then pull the changes back here; the lockfile records the new bytes as this generation." : "The account object this generation came from. Edit it there with PixelLab’s editor, then pull the changes back here; the lockfile records the new bytes as this generation." : "The provider’s page for this object.");
4921
+ root.append(wrap);
2804
4922
  }
2805
- s.append(dl);
2806
- if (GENERATION && item.refreshable) {
2807
- const acts = el("div", "hand-actions");
2808
- const b = el("button", null, "Pull upstream changes · no cost");
4923
+ root.append(...modelSections());
4924
+ if (hidden) {
4925
+ const more = el("div", "empty");
4926
+ more.append(el("p", null, hidden + " more " + (hidden === 1 ? "generation is" : "generations are") + " not shown."));
4927
+ const b = el("button", null, "Show all " + items.length);
2809
4928
  b.type = "button";
2810
- b.onclick = () => generateDialog([item], { project: item.project, refresh: true });
2811
- acts.append(b);
2812
- s.append(acts);
4929
+ b.onclick = () => {
4930
+ ui.limit = Infinity;
4931
+ render();
4932
+ };
4933
+ more.append(b);
4934
+ root.append(more);
2813
4935
  }
2814
- return s;
2815
4936
  }
2816
- function jobStrip(item, job) {
2817
- const strip = el("div", "job-strip");
2818
- const ph = el("span", "ph");
2819
- ph.append(el("i", "dot busy"), document.createTextNode(job.phase));
2820
- const last = el("span", "last", job.messages.length ? job.messages[job.messages.length - 1].trim() : "");
2821
- last.title = job.messages.join("\n");
2822
- const what = el("span", "what", (JOB_VERB[job.mode] || job.mode) + " this asset: " + (PHASE_TEXT[job.phase] || job.phase) + (job.mode === "generate" && job.phase !== "review" ? ". The current file stays until the new result is downloaded." : "."));
2823
- strip.append(ph, last, what);
2824
- const acts = el("div", "acts");
2825
- if (job.phase === "review" && job.review.includes(item.key)) {
2826
- const b = el("button", "primary", "Review candidates");
2827
- b.type = "button";
2828
- b.onclick = () => openReview(job.id);
2829
- acts.append(b);
2830
- }
2831
- const logBtn = el("button", null, ui.logs.has(job.id) ? "Hide log" : "Log");
2832
- logBtn.type = "button";
2833
- logBtn.onclick = () => {
2834
- ui.logs.has(job.id) ? ui.logs.delete(job.id) : ui.logs.add(job.id);
2835
- renderDrawer();
2836
- };
2837
- acts.append(logBtn);
2838
- strip.append(acts);
2839
- if (ui.logs.has(job.id)) {
2840
- const pre = el("pre", null, job.messages.join("\n"));
2841
- pre.style.gridColumn = "1 / -1";
2842
- strip.append(pre);
4937
+ var KIND_ORDER = { base: 0, state: 1, animation: 2, portrait: 3, outfit: 4 };
4938
+ var TURN = ["south", "south-east", "east", "north-east", "north", "north-west", "west", "south-west"];
4939
+ function familyOrder(a, b) {
4940
+ const ka = KIND_ORDER[a.character.kind] ?? 9, kb = KIND_ORDER[b.character.kind] ?? 9;
4941
+ if (ka !== kb) return ka - kb;
4942
+ if (a.character.kind === "animation") {
4943
+ const la = loopName(a), lb = loopName(b);
4944
+ if (la !== lb) return la < lb ? -1 : 1;
4945
+ return TURN.indexOf(a.character.direction) - TURN.indexOf(b.character.direction);
2843
4946
  }
2844
- return strip;
4947
+ return a.assetId < b.assetId ? -1 : a.assetId > b.assetId ? 1 : 0;
2845
4948
  }
2846
- function generateActions(item) {
2847
- const row2 = el("div", "gen");
2848
- if (!GENERATION || !item.declared || item.currentSpecHash === null) return row2;
2849
- const cost = item.estimatedCost === null ? "" : " · " + fmtCost(item.costUnit, item.estimatedCost);
2850
- const add = (label, cls, opts) => {
2851
- const b = el("button", cls, label);
2852
- b.type = "button";
2853
- b.onclick = () => generateDialog([item], { project: item.project, ...opts });
2854
- row2.append(b);
2855
- };
2856
- if (item.state === "missing" || item.state === "stale" || item.state === "failed") add("Generate" + cost, "primary", {});
2857
- else if (item.state === "ok") add("Regenerate" + cost, null, { force: true });
2858
- else if (item.state === "orphaned" && item.outputs.every((o) => o.exists)) {
2859
- add("Restore recorded bytes · no cost", null, { restore: true, force: true });
2860
- add("Regenerate" + cost, null, { force: true });
2861
- } else if (item.state === "orphaned") add("Restore · no cost", "primary", { restore: true });
2862
- else if (item.state === "untracked") add("Generate" + cost + " · replaces the file", null, { force: true });
2863
- if (item.state === "recoverable" && item.status === "downloaded") {
2864
- add(paletteRuleOf(item) ? "Snap to the palette · no cost" : "Put the provider’s bytes back · no cost", "primary", { resume: true });
2865
- } else if (item.state === "in-flight" || item.state === "recoverable") {
2866
- const holder = S.GEN.jobs.find((job) => job.phase === "review" && job.project === item.project && job.review.includes(item.key));
2867
- if (holder) {
2868
- const b = el("button", "primary", "Review candidates");
2869
- b.type = "button";
2870
- b.onclick = () => openReview(holder.id);
2871
- row2.append(b);
2872
- } else {
2873
- add(item.status === "review" ? "Resume review" : "Resume · no cost", "primary", { resume: true });
4949
+ function familyGroups(items) {
4950
+ const families = /* @__PURE__ */ new Map();
4951
+ const loose = [];
4952
+ for (const item of items) {
4953
+ const root = item.character ? familyRoot(item) : null;
4954
+ if (!root) {
4955
+ loose.push(item);
4956
+ continue;
2874
4957
  }
4958
+ if (!families.has(root.id)) families.set(root.id, { root, members: [] });
4959
+ families.get(root.id).members.push(item);
2875
4960
  }
2876
- return row2;
2877
- }
2878
-
2879
- // src/gallery/client/src/jobs.ts
2880
- var ACTIVE_PHASES = /* @__PURE__ */ new Set(["queued", "submitting", "polling", "fetching", "review"]);
2881
- var PHASE_TONE = { queued: "cool", submitting: "cool", polling: "cool", fetching: "cool", review: "warn", done: "ok", failed: "bad" };
2882
- var familyLabel = (item) => {
2883
- const c = item.character;
2884
- if (item.mirrorOfKey) return "mirror of " + item.mirrorOfKey.split("/").slice(1).join("/") + (c && c.direction ? ", " + c.direction : "");
2885
- if (!c || c.kind === "base") return null;
2886
- const parent = c.parentKey ? c.parentKey.split("/").slice(1).join("/") : null;
2887
- if (c.kind === "state") return parent ? "state of " + parent : "state";
2888
- return (parent ? "loop of " + parent : "loop") + (c.direction ? ", " + c.direction : "");
2889
- };
2890
- var paletteRuleOf = (item) => {
2891
- const style = S.snap.styles.find((s) => s.id === item.styleId && s.project === item.project);
2892
- return style && style.enforcePalette && style.palette.length >= 2 ? style.palette : null;
2893
- };
2894
- var isRevisable = (item) => {
2895
- if (item.source) return true;
2896
- if (item.quality) return item.quality.review?.status === "approved" && !!item.quality.check?.current;
2897
- return item.status === "downloaded" && item.state === "ok";
2898
- };
2899
- var activeJobFor = (item) => S.GEN.jobs.find((job) => ACTIVE_PHASES.has(job.phase) && job.project === item.project && job.keys.includes(item.key)) || null;
2900
- var JOB_VERB = { generate: "regenerating", resume: "resuming", refresh: "pulling upstream changes for", restore: "restoring", revert: "bringing back a previous generation of" };
2901
- var PHASE_TEXT = { queued: "queued", submitting: "submitting to the provider", polling: "waiting for the provider to finish", fetching: "downloading the result", review: "candidates are ready to review" };
2902
- var remainingBudget = (provider) => {
2903
- const keyed = S.GEN.budget.byProvider[provider];
2904
- const ceiling = keyed !== void 0 ? keyed : S.GEN.budget.amount;
2905
- return ceiling === void 0 ? null : Math.max(0, ceiling - (S.GEN.spent[provider] || 0));
2906
- };
2907
- async function postGenerate(body) {
2908
- const res = await fetch("/api/generate", {
2909
- method: "POST",
2910
- headers: { "Content-Type": "application/json", "X-Pixelkiln-Session": SESSION ?? "" },
2911
- body: JSON.stringify(body)
2912
- });
2913
- if (!res.ok) {
2914
- const err = new Error(await res.text());
2915
- err.status = res.status;
2916
- throw err;
2917
- }
2918
- return res.json();
2919
- }
2920
- var jobsTimer = null;
2921
- async function pollJobs() {
2922
- if (!GENERATION) return;
2923
- try {
2924
- const res = await fetch("/api/jobs", { cache: "no-store" });
2925
- if (!res.ok) throw new Error(await res.text());
2926
- S.GEN = await res.json();
2927
- } catch (err) {
2928
- $("note").textContent = " Job status unavailable: " + err.message;
2929
- return;
2930
- }
2931
- renderJobs();
2932
- renderHeader();
2933
- let changed = false;
2934
- for (const job of S.GEN.jobs) {
2935
- if (!ACTIVE_PHASES.has(job.phase) && !ui.settled.has(job.id)) {
2936
- ui.settled.add(job.id);
2937
- changed = true;
2938
- notifyJob(job);
2939
- const open = ui.open && S.snap.items.find((i) => i.id === ui.open);
2940
- if (open && job.project === open.project && job.keys.includes(open.key)) {
2941
- ui.notice = { id: open.id, text: job.phase === "failed" ? (JOB_VERB[job.mode] || job.mode).replace(/ing$/, "ing") + " this asset failed: " + (job.error || "see the log above") : job.mode === "generate" ? "Regenerated. The new result is on disk and recorded as this generation." : job.mode === "restore" ? "Restored. The recorded bytes are back on disk." : job.mode === "revert" ? "Brought back generation #" + job.revert + ". The one it replaced is now #1 in the list below." : job.mode === "refresh" ? job.counts.downloaded ? "Pulled the upstream change; the lockfile records the new bytes." : "Nothing changed upstream; the file was left alone." : job.mode === "resume" && job.counts.downloaded ? "Done. The file on disk and the record now match the manifest." : "Done." };
2942
- }
4961
+ const out = [];
4962
+ for (const { root, members } of families.values()) {
4963
+ members.sort(familyOrder);
4964
+ const group = el("div", "fam-group");
4965
+ const head = el("div", "fam-head");
4966
+ head.append(el("b", "mono", root.assetId));
4967
+ const counts = {};
4968
+ for (const m of members) counts[m.state] = (counts[m.state] || 0) + 1;
4969
+ const tally = el("span", "fam-tally");
4970
+ const loops2 = new Set(members.filter((m) => m.character.kind === "animation").map(loopName)).size;
4971
+ tally.append(document.createTextNode(members.length + (members.length === 1 ? " asset" : " assets") + (loops2 ? " · " + loops2 + (loops2 === 1 ? " loop" : " loops") : "")));
4972
+ for (const [state, n] of Object.entries(counts)) {
4973
+ const t = el("span", "st");
4974
+ t.append(el("i", "dot " + STATE_TONE[state]), document.createTextNode(n + " " + state));
4975
+ tally.append(t);
2943
4976
  }
2944
- if (job.phase === "review" && !ui.settled.has(job.id + ":review")) {
2945
- ui.settled.add(job.id + ":review");
2946
- changed = true;
2947
- notifyJob(job);
4977
+ head.append(tally);
4978
+ const tools = el("div", "tools");
4979
+ if (ui.selecting) tools.append(selectAllButton(members));
4980
+ const view = el("button", null, "Family view");
4981
+ view.type = "button";
4982
+ view.onclick = () => openFamily(root);
4983
+ tools.append(view);
4984
+ const everything = familyMembers(root);
4985
+ const todo = everything.filter(actionable);
4986
+ if (GENERATION && todo.length) {
4987
+ const g = el("button", "primary", "Generate " + todo.length + " · " + priceOf(todo));
4988
+ g.type = "button";
4989
+ g.title = "One job for the family: parents first, then everything drawn from them";
4990
+ g.onclick = () => generateDialog(todo, { project: root.project });
4991
+ tools.append(g);
2948
4992
  }
4993
+ head.append(tools);
4994
+ const grid = el("div", "grid");
4995
+ for (const m of members) grid.append(card(m));
4996
+ group.append(head, grid);
4997
+ out.push(group);
2949
4998
  }
2950
- if (changed) refresh();
2951
- else {
2952
- if (ui.open && !$("dialog-host").childNodes.length && formRegion() !== "drawer") renderDrawer();
2953
- for (const c of document.querySelectorAll(".card")) {
2954
- const item = S.snap.items.find((i) => i.id === c.dataset.key);
2955
- const job = item && activeJobFor(item);
2956
- const badge = c.querySelector(".busy-badge");
2957
- if (job && !badge) c.replaceWith(card(item));
2958
- else if (!job && badge) badge.remove();
4999
+ if (loose.length) {
5000
+ const group = el("div", "fam-group loose");
5001
+ if (families.size) {
5002
+ const head = el("div", "fam-head");
5003
+ head.append(el("b", null, "Not in a family"), el("span", "fam-tally", loose.length + (loose.length === 1 ? " asset" : " assets")));
5004
+ if (ui.selecting) {
5005
+ const tools = el("div", "tools");
5006
+ tools.append(selectAllButton(loose));
5007
+ head.append(tools);
5008
+ }
5009
+ group.append(head);
2959
5010
  }
5011
+ const grid = el("div", "grid");
5012
+ for (const item of loose) grid.append(card(item));
5013
+ group.append(grid);
5014
+ out.push(group);
2960
5015
  }
2961
- const active = S.GEN.jobs.some((job) => ACTIVE_PHASES.has(job.phase) && job.phase !== "review");
2962
- clearTimeout(jobsTimer ?? void 0);
2963
- if (active) jobsTimer = setTimeout(pollJobs, 2e3);
5016
+ return out;
2964
5017
  }
2965
- var DONE_VERB = { generate: "Generated", resume: "Resumed", refresh: "Pulled upstream changes for", restore: "Restored", revert: "Brought back a generation of" };
2966
- async function enableNotifications() {
2967
- if (typeof Notification === "undefined") return false;
2968
- if (Notification.permission === "granted") return true;
2969
- if (Notification.permission === "denied") {
2970
- $("note").textContent = " Notifications are blocked for this page in the browser's site settings.";
2971
- return false;
2972
- }
2973
- try {
2974
- return await Notification.requestPermission() === "granted";
2975
- } catch {
2976
- return false;
2977
- }
5018
+ var actionable = (item) => item.declared && item.currentSpecHash !== null && ["missing", "stale", "failed"].includes(item.state);
5019
+ function priceOf(items) {
5020
+ const totals = {};
5021
+ for (const i of items) if (i.estimatedCost !== null) totals[i.costUnit] = (totals[i.costUnit] || 0) + i.estimatedCost;
5022
+ return Object.entries(totals).map(([unit, n]) => fmtCost(unit, Math.round(n * 100) / 100)).join(" + ") || "free";
2978
5023
  }
2979
- function notifyJob(job) {
2980
- if (!ui.notify || !document.hidden || typeof Notification === "undefined" || Notification.permission !== "granted") return;
2981
- const n = job.keys.length;
2982
- const what = n === 1 ? job.keys[0] : n + " assets";
2983
- const body = job.phase === "review" ? job.review.length + " waiting for you to pick a candidate" : job.phase === "failed" ? "failed: " + (job.error || "see the log") : (DONE_VERB[job.mode] || "Finished") + " " + what;
2984
- try {
2985
- const note = new Notification("pixelkiln" + (job.project ? " · " + job.project : ""), { body, tag: "pixelkiln-job-" + job.id });
2986
- note.onclick = () => {
2987
- window.focus();
2988
- note.close();
2989
- };
2990
- } catch {
5024
+ function projectHeader(pr, count) {
5025
+ const head = el("section", "project");
5026
+ const line = el("div", "phead");
5027
+ line.append(el("h2", null, pr.id));
5028
+ const meta = el("div", "meta");
5029
+ if (pr.name !== pr.id) meta.append(el("span", null, pr.name));
5030
+ meta.append(el("span", "mono", shortPath(pr.manifest)));
5031
+ if (pr.account) meta.append(el("span", null, pr.account));
5032
+ if (pr.error) {
5033
+ meta.append(el("span", "state-bad", "unreadable: " + pr.error));
5034
+ } else {
5035
+ meta.append(el("span", null, count + " of " + pr.items + " shown · " + pr.entries + " lock " + (pr.entries === 1 ? "entry" : "entries")));
5036
+ if (Object.keys(pr.spendByUnit).length) meta.append(el("span", null, fmtSpend(pr.spendByUnit)));
2991
5037
  }
5038
+ line.append(meta);
5039
+ head.append(line);
5040
+ return head;
2992
5041
  }
2993
- function renderJobs() {
2994
- const host = $("jobs");
2995
- host.textContent = "";
2996
- if (!GENERATION) return;
2997
- for (const job of S.GEN.jobs) {
2998
- if (ui.settled.has(job.id + ":dismissed")) continue;
2999
- const row2 = el("div", "job");
3000
- const ph = el("span", "ph");
3001
- ph.append(el("i", "dot " + PHASE_TONE[job.phase]), document.createTextNode(job.phase));
3002
- const what = (job.mode === "refresh" ? "pull upstream for " : job.mode === "restore" ? "restore " : job.mode === "revert" ? "bring back generation #" + job.revert + " of " : job.mode === "resume" ? "resume " : "generate ") + job.keys.length + (job.keys.length === 1 ? " asset" : " assets") + (job.project ? " in " + job.project : "");
3003
- const last = el("span", "last", what + (job.messages.length ? ": " + job.messages[job.messages.length - 1].trim() : ""));
3004
- last.title = job.keys.join("\n");
3005
- const acts = el("div", "acts");
3006
- if (job.phase === "review" && job.review.length) {
3007
- const b = el("button", "primary", "Review " + job.review.length);
5042
+ function candidatesControl(style) {
5043
+ const wrap = el("span", "cand");
5044
+ const editKey = "cand:" + (style.project || "") + ":" + style.id;
5045
+ const declared = S.snap.items.filter((i) => i.project === style.project && i.styleId === style.id && i.declared).length;
5046
+ if (!(EDITABLE && style.candidatesEditable) || ui.editing !== editKey) {
5047
+ wrap.append(el("span", null, style.candidates + (style.candidates === 1 ? " candidate" : " candidates") + " per generation"));
5048
+ if (EDITABLE && style.candidatesEditable) {
5049
+ const b = el("button", null, "change");
3008
5050
  b.type = "button";
3009
- b.onclick = () => openReview(job.id);
3010
- acts.append(b);
3011
- }
3012
- const logBtn = el("button", null, ui.logs.has(job.id) ? "Hide log" : "Log");
3013
- logBtn.type = "button";
3014
- logBtn.onclick = () => {
3015
- ui.logs.has(job.id) ? ui.logs.delete(job.id) : ui.logs.add(job.id);
3016
- renderJobs();
3017
- };
3018
- acts.append(logBtn);
3019
- if (!ACTIVE_PHASES.has(job.phase)) {
3020
- const d = el("button", null, "Dismiss");
3021
- d.type = "button";
3022
- d.onclick = () => {
3023
- ui.settled.add(job.id + ":dismissed");
3024
- renderJobs();
5051
+ b.onclick = () => {
5052
+ ui.editing = editKey;
5053
+ render();
3025
5054
  };
3026
- acts.append(d);
5055
+ wrap.append(b);
5056
+ } else if (style.provider === "pixellab") {
5057
+ wrap.title = "PixelLab: map and pixflux return one image per generation; a 1dir style returns 4–64 for its size.";
3027
5058
  }
3028
- row2.append(ph, last, acts);
3029
- if (ui.logs.has(job.id)) row2.append(el("pre", null, job.messages.join("\n")));
3030
- host.append(row2);
5059
+ return wrap;
3031
5060
  }
5061
+ const input = el("input");
5062
+ input.type = "number";
5063
+ input.min = "1";
5064
+ input.max = "64";
5065
+ input.value = String(style.candidates);
5066
+ const save = el("button", "primary", "Save");
5067
+ save.type = "button";
5068
+ const cancel = el("button", null, "Cancel");
5069
+ cancel.type = "button";
5070
+ cancel.onclick = () => {
5071
+ ui.editing = null;
5072
+ render();
5073
+ };
5074
+ const note = el("span", null, "affects " + declared + (declared === 1 ? " asset, which becomes stale" : " assets, which become stale"));
5075
+ save.onclick = async () => {
5076
+ save.disabled = true;
5077
+ try {
5078
+ const pr = S.snap.workspace ? S.snap.workspace.projects.find((x) => x.id === style.project) : S.snap.project;
5079
+ const body = { action: "patch-style", styleId: style.id, expectedSha256: pr.manifestSha256, patch: { candidates: Number(input.value) } };
5080
+ if (style.project) body.project = style.project;
5081
+ S.snap = await postEdit(body);
5082
+ ui.editing = null;
5083
+ render();
5084
+ } catch (err) {
5085
+ save.disabled = false;
5086
+ note.textContent = err.message;
5087
+ note.className = "state-bad";
5088
+ }
5089
+ };
5090
+ wrap.append(input, save, cancel, note);
5091
+ setTimeout(() => input.focus(), 0);
5092
+ return wrap;
3032
5093
  }
3033
-
3034
- // src/gallery/client/src/hand-edit.ts
3035
- var EDIT_STATUS_TEXT = {
3036
- same: "The generated art’s pixels, not changed yet. Open it in your editor and save.",
3037
- edited: "Differs from the generated art. mount and pack place this file; the generated file stays as the record.",
3038
- "regenerated-since": "The generated art changed after this edit was saved; the edit is based on an older generation.",
3039
- missing: "The declared file is not on disk."
3040
- };
3041
- async function postHandEdit(item, action, extra) {
3042
- const pr = projectOf(item);
3043
- const body = { action, assetId: item.assetId, styleId: item.styleId, expectedSha256: pr.manifestSha256, ...extra };
3044
- if (item.project) body.project = item.project;
3045
- S.snap = await postEdit(body);
3046
- }
3047
- var editableOutputs = (item) => item.outputs.length && item.outputs.every((o) => o.exists && o.mediaType === "image/png");
3048
- var memberNoun = (item, n) => isFrameSet(item) ? n === 1 ? "frame" : "frames" : item.outputs.every((o) => o.role && /^tile/i.test(o.role)) ? n === 1 ? "tile" : "tiles" : n === 1 ? "member" : "members";
3049
- function handEditSection(item) {
3050
- const canStart = EDITABLE && item.declared && item.asset && projectOf(item)?.manifestSha256 && editableOutputs(item);
3051
- if (!item.edit && !canStart) return null;
3052
- const set = item.edits.length > 1;
5094
+ function historySection(item) {
5095
+ const limit = projectOf(item)?.historyLimit;
5096
+ if (!item.history.length && !((limit ?? 0) > 0 && item.status === "downloaded")) return null;
3053
5097
  const s = el("section", "meta");
3054
- s.append(el("h3", null, set ? "Hand edit (" + item.edits.length + " " + memberNoun(item, item.edits.length) + ")" : "Hand edit"));
3055
- if (item.edit) {
3056
- const pair = el("div", "pair");
3057
- const shared = displayScale(item.width, item.height, 200, 160);
3058
- const fig = (out, label) => {
3059
- const f = el("figure");
3060
- if (out && out.url) {
3061
- const img = el("img");
3062
- img.src = out.url;
3063
- img.alt = label;
3064
- if (shared >= 1) {
3065
- img.width = item.width * shared;
3066
- img.height = item.height * shared;
3067
- }
3068
- f.append(img);
3069
- } else f.append(el("span", "state-dim", "not on disk"));
3070
- f.append(el("figcaption", null, label));
3071
- return f;
3072
- };
3073
- const at = set ? Math.min(ui.member, item.edits.length - 1) : 0;
3074
- const which = set ? " · " + (item.outputs[at].role || memberNoun(item, 1) + " " + (at + 1)) : "";
3075
- pair.append(fig(item.outputs[at], "generated" + which), fig(item.edits[at], "edit" + which));
3076
- s.append(pair);
3077
- const dl = el("dl");
3078
- const tone = item.editStatus === "edited" ? "ok" : item.editStatus === "same" ? "dim" : "warn";
3079
- const st = el("span", "state-" + tone);
3080
- st.append(el("i", "dot " + tone), document.createTextNode(" " + item.editStatus));
3081
- row(dl, "status", st);
3082
- row(dl, "why", EDIT_STATUS_TEXT[item.editStatus] || "");
3083
- if (set) {
3084
- row(dl, "files", item.source + ", one per " + memberNoun(item, 1) + ": " + item.edits.map((e) => e.path.split("/").pop()).join(", "), { mono: true, copy: item.edits.map((e) => e.absolutePath).join("\n") });
3085
- const differing = item.editChanged.filter(Boolean).length;
3086
- row(dl, "changed", differing + " of " + item.edits.length + " " + memberNoun(item, item.edits.length) + " differ from the generated art" + (differing ? ": " + item.edits.filter((e, i) => item.editChanged[i]).map((e) => item.outputs[item.edits.indexOf(e)].role || e.path.split("/").pop()).join(", ") : ""));
3087
- } else {
3088
- row(dl, "file", item.edit.path, { mono: true, copy: item.edit.absolutePath });
3089
- if (item.edit.sha256) row(dl, "sha256", item.edit.sha256.slice(0, 16) + "…", { mono: true, copy: item.edit.sha256 });
3090
- }
3091
- row(dl, "saved", fmtWhen(item.edits.reduce((latest, e) => e.modifiedAt && (!latest || e.modifiedAt > latest) ? e.modifiedAt : latest, null)));
3092
- if (item.editMeta) {
3093
- row(dl, "editor", item.editMeta.editor + ", " + fmtWhen(item.editMeta.savedAt) + (item.editMeta.changedSince ? "; a file changed since" : ""));
3094
- if (item.editMeta.basedOn && !set) row(dl, "based on", item.editMeta.basedOn.slice(0, 16) + "…", { mono: true, copy: item.editMeta.basedOn });
3095
- if (item.editMeta.project) row(dl, "layers", item.editMeta.project, { mono: true });
5098
+ s.append(el("h3", null, item.history.length ? "Previous generations (" + item.history.length + ")" : "Previous generations"));
5099
+ if (!item.history.length) {
5100
+ s.append(el("div", "state-dim", "None yet. A regeneration keeps the generation it replaces, up to " + limit + " per asset (PIXELKILN_HISTORY, or the manifest’s history), so it can be brought back from here."));
5101
+ return s;
5102
+ }
5103
+ const list = el("div", "versions");
5104
+ const job = GENERATION ? activeJobFor(item) : null;
5105
+ for (const g of item.history) {
5106
+ const v = el("div", "version");
5107
+ const thumb2 = el("div", "thumb");
5108
+ const first = g.outputs[0];
5109
+ if (first && first.url) {
5110
+ const img = el("img");
5111
+ img.src = first.url;
5112
+ img.alt = "generation #" + g.index;
5113
+ thumb2.append(img);
5114
+ } else thumb2.append(el("span", null, g.cached ? "" : "not cached"));
5115
+ const facts = el("div", "facts");
5116
+ const head = el("div");
5117
+ const billedNote = g.billed && (g.billed.unit !== g.costUnit || g.billed.amount !== g.cost) ? " (billed " + fmtCost(g.billed.unit, g.billed.amount) + ")" : "";
5118
+ head.append(el("b", null, "#" + g.index), document.createTextNode(" · " + fmtWhen(g.downloadedAt || g.submittedAt) + " · " + fmtCost(g.costUnit, g.cost) + billedNote + (g.outputs.length > 1 ? " · " + g.outputs.length + " files" : "")));
5119
+ facts.append(head);
5120
+ const prompt = el("div", "prompt" + (g.promptDiffers ? " differs" : ""), (g.promptDiffers ? "prompt: " : "same prompt: ") + g.prompt);
5121
+ prompt.title = g.prompt;
5122
+ facts.append(prompt);
5123
+ const meta = el("div", "meta");
5124
+ meta.append(document.createTextNode((first ? first.sha256.slice(0, 12) + "…" : "") + (g.cached ? " · bytes cached locally" : " · not in the local cache; a restore re-downloads it")));
5125
+ if (g.upstreamUrl) {
5126
+ const a = el("a", null, "open in " + item.provider + " ↗");
5127
+ a.href = g.upstreamUrl;
5128
+ a.target = "_blank";
5129
+ a.rel = "noopener";
5130
+ meta.append(document.createTextNode(" · "), a);
3096
5131
  }
3097
- s.append(dl);
3098
- } else {
3099
- s.append(el("div", "state-dim", item.outputs.length > 1 ? "Touch the " + memberNoun(item, 2) + " up in your own editor or in the browser, where they open as " + (isFrameSet(item) ? "one animation" : "the frames of one project") + ". The generated files stay untouched; the edit is one sibling file per " + memberNoun(item, 1) + " that the manifest points at, and mount, pack, and export place those instead." : "Touch it up in your own editor. The generated file stays untouched; the edit is a sibling file the manifest points at, and mount and pack place that instead."));
3100
- }
3101
- if (EDITABLE && item.declared && projectOf(item)?.manifestSha256) {
3102
- const acts = el("div", "hand-actions");
3103
- const msg = el("span", "msg");
3104
- const go = async (label, action, extra, done) => {
3105
- const b = el("button", label === "Detach edit" || EDITOR && S.ED && S.ED.installed ? null : "primary", label);
5132
+ facts.append(meta);
5133
+ const acts = el("div", "acts");
5134
+ if (GENERATION) {
5135
+ const b = el("button", null, "Restore this one · no cost");
3106
5136
  b.type = "button";
3107
- b.onclick = async () => {
3108
- b.disabled = true;
3109
- msg.className = "msg";
3110
- msg.textContent = "…";
3111
- try {
3112
- await postHandEdit(item, action, extra);
3113
- ui.notice = { id: item.id, text: done };
3114
- render();
3115
- } catch (err) {
3116
- showSaveError(msg, b, err);
3117
- }
3118
- };
5137
+ b.disabled = !!job;
5138
+ b.title = job ? "Wait for the running job to finish" : "The current generation moves into history; this one becomes current and its bytes are written back";
5139
+ b.onclick = () => generateDialog([item], { project: item.project, revert: String(g.index), generation: g });
3119
5140
  acts.append(b);
3120
- };
3121
- if (EDITOR && S.ED && (item.edit || canStart) && editorSource(item)) {
3122
- if (S.ED.installed) {
3123
- const b = el("button", "primary", "Edit in browser");
3124
- b.type = "button";
3125
- b.title = "Open in Pixelorama here; Save writes the edit file and declares it";
3126
- b.onclick = () => openEditorSheet(item);
3127
- acts.append(b);
3128
- } else if (S.ED.release && !S.ED.installing) {
3129
- const b = el("button", null, "Install editor to edit in browser");
3130
- b.type = "button";
3131
- b.onclick = () => {
3132
- installEditor();
3133
- window.scrollTo({ top: 0 });
3134
- };
3135
- acts.append(b);
3136
- }
3137
- }
3138
- if (item.edit) {
3139
- go("Open in desktop editor", "start-edit", { open: true }, "Opened " + item.edit.path + " in your editor. Save there, then Refresh.");
3140
- go("Detach edit", "detach-edit", {}, "Detached. The file" + (set ? "s are" : " is") + " still at " + item.source + "; the generated art is placed again.");
3141
- } else if (canStart) {
3142
- const many = item.outputs.length > 1;
3143
- go("Edit by hand", "start-edit", { open: true }, "Created the edit file" + (many ? "s and opened the first " + memberNoun(item, 1) : " and opened it") + " in your editor. Save there, then Refresh to see it here.");
3144
- go("Create edit file" + (many ? "s" : "") + " only", "start-edit", { open: false }, "Created the edit file" + (many ? "s" : "") + " and declared " + (many ? "them" : "it") + " in the manifest.");
3145
5141
  }
3146
- acts.append(msg);
5142
+ v.append(thumb2, facts, acts);
5143
+ list.append(v);
5144
+ }
5145
+ s.append(list);
5146
+ s.append(el("div", "state-dim", "Keeping up to " + limit + " per asset; a restore moves the current generation into this list, so it can be undone the same way." + (GENERATION ? "" : " Restoring needs the gallery started with --budget (any amount; nothing is spent).")));
5147
+ return s;
5148
+ }
5149
+ function upstreamSection(item) {
5150
+ if (!item.upstreamUrl && !(GENERATION && item.refreshable)) return null;
5151
+ const s = el("section", "meta");
5152
+ s.append(el("h3", null, "Upstream"));
5153
+ const dl = el("dl");
5154
+ if (item.upstreamUrl) {
5155
+ const a = el("a", null, "Open in " + item.provider + " ↗");
5156
+ a.href = item.upstreamUrl;
5157
+ a.target = "_blank";
5158
+ a.rel = "noopener";
5159
+ const tiles = item.generator === "tiles";
5160
+ row(dl, tiles ? "tile set" : "object", a);
5161
+ row(dl, "note", item.provider === "pixellab" ? tiles ? "The tile set this generation was chosen from. Edit it there with PixelLab’s editor, then pull the changes back here; the lockfile records the new bytes as this generation." : "The account object this generation came from. Edit it there with PixelLab’s editor, then pull the changes back here; the lockfile records the new bytes as this generation." : "The provider’s page for this object.");
5162
+ }
5163
+ s.append(dl);
5164
+ if (GENERATION && item.refreshable) {
5165
+ const acts = el("div", "hand-actions");
5166
+ const b = el("button", null, "Pull upstream changes · no cost");
5167
+ b.type = "button";
5168
+ b.onclick = () => generateDialog([item], { project: item.project, refresh: true });
5169
+ acts.append(b);
3147
5170
  s.append(acts);
3148
5171
  }
3149
5172
  return s;
3150
5173
  }
5174
+ function jobStrip(item, job) {
5175
+ const strip = el("div", "job-strip");
5176
+ const ph = el("span", "ph");
5177
+ ph.append(el("i", "dot busy"), document.createTextNode(job.phase));
5178
+ const last = el("span", "last", job.messages.length ? job.messages[job.messages.length - 1].trim() : "");
5179
+ last.title = job.messages.join("\n");
5180
+ const what = el("span", "what", (JOB_VERB[job.mode] || job.mode) + " this asset: " + (PHASE_TEXT[job.phase] || job.phase) + (job.mode === "generate" && job.phase !== "review" ? ". The current file stays until the new result is downloaded." : "."));
5181
+ strip.append(ph, last, what);
5182
+ const acts = el("div", "acts");
5183
+ if (job.phase === "review" && job.review.includes(item.key)) {
5184
+ const b = el("button", "primary", "Review candidates");
5185
+ b.type = "button";
5186
+ b.onclick = () => openReview(job.id);
5187
+ acts.append(b);
5188
+ }
5189
+ const logBtn = el("button", null, ui.logs.has(job.id) ? "Hide log" : "Log");
5190
+ logBtn.type = "button";
5191
+ logBtn.onclick = () => {
5192
+ ui.logs.has(job.id) ? ui.logs.delete(job.id) : ui.logs.add(job.id);
5193
+ renderDrawer();
5194
+ };
5195
+ acts.append(logBtn);
5196
+ strip.append(acts);
5197
+ if (ui.logs.has(job.id)) {
5198
+ const pre = el("pre", null, job.messages.join("\n"));
5199
+ pre.style.gridColumn = "1 / -1";
5200
+ strip.append(pre);
5201
+ }
5202
+ return strip;
5203
+ }
5204
+ function generateActions(item) {
5205
+ const row2 = el("div", "gen");
5206
+ if (!GENERATION || !item.declared || item.currentSpecHash === null) return row2;
5207
+ const cost = item.estimatedCost === null ? "" : " · " + fmtCost(item.costUnit, item.estimatedCost);
5208
+ const add = (label, cls, opts) => {
5209
+ const b = el("button", cls, label);
5210
+ b.type = "button";
5211
+ b.onclick = () => generateDialog([item], { project: item.project, ...opts });
5212
+ row2.append(b);
5213
+ };
5214
+ if (item.state === "missing" || item.state === "stale" || item.state === "failed") add("Generate" + cost, "primary", {});
5215
+ else if (item.state === "ok") add("Regenerate" + cost, null, { force: true });
5216
+ else if (item.state === "orphaned" && item.outputs.every((o) => o.exists)) {
5217
+ add("Restore recorded bytes · no cost", null, { restore: true, force: true });
5218
+ add("Regenerate" + cost, null, { force: true });
5219
+ } else if (item.state === "orphaned") add("Restore · no cost", "primary", { restore: true });
5220
+ else if (item.state === "untracked") add("Generate" + cost + " · replaces the file", null, { force: true });
5221
+ if (item.state === "recoverable" && item.status === "downloaded") {
5222
+ add(paletteRuleOf(item) ? "Snap to the palette · no cost" : "Put the provider’s bytes back · no cost", "primary", { resume: true });
5223
+ } else if (item.state === "in-flight" || item.state === "recoverable") {
5224
+ const holder = S.GEN.jobs.find((job) => job.phase === "review" && job.project === item.project && job.review.includes(item.key));
5225
+ if (holder) {
5226
+ const b = el("button", "primary", "Review candidates");
5227
+ b.type = "button";
5228
+ b.onclick = () => openReview(holder.id);
5229
+ row2.append(b);
5230
+ } else {
5231
+ add(item.status === "review" ? "Resume review" : "Resume · no cost", "primary", { resume: true });
5232
+ }
5233
+ }
5234
+ return row2;
5235
+ }
3151
5236
 
3152
- // src/gallery/client/src/sheet.ts
3153
- var editorSources = (item) => {
3154
- if (item.edits.length && item.edits.every((e) => e.exists)) return { files: item.edits, fromEdit: true };
3155
- if (editableOutputs(item)) return { files: item.outputs, fromEdit: false };
3156
- return null;
5237
+ // src/gallery/client/src/jobs.ts
5238
+ var ACTIVE_PHASES = /* @__PURE__ */ new Set(["queued", "submitting", "polling", "fetching", "review"]);
5239
+ var PHASE_TONE = { queued: "cool", submitting: "cool", polling: "cool", fetching: "cool", review: "warn", done: "ok", failed: "bad" };
5240
+ var familyLabel = (item) => {
5241
+ const c = item.character;
5242
+ if (item.mirrorOfKey) return "mirror of " + item.mirrorOfKey.split("/").slice(1).join("/") + (c && c.direction ? ", " + c.direction : "");
5243
+ if (!c || c.kind === "base") return null;
5244
+ const parent = c.parentKey ? c.parentKey.split("/").slice(1).join("/") : null;
5245
+ if (c.kind === "state") return parent ? "state of " + parent : "state";
5246
+ return (parent ? "loop of " + parent : "loop") + (c.direction ? ", " + c.direction : "");
3157
5247
  };
3158
- var editorSource = (item) => {
3159
- const s = editorSources(item);
3160
- return s ? s.files[0] : null;
5248
+ var paletteRuleOf = (item) => {
5249
+ const style = S.snap.styles.find((s) => s.id === item.styleId && s.project === item.project);
5250
+ return style && style.enforcePalette && style.palette.length >= 2 ? style.palette : null;
3161
5251
  };
3162
- var toBase64 = (buf) => new Promise((resolve, reject) => {
3163
- const r = new FileReader();
3164
- r.onload = () => resolve(String(r.result).slice(String(r.result).indexOf(",") + 1));
3165
- r.onerror = () => reject(r.error);
3166
- r.readAsDataURL(new Blob([buf]));
3167
- });
3168
- function sheetStatus(tone, text) {
3169
- if (!S.SHEET) return;
3170
- S.SHEET.status.textContent = "";
3171
- S.SHEET.status.append(el("i", "dot " + tone), document.createTextNode(text));
3172
- }
3173
- function sheetButtons() {
3174
- if (!S.SHEET) return;
3175
- const busy = !S.SHEET.opened || S.SHEET.pending !== null;
3176
- S.SHEET.save.disabled = busy || !S.SHEET.dirty;
3177
- S.SHEET.saveClose.disabled = busy;
3178
- }
3179
- function openEditorSheet(item) {
3180
- if (S.SHEET) return;
3181
- const src = editorSource(item);
3182
- const host = $("dialog-host");
3183
- host.textContent = "";
3184
- const scrim = el("div", "sheet-scrim");
3185
- scrim.onclick = () => closeEditorSheet();
3186
- const panel = el("div", "sheet editor-host");
3187
- const bar = el("div", "rbar");
3188
- const close = el("button", null, "Close");
3189
- close.type = "button";
3190
- close.onclick = () => closeEditorSheet();
3191
- const title = el("b", null, (item.project ? item.project + ":" : "") + item.styleId + "/" + item.assetId + " · " + item.width + "×" + item.height + (item.outputs.length > 1 ? " · " + item.outputs.length + " " + memberNoun(item, item.outputs.length) : ""));
3192
- const status = el("span", "st");
3193
- const acts = el("div", "acts");
3194
- const msg = el("span", "msg");
3195
- const compare = el("label", "chip");
3196
- compare.hidden = true;
3197
- compare.title = "The generated art on a locked layer at 50%, for comparison; never part of the saved file";
3198
- const compareBox = el("input");
3199
- compareBox.type = "checkbox";
3200
- compareBox.checked = true;
3201
- compareBox.onchange = () => showReference(compareBox.checked);
3202
- compare.append(compareBox, document.createTextNode(" show generated"));
3203
- const save = el("button", "primary", "Save to project");
3204
- save.type = "button";
3205
- save.onclick = () => requestEditorSave(false);
3206
- const saveClose = el("button", null, "Save & close");
3207
- saveClose.type = "button";
3208
- saveClose.onclick = () => requestEditorSave(true);
3209
- acts.append(msg, compare, save, saveClose);
3210
- bar.append(close, title, status, acts);
3211
- const stage = el("div", "stage");
3212
- const frame = el("iframe");
3213
- frame.title = "Pixelorama";
3214
- frame.src = S.ED.url;
3215
- const loading = el("div", "loading");
3216
- const loadText = el("div");
3217
- loadText.append(el("b", null, "Loading the editor"), document.createTextNode("The first open compiles a 40 MB build; later opens come from the browser cache."));
3218
- loading.append(loadText);
3219
- stage.append(frame, loading);
3220
- panel.append(bar, stage);
3221
- host.append(scrim, panel);
3222
- S.SHEET = { item, frame, loading, status, msg, save, saveClose, compare, dirty: false, opened: false, ready: null, pending: null, requests: 0, source: src, sentProject: false, sentReference: false, reference: false, roles: null };
3223
- sheetStatus("cool", "loading");
3224
- sheetButtons();
3225
- close.focus({ preventScroll: true });
5252
+ var isRevisable = (item) => {
5253
+ if (item.source) return true;
5254
+ if (item.quality) return item.quality.review?.status === "approved" && !!item.quality.check?.current;
5255
+ return item.status === "downloaded" && item.state === "ok";
5256
+ };
5257
+ var activeJobFor = (item) => S.GEN.jobs.find((job) => ACTIVE_PHASES.has(job.phase) && job.project === item.project && job.keys.includes(item.key)) || null;
5258
+ var JOB_VERB = { generate: "regenerating", resume: "resuming", refresh: "pulling upstream changes for", restore: "restoring", revert: "bringing back a previous generation of" };
5259
+ var PHASE_TEXT = { queued: "queued", submitting: "submitting to the provider", polling: "waiting for the provider to finish", fetching: "downloading the result", review: "candidates are ready to review" };
5260
+ var remainingBudget = (provider) => {
5261
+ const keyed = S.GEN.budget.byProvider[provider];
5262
+ const ceiling = keyed !== void 0 ? keyed : S.GEN.budget.amount;
5263
+ return ceiling === void 0 ? null : Math.max(0, ceiling - (S.GEN.spent[provider] || 0));
5264
+ };
5265
+ async function postGenerate(body) {
5266
+ const res = await fetch("/api/generate", {
5267
+ method: "POST",
5268
+ headers: { "Content-Type": "application/json", "X-Pixelkiln-Session": SESSION ?? "" },
5269
+ body: JSON.stringify(body)
5270
+ });
5271
+ if (!res.ok) {
5272
+ const err = new Error(await res.text());
5273
+ err.status = res.status;
5274
+ throw err;
5275
+ }
5276
+ return res.json();
3226
5277
  }
3227
- async function sendOpen() {
3228
- const { item } = S.SHEET;
3229
- const sources = editorSources(item);
3230
- const style = S.snap.styles.find((s) => s.id === item.styleId && s.project === item.project);
3231
- const projectUrl = sources.fromEdit && item.editMeta && item.editMeta.projectUrl && S.SHEET.ready.version >= 2 ? item.editMeta.projectUrl : null;
3232
- const set = sources.files.length > 1;
3233
- if (set && S.SHEET.ready.version < 3) {
3234
- S.SHEET.msg.textContent = "This editor build cannot open sets; reinstall it with pixelkiln tools install editor.";
3235
- sheetStatus("bad", "unsupported");
5278
+ var jobsTimer = null;
5279
+ async function pollJobs() {
5280
+ if (!GENERATION) return;
5281
+ try {
5282
+ const res = await fetch("/api/jobs", { cache: "no-store" });
5283
+ if (!res.ok) throw new Error(await res.text());
5284
+ S.GEN = await res.json();
5285
+ } catch (err) {
5286
+ $("note").textContent = " Job status unavailable: " + err.message;
3236
5287
  return;
3237
5288
  }
3238
- const referenceFiles = sources.fromEdit && S.SHEET.ready.version >= 4 && item.outputs.every((o) => o.exists && o.url) ? item.outputs : null;
3239
- const pngs = [];
3240
- const reference = [];
3241
- let pxo = null;
3242
- try {
3243
- for (const file of sources.files) {
3244
- const res = await fetch(file.url, { cache: "no-store" });
3245
- if (!res.ok) throw new Error(await res.text());
3246
- pngs.push(await res.arrayBuffer());
3247
- }
3248
- if (projectUrl) {
3249
- const p = await fetch(projectUrl, { cache: "no-store" });
3250
- if (p.ok) pxo = await p.arrayBuffer();
3251
- }
3252
- for (const file of referenceFiles || []) {
3253
- const res = await fetch(file.url, { cache: "no-store" });
3254
- if (res.ok) reference.push({ role: file.role || null, png: await res.arrayBuffer() });
5289
+ renderJobs();
5290
+ renderHeader();
5291
+ let changed = false;
5292
+ for (const job of S.GEN.jobs) {
5293
+ if (!ACTIVE_PHASES.has(job.phase) && !ui.settled.has(job.id)) {
5294
+ ui.settled.add(job.id);
5295
+ changed = true;
5296
+ notifyJob(job);
5297
+ const open = ui.open && S.snap.items.find((i) => i.id === ui.open);
5298
+ if (open && job.project === open.project && job.keys.includes(open.key)) {
5299
+ ui.notice = { id: open.id, text: job.phase === "failed" ? (JOB_VERB[job.mode] || job.mode).replace(/ing$/, "ing") + " this asset failed: " + (job.error || "see the log above") : job.mode === "generate" ? "Regenerated. The new result is on disk and recorded as this generation." : job.mode === "restore" ? "Restored. The recorded bytes are back on disk." : job.mode === "revert" ? "Brought back generation #" + job.revert + ". The one it replaced is now #1 in the list below." : job.mode === "refresh" ? job.counts.downloaded ? "Pulled the upstream change; the lockfile records the new bytes." : "Nothing changed upstream; the file was left alone." : job.mode === "resume" && job.counts.downloaded ? "Done. The file on disk and the record now match the manifest." : "Done." };
5300
+ }
3255
5301
  }
3256
- } catch (err) {
3257
- if (S.SHEET) {
3258
- S.SHEET.msg.textContent = "Could not load the image: " + err.message;
3259
- sheetStatus("bad", "failed");
5302
+ if (job.phase === "review" && !ui.settled.has(job.id + ":review")) {
5303
+ ui.settled.add(job.id + ":review");
5304
+ changed = true;
5305
+ notifyJob(job);
3260
5306
  }
3261
- return;
3262
5307
  }
3263
- if (!S.SHEET) return;
3264
- const request = "open-" + ++S.SHEET.requests;
3265
- S.SHEET.sentProject = !!pxo;
3266
- S.SHEET.roles = set ? item.outputs.map((o) => o.role || null) : null;
3267
- const message = {
3268
- type: "pixelkiln:open",
3269
- request,
3270
- asset: { key: item.styleId + "/" + item.assetId, id: item.id, name: item.assetId, width: item.width, height: item.height },
3271
- png: pngs[0],
3272
- palette: style ? style.palette : []
3273
- };
3274
- const transfer = [pngs[0]];
3275
- if (set) {
3276
- message.frames = pngs.map((png, i) => ({ role: S.SHEET.roles[i], png }));
3277
- message.fps = isFrameSet(item) ? item.fps || 12 : 1;
3278
- for (const png of pngs.slice(1)) transfer.push(png);
3279
- message.png = pngs[0].slice(0);
3280
- transfer.push(message.png);
5308
+ if (changed) refresh();
5309
+ else {
5310
+ if (ui.open && !$("dialog-host").childNodes.length && formRegion() !== "drawer") renderDrawer();
5311
+ for (const c of document.querySelectorAll(".card")) {
5312
+ const item = S.snap.items.find((i) => i.id === c.dataset.key);
5313
+ const job = item && activeJobFor(item);
5314
+ const badge = c.querySelector(".busy-badge");
5315
+ if (job && !badge) c.replaceWith(card(item));
5316
+ else if (!job && badge) badge.remove();
5317
+ }
3281
5318
  }
3282
- if (pxo) {
3283
- message.pxo = pxo;
3284
- transfer.push(pxo);
5319
+ const active = S.GEN.jobs.some((job) => ACTIVE_PHASES.has(job.phase) && job.phase !== "review");
5320
+ clearTimeout(jobsTimer ?? void 0);
5321
+ if (active) jobsTimer = setTimeout(pollJobs, 2e3);
5322
+ }
5323
+ var DONE_VERB = { generate: "Generated", resume: "Resumed", refresh: "Pulled upstream changes for", restore: "Restored", revert: "Brought back a generation of" };
5324
+ async function enableNotifications() {
5325
+ if (typeof Notification === "undefined") return false;
5326
+ if (Notification.permission === "granted") return true;
5327
+ if (Notification.permission === "denied") {
5328
+ $("note").textContent = " Notifications are blocked for this page in the browser's site settings.";
5329
+ return false;
3285
5330
  }
3286
- if (reference.length === (referenceFiles || []).length && reference.length) {
3287
- message.reference = reference;
3288
- for (const r of reference) transfer.push(r.png);
5331
+ try {
5332
+ return await Notification.requestPermission() === "granted";
5333
+ } catch {
5334
+ return false;
3289
5335
  }
3290
- S.SHEET.sentReference = !!message.reference;
3291
- S.SHEET.frame.contentWindow.postMessage(message, location.origin, transfer);
3292
- sheetStatus("cool", "opening");
3293
- }
3294
- function showReference(visible) {
3295
- if (!S.SHEET || !S.SHEET.opened || !S.SHEET.reference) return;
3296
- S.SHEET.frame.contentWindow.postMessage({ type: "pixelkiln:reference", visible }, location.origin);
3297
5336
  }
3298
- function requestEditorSave(close) {
3299
- if (!S.SHEET || !S.SHEET.opened || S.SHEET.pending) return;
3300
- const request = "save-" + ++S.SHEET.requests;
3301
- S.SHEET.pending = { request, close };
3302
- S.SHEET.msg.textContent = "";
3303
- sheetStatus("cool", "saving");
3304
- sheetButtons();
3305
- S.SHEET.frame.contentWindow.postMessage({ type: "pixelkiln:request-save", request }, location.origin);
5337
+ function notifyJob(job) {
5338
+ if (!ui.notify || !document.hidden || typeof Notification === "undefined" || Notification.permission !== "granted") return;
5339
+ const n = job.keys.length;
5340
+ const what = n === 1 ? job.keys[0] : n + " assets";
5341
+ const body = job.phase === "review" ? job.review.length + " waiting for you to pick a candidate" : job.phase === "failed" ? "failed: " + (job.error || "see the log") : (DONE_VERB[job.mode] || "Finished") + " " + what;
5342
+ try {
5343
+ const note = new Notification("pixelkiln" + (job.project ? " · " + job.project : ""), { body, tag: "pixelkiln-job-" + job.id });
5344
+ note.onclick = () => {
5345
+ window.focus();
5346
+ note.close();
5347
+ };
5348
+ } catch {
5349
+ }
3306
5350
  }
3307
- async function onEditorMessage(m) {
3308
- switch (m.type) {
3309
- case "pixelkiln:ready":
3310
- S.SHEET.ready = m;
3311
- if (m.version !== S.ED.protocol) {
3312
- S.SHEET.msg.textContent = "The editor speaks protocol " + m.version + "; this gallery expects " + S.ED.protocol + ". Reinstall it with pixelkiln tools install editor.";
3313
- sheetStatus("bad", "mismatch");
3314
- return;
3315
- }
3316
- sendOpen();
3317
- break;
3318
- case "pixelkiln:opened":
3319
- S.SHEET.opened = true;
3320
- S.SHEET.loading.remove();
3321
- S.SHEET.reference = !!m.reference;
3322
- S.SHEET.compare.hidden = !S.SHEET.reference;
3323
- if (m.source === "pxo") sheetStatus("ok", "editing the edit file" + (m.frames > 1 ? "s" : "") + " with " + (m.layers === 1 ? "the layer" : m.layers + " layers") + (m.frames > 1 ? " and " + m.frames + " " + memberNoun(S.SHEET.item, m.frames) : "") + " restored");
3324
- else if (S.SHEET.sentProject) sheetStatus("warn", "editing the flattened edit file" + (m.frames > 1 ? "s" : "") + "; the layer file could not be opened");
3325
- else if (m.source === "frames") sheetStatus("ok", (S.SHEET.item.edits.length ? "editing the edit files" : "editing a copy of the generated " + memberNoun(S.SHEET.item, m.frames)) + " as " + m.frames + " frames" + (isFrameSet(S.SHEET.item) ? "" : ", one per " + memberNoun(S.SHEET.item, 1)));
3326
- else sheetStatus("ok", S.SHEET.item.edit && S.SHEET.item.edit.exists ? "editing the edit file" : "editing a copy of the generated art");
3327
- if (S.SHEET.reference) S.SHEET.status.append(document.createTextNode(" · generated art shown through at 50%"));
3328
- sheetButtons();
3329
- break;
3330
- case "pixelkiln:dirty":
3331
- S.SHEET.dirty = !!m.dirty;
3332
- if (S.SHEET.opened && !S.SHEET.pending) sheetStatus(S.SHEET.dirty ? "warn" : "ok", S.SHEET.dirty ? "unsaved changes" : "saved");
3333
- sheetButtons();
3334
- break;
3335
- case "pixelkiln:save": {
3336
- const pending = S.SHEET.pending;
3337
- if (!pending || pending.request !== m.request) return;
3338
- try {
3339
- const body = { editor: S.SHEET.ready.editor, protocol: S.SHEET.ready.version };
3340
- if (S.SHEET.roles) {
3341
- if (!Array.isArray(m.frames)) throw new Error("the editor returned no frames");
3342
- body.frames = [];
3343
- for (const f of m.frames) body.frames.push({ role: f.role === void 0 ? null : f.role, png: await toBase64(f.png) });
3344
- } else {
3345
- body.png = await toBase64(m.png);
3346
- }
3347
- if (m.pxo && m.pxo.byteLength) body.pxo = await toBase64(m.pxo);
3348
- await postHandEdit(S.SHEET.item, "save-edit", body);
3349
- const saved = S.snap.items.find((i) => i.id === S.SHEET.item.id);
3350
- if (saved) S.SHEET.item = saved;
3351
- S.SHEET.dirty = false;
3352
- S.SHEET.pending = null;
3353
- ui.notice = { id: S.SHEET.item.id, text: "Saved " + (saved && saved.edits.length > 1 ? saved.edits.length + " " + memberNoun(saved, saved.edits.length) + " to " + saved.source : saved && saved.edit ? saved.edit.path : "the edit") + ". mount and pack place " + (saved && saved.edits.length > 1 ? "them" : "it") + " in place of the generated art." };
3354
- render();
3355
- if (pending.close) {
3356
- closeEditorSheet(true);
3357
- return;
3358
- }
3359
- sheetStatus("ok", "saved");
3360
- } catch (err) {
3361
- S.SHEET.pending = null;
3362
- S.SHEET.msg.textContent = err.message + (err.status === 409 ? " Press Refresh, then save again." : "");
3363
- sheetStatus("bad", "not saved");
3364
- }
3365
- sheetButtons();
3366
- break;
5351
+ function renderJobs() {
5352
+ const host = $("jobs");
5353
+ host.textContent = "";
5354
+ if (!GENERATION) return;
5355
+ for (const job of S.GEN.jobs) {
5356
+ if (ui.settled.has(job.id + ":dismissed")) continue;
5357
+ const row2 = el("div", "job");
5358
+ const ph = el("span", "ph");
5359
+ ph.append(el("i", "dot " + PHASE_TONE[job.phase]), document.createTextNode(job.phase));
5360
+ const what = (job.mode === "refresh" ? "pull upstream for " : job.mode === "restore" ? "restore " : job.mode === "revert" ? "bring back generation #" + job.revert + " of " : job.mode === "resume" ? "resume " : "generate ") + job.keys.length + (job.keys.length === 1 ? " asset" : " assets") + (job.project ? " in " + job.project : "");
5361
+ const last = el("span", "last", what + (job.messages.length ? ": " + job.messages[job.messages.length - 1].trim() : ""));
5362
+ last.title = job.keys.join("\n");
5363
+ const acts = el("div", "acts");
5364
+ if (job.phase === "review" && job.review.length) {
5365
+ const b = el("button", "primary", "Review " + job.review.length);
5366
+ b.type = "button";
5367
+ b.onclick = () => openReview(job.id);
5368
+ acts.append(b);
3367
5369
  }
3368
- case "pixelkiln:error":
3369
- S.SHEET.msg.textContent = m.message || "The editor reported an error.";
3370
- if (S.SHEET.pending) {
3371
- S.SHEET.pending = null;
3372
- sheetStatus("bad", "not saved");
3373
- sheetButtons();
3374
- }
3375
- break;
5370
+ const logBtn = el("button", null, ui.logs.has(job.id) ? "Hide log" : "Log");
5371
+ logBtn.type = "button";
5372
+ logBtn.onclick = () => {
5373
+ ui.logs.has(job.id) ? ui.logs.delete(job.id) : ui.logs.add(job.id);
5374
+ renderJobs();
5375
+ };
5376
+ acts.append(logBtn);
5377
+ if (!ACTIVE_PHASES.has(job.phase)) {
5378
+ const d = el("button", null, "Dismiss");
5379
+ d.type = "button";
5380
+ d.onclick = () => {
5381
+ ui.settled.add(job.id + ":dismissed");
5382
+ renderJobs();
5383
+ };
5384
+ acts.append(d);
5385
+ }
5386
+ row2.append(ph, last, acts);
5387
+ if (ui.logs.has(job.id)) row2.append(el("pre", null, job.messages.join("\n")));
5388
+ host.append(row2);
3376
5389
  }
3377
5390
  }
3378
- function closeEditorSheet(force) {
3379
- if (!S.SHEET) return;
3380
- if (S.SHEET.dirty && !force && !confirm("Discard unsaved changes in the editor?")) return;
3381
- S.SHEET = null;
3382
- $("dialog-host").textContent = "";
3383
- refresh();
3384
- }
3385
- window.addEventListener("beforeunload", (e) => {
3386
- if (S.SHEET && S.SHEET.dirty) {
3387
- e.preventDefault();
3388
- e.returnValue = "";
3389
- }
3390
- });
3391
5391
 
3392
5392
  // src/gallery/client/src/editor.ts
3393
5393
  var edTimer = null;
@@ -3404,7 +5404,7 @@
3404
5404
  renderTools();
3405
5405
  clearTimeout(edTimer ?? void 0);
3406
5406
  if (S.ED.installing) edTimer = setTimeout(pollEditor, 1e3);
3407
- else if (ui.open && formRegion() !== "drawer") renderDrawer();
5407
+ else if ((ui.open || ui.model) && formRegion() !== "drawer") renderDrawer();
3408
5408
  }
3409
5409
  async function installEditor() {
3410
5410
  try {
@@ -4286,7 +6286,7 @@
4286
6286
  }
4287
6287
  dl.append(dd);
4288
6288
  }
4289
- function section(title) {
6289
+ function section2(title) {
4290
6290
  const s = el("section", "meta");
4291
6291
  s.append(el("h3", null, title));
4292
6292
  const dl = el("dl");
@@ -4561,6 +6561,7 @@
4561
6561
  };
4562
6562
  function renderDrawer() {
4563
6563
  const host = $("drawer-host");
6564
+ if (!ui.open && renderModelDrawer()) return;
4564
6565
  host.textContent = "";
4565
6566
  stopPlayback();
4566
6567
  const item = ui.open && S.snap.items.find((i) => i.id === ui.open);
@@ -4632,7 +6633,7 @@
4632
6633
  const tab = { overview: el("div"), files: el("div"), history: el("div"), details: el("div") };
4633
6634
  let pane = tab.overview;
4634
6635
  {
4635
- const { s, dl } = section("Generation");
6636
+ const { s, dl } = section2("Generation");
4636
6637
  row(dl, "provider", item.provider);
4637
6638
  row(dl, "generator", item.generator + (item.tileFeature ? " · " + item.tileFeature : ""));
4638
6639
  const pr = el("div", "prompt", item.prompt);
@@ -4663,7 +6664,7 @@
4663
6664
  pane.append(s);
4664
6665
  }
4665
6666
  {
4666
- const { s, dl } = section("Provider record");
6667
+ const { s, dl } = section2("Provider record");
4667
6668
  row(dl, "lock status", item.status || "none (nothing submitted)");
4668
6669
  row(dl, "submitted", fmtWhen(item.submittedAt));
4669
6670
  row(dl, "downloaded", fmtWhen(item.downloadedAt));
@@ -4709,7 +6710,7 @@
4709
6710
  pane = tab.overview;
4710
6711
  if (item.character) {
4711
6712
  const c = item.character;
4712
- const { s, dl } = section("Character");
6713
+ const { s, dl } = section2("Character");
4713
6714
  row(dl, "kind", CHARACTER_KIND[c.kind] || c.kind);
4714
6715
  if (c.parentKey) row(dl, "parent", keyLink(item, c.parentKey));
4715
6716
  row(dl, "engine", c.mode);
@@ -4760,19 +6761,19 @@
4760
6761
  pane.append(s);
4761
6762
  }
4762
6763
  if (item.mirrorOfKey) {
4763
- const { s, dl } = section("Mirror");
6764
+ const { s, dl } = section2("Mirror");
4764
6765
  row(dl, "flipped from", keyLink(item, item.mirrorOfKey));
4765
6766
  row(dl, "cost", "none; made locally from that asset's files");
4766
6767
  pane.append(s);
4767
6768
  }
4768
6769
  const mirrors = S.snap.items.filter((i) => i.mirrorOfKey === item.key && i.project === item.project);
4769
6770
  if (mirrors.length) {
4770
- const { s, dl } = section(mirrors.length === 1 ? "Mirror of this asset" : "Mirrors of this asset");
6771
+ const { s, dl } = section2(mirrors.length === 1 ? "Mirror of this asset" : "Mirrors of this asset");
4771
6772
  for (const m of mirrors) row(dl, m.character && m.character.direction ? m.character.direction : "flipped", keyLink(item, m.key));
4772
6773
  pane.append(s);
4773
6774
  }
4774
6775
  if (item.revision || item.revisionParentKey) {
4775
- const { s, dl } = section("Lineage");
6776
+ const { s, dl } = section2("Lineage");
4776
6777
  row(dl, "mode", item.revision ? item.revision.mode : item.asset && item.asset.revision && item.asset.revision.mode);
4777
6778
  if (item.revisionParentKey) row(dl, "parent", keyLink(item, item.revisionParentKey));
4778
6779
  if (item.revision) {
@@ -4817,7 +6818,7 @@
4817
6818
  const reviseKey = "revise:" + item.id;
4818
6819
  const canRevise = canEdit && isRevisable(item);
4819
6820
  if (children.length || canRevise) {
4820
- const { s, dl } = section("Revisions from this asset");
6821
+ const { s, dl } = section2("Revisions from this asset");
4821
6822
  for (const c of children) row(dl, c.revision ? c.revision.mode : "child", keyLink(item, c.key));
4822
6823
  if (canRevise) {
4823
6824
  const revise = el("button", ui.editing === reviseKey ? null : "add", ui.editing === reviseKey ? "Cancel" : "+ New revision");
@@ -4849,7 +6850,7 @@
4849
6850
  pane = tab.details;
4850
6851
  if (item.quality) {
4851
6852
  const q = item.quality;
4852
- const { s, dl } = section("Quality");
6853
+ const { s, dl } = section2("Quality");
4853
6854
  const tone = q.state === "approved" ? "ok" : q.state === "blocked" ? "bad" : "warn";
4854
6855
  const st = el("span", "state-" + tone);
4855
6856
  st.append(el("i", "dot " + tone + " "), document.createTextNode(" " + q.state));
@@ -4895,7 +6896,7 @@
4895
6896
  }
4896
6897
  }
4897
6898
  {
4898
- const { s, dl } = section("Identity");
6899
+ const { s, dl } = section2("Identity");
4899
6900
  if (item.project) row(dl, "project", item.project);
4900
6901
  row(dl, "lock key", item.key, { mono: true, copy: item.key });
4901
6902
  if (item.recordedSpecHash) {
@@ -4952,7 +6953,8 @@
4952
6953
  if (ui.sort !== "key") params.set("sort", ui.sort);
4953
6954
  if (ui.group !== "style") params.set("group", ui.group);
4954
6955
  const query = params.toString();
4955
- const next = location.pathname + (query ? "?" + query : "") + (ui.open ? "#" + encodeURIComponent(ui.open) : "");
6956
+ const open = ui.open ?? ui.model;
6957
+ const next = location.pathname + (query ? "?" + query : "") + (open ? "#" + encodeURIComponent(open) : "");
4956
6958
  if (next !== location.pathname + location.search + location.hash) history.replaceState(null, "", next);
4957
6959
  }
4958
6960
  function syncHash() {
@@ -4979,6 +6981,7 @@
4979
6981
  ui.open = key;
4980
6982
  ui.member = 0;
4981
6983
  ui.zoom = "auto";
6984
+ ui.model = null;
4982
6985
  syncHash();
4983
6986
  const card2 = markActive(key);
4984
6987
  renderDrawer();
@@ -4998,7 +7001,9 @@
4998
7001
  window.addEventListener("hashchange", () => {
4999
7002
  const key = keyFromHash();
5000
7003
  if (key && key !== ui.open && S.snap.items.some((i) => i.id === key)) openItem(key);
7004
+ else if (key && key !== ui.model && S.snap.models.some((m) => m.id === key)) openModel(key);
5001
7005
  else if (!key && ui.open) closeItem();
7006
+ else if (!key && ui.model) closeModel();
5002
7007
  });
5003
7008
  function step(delta) {
5004
7009
  const items = visibleItems();
@@ -5224,8 +7229,8 @@
5224
7229
  actions.append(msg);
5225
7230
  form.append(styleSection, baseSection, loopsSection, portraitSection, priceBox, actions);
5226
7231
  const currentProject = () => {
5227
- const live = S.snap.workspace ? S.snap.workspace.projects : S.snap.project ? [S.snap.project] : [];
5228
- return live.find((pr) => pr.id === project.value) || live.find((pr) => pr.manifestSha256) || projects[0];
7232
+ const live2 = S.snap.workspace ? S.snap.workspace.projects : S.snap.project ? [S.snap.project] : [];
7233
+ return live2.find((pr) => pr.id === project.value) || live2.find((pr) => pr.manifestSha256) || projects[0];
5229
7234
  };
5230
7235
  const projectId = () => workspace ? project.value : null;
5231
7236
  const characterStyles = () => S.snap.styles.filter((s) => s.generator === "character" && s.project === projectId());
@@ -5770,8 +7775,8 @@
5770
7775
  head.append(close);
5771
7776
  box.append(head);
5772
7777
  for (const group of GROUPS) {
5773
- const section2 = el("section");
5774
- section2.append(el("h4", null, group.title));
7778
+ const section3 = el("section");
7779
+ section3.append(el("h4", null, group.title));
5775
7780
  const dl = el("dl");
5776
7781
  for (const [keys, what] of group.keys) {
5777
7782
  const dt = el("dt");
@@ -5781,8 +7786,8 @@
5781
7786
  });
5782
7787
  dl.append(dt, el("dd", null, what));
5783
7788
  }
5784
- section2.append(dl);
5785
- box.append(section2);
7789
+ section3.append(dl);
7790
+ box.append(section3);
5786
7791
  }
5787
7792
  wrap.append(box);
5788
7793
  host.append(wrap);
@@ -5971,6 +7976,11 @@
5971
7976
  closeItem();
5972
7977
  return;
5973
7978
  }
7979
+ if (ui.model) {
7980
+ e.preventDefault();
7981
+ closeModel();
7982
+ return;
7983
+ }
5974
7984
  if (ui.selecting) {
5975
7985
  e.preventDefault();
5976
7986
  setSelecting(false);
@@ -6004,11 +8014,12 @@
6004
8014
  $("group").value = ui.group;
6005
8015
  var initialKey = keyFromHash();
6006
8016
  if (initialKey && S.snap.items.some((i) => i.id === initialKey)) ui.open = initialKey;
8017
+ else if (initialKey && S.snap.models.some((m) => m.id === initialKey)) ui.model = initialKey;
6007
8018
  ui.compare = ui.compare.filter((id) => S.snap.items.some((i) => i.id === id));
6008
8019
  render();
6009
8020
  if (ui.open) document.querySelector(".card.active")?.scrollIntoView({ block: "center" });
6010
8021
  if (GENERATION) pollJobs();
6011
8022
  if (EDITOR) pollEditor();
6012
8023
  if (ui.compare.length >= 2 && !ui.open) openCompare();
6013
- window.__pixelkiln = { S, ui, family: familyState };
8024
+ window.__pixelkiln = { S, ui, family: familyState, model: modelState, thumbs: thumbCount };
6014
8025
  })();