import { MaxRectsPacker } from 'maxrects-packer';
import { unzipSync } from 'fflate';
import { num, text, choice, assert, parseJSON, numeric, source, pixels, canvas, png, json, plain, zip, file, safeName, svgDoc, svgResults, luminance } from './common.js';

export const atlas_pack = /*#__PURE__*/ (() => ({ fields: [num('size', '图集最大边长', 1024, 128, 2048, 128), num('padding', '帧间距', 2, 0, 16), choice('trim', '透明边缘', [['trim', '裁去透明边'], ['keep', '保留原尺寸']])], async run({ images, values: v }) {
  assert(images.length >= 1 && images.length <= 8, '选择1–8张图片。'); const rects = [];
  for (const [i, image] of images.entries()) { const original = source([image]), p = pixels(original); let left = 0, top = 0, right = original.width, bottom = original.height;
    if (v.trim === 'trim') { left = original.width; top = original.height; right = 0; bottom = 0; for (let y = 0; y < p.height; y++) for (let x = 0; x < p.width; x++) if (p.data[(y * p.width + x) * 4 + 3]) { left = Math.min(left, x); top = Math.min(top, y); right = Math.max(right, x + 1); bottom = Math.max(bottom, y + 1); } assert(right > left && bottom > top, `第${i + 1}张全透明,无法裁边。`); }
    const width = right - left, height = bottom - top; assert(width + v.padding * 2 <= v.size && height + v.padding * 2 <= v.size, `第${i + 1}张超过图集可用尺寸。`); rects.push({ width, height, original, left, top, name: `${i + 1}-${safeName(image.file.name)}`, index: i });
  }
  const packer = new MaxRectsPacker(v.size, v.size, v.padding, { smart: true, pot: false, square: false, allowRotation: false, border: v.padding }); packer.addArray(rects); const outputs = [], report = [];
  for (const [i, bin] of packer.bins.entries()) { assert(bin.width <= v.size && bin.height <= v.size, '装箱结果超出尺寸。'); const node = canvas(bin.width, bin.height), ctx = node.getContext('2d'), frames = [];
    for (const r of bin.rects) { ctx.drawImage(r.original, r.left, r.top, r.width, r.height, r.x, r.y, r.width, r.height); frames.push({ name: r.name, x: r.x, y: r.y, width: r.width, height: r.height, sourceWidth: r.original.width, sourceHeight: r.original.height, offsetX: r.left, offsetY: r.top, rotated: false }); }
    const name = `atlas-${i + 1}.png`; outputs.push(await png(node, name)); report.push({ image: name, width: bin.width, height: bin.height, frames });
  }
  return [...outputs, json({ atlases: report, padding: v.padding }, 'atlas.json')];
} }))();
export const atlas_extract = /*#__PURE__*/ (() => ({ fields: [text('frames', '帧坐标JSON(数组或含frames字段)', '[{"name":"part","x":8,"y":6,"width":24,"height":18}]', true)], async run({ images, values: v }) {
  const input = source(images), parsed = parseJSON(v.frames), frames = Array.isArray(parsed) ? parsed : parsed.frames; assert(Array.isArray(frames) && frames.length >= 1 && frames.length <= 100, '需要1–100个帧坐标。'); let total = 0; const entries = [], report = [];
  for (const [i, f] of frames.entries()) { const [x, y, w, h] = ['x', 'y', 'width', 'height'].map((key) => numeric(f[key])); assert([x, y, w, h].every(Number.isInteger) && x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= input.width && y + h <= input.height, `第${i + 1}帧超出图集或不是整数坐标。`); total += w * h; assert(total <= 24e6, '提取总像素超过24MP。'); const node = canvas(w, h), name = `${String(i + 1).padStart(3, '0')}-${safeName(f.name || 'frame')}.png`; node.getContext('2d').drawImage(input, x, y, w, h, 0, 0, w, h); entries.push(await png(node, name)); report.push({ name, x, y, width: w, height: h }); }
  return [await zip(entries, 'atlas-frames.zip'), json(report, 'extracted.json')];
} }))();
export const channel_pack = /*#__PURE__*/ (() => ({ fields: [choice('sample', '每张图取值', [['red', '红通道'], ['luminance', '亮度']])], async run({ images, values: v }) {
  assert(images.length === 4 && images.every((im) => im.width === images[0].width && im.height === images[0].height), '请按R/G/B/A顺序选择4张同尺寸图片。'); const inputs = images.map((im) => pixels(source([im]))), node = canvas(inputs[0].width, inputs[0].height), out = new ImageData(node.width, node.height);
  for (let i = 0; i < out.data.length; i += 4) for (let c = 0; c < 4; c++) { const d = inputs[c].data; out.data[i + c] = v.sample === 'red' ? d[i] : luminance(d[i], d[i + 1], d[i + 2]); }
  node.getContext('2d').putImageData(out, 0, 0); return [await png(node, 'channels.png'), json({ order: images.map((im) => im.file.name), sample: v.sample, note: 'PNG查看器可能用Alpha合成显示;读取纹理时保留原始RGBA通道。' }, 'channels.json')];
} }))();
export const normal_check = /*#__PURE__*/ (() => ({ fields: [num('tolerance', '单位长度容差', .1, .01, .5, .01), choice('hemisphere', '检查Z方向', [['positive', '要求Z非负'], ['both', '允许双向']])], async run({ images, values: v }) {
  const node = source(images), p = pixels(node), out = new ImageData(p.width, p.height); let invalid = 0, count = 0, total = 0, min = Infinity, max = 0;
  for (let i = 0; i < p.data.length; i += 4) { if (!p.data[i + 3]) continue; const x = p.data[i] / 127.5 - 1, y = p.data[i + 1] / 127.5 - 1, z = p.data[i + 2] / 127.5 - 1, length = Math.hypot(x, y, z), bad = Math.abs(length - 1) > v.tolerance || v.hemisphere === 'positive' && z < 0; if (bad) invalid++; count++; total += length; min = Math.min(min, length); max = Math.max(max, length); out.data.set(bad ? [255, 50, 80, 255] : [40, 170, 125, 255], i); }
  assert(count, '图片没有可见像素。'); node.getContext('2d').putImageData(out, 0, 0);
  return [await png(node, 'normal-check.png'), json({ visiblePixels: count, invalidPixels: invalid, invalidRatio: invalid / count, meanLength: total / count, minLength: min, maxLength: max, encoding: 'RGB映射到[-1,1];透明像素跳过' }, 'normal-report.json')];
} }))();
export const obj_uv = /*#__PURE__*/ (() => ({ fields: [num('size', 'UV画布大小', 512, 128, 2048, 128)], async run({ files, values: v }) {
  const value = await files[0].text(); assert(value.length <= 2e6, 'OBJ文本最多2MB。'); const uv = [], faces = []; let missingUV = 0;
  for (const raw of value.split(/\r?\n/)) { const parts = raw.split('#')[0].trim().split(/\s+/); if (parts[0] === 'vt') { assert(parts.length >= 3, 'vt坐标缺少分量。'); uv.push([numeric(parts[1]), numeric(parts[2])]); assert(uv.length <= 20000, 'UV顶点超过20000个。'); }
    else if (parts[0] === 'f') { assert(parts.length >= 4 && parts.length <= 65, '面片需3–64个顶点。'); const indices = parts.slice(1).map((p) => { const token = p.split('/')[1]; if (!token) return null; assert(/^-?\d+$/.test(token) && Number(token) !== 0, 'UV索引无效。'); const index = Number(token); return index < 0 ? uv.length + index : index - 1; }); if (indices.some((n) => n === null)) missingUV++; else faces.push(indices); assert(faces.length + missingUV <= 10000, '面片超过10000个。'); }
  }
  assert(uv.length && faces.length, 'OBJ没有可用的UV坐标及引用面片。'); assert(faces.every((f) => f.every((i) => i >= 0 && i < uv.length)), 'UV索引超出范围。'); assert(uv.every((p) => p.every((n) => n >= -10 && n <= 10)), 'UV坐标超出−10至10范围。');
  const outside = uv.filter(([u, w]) => u < 0 || u > 1 || w < 0 || w > 1).length, body = faces.map((f) => `<polygon points="${f.map((i) => `${uv[i][0] * v.size},${(1 - uv[i][1]) * v.size}`).join(' ')}" fill="#167d68" fill-opacity=".06" stroke="#167d68" stroke-width="1"/>`).join('');
  return [...await svgResults(svgDoc(body, v.size, v.size, 'OBJ UV'), 'uv-layout'), json({ uvVertices: uv.length, uvFaces: faces.length, facesWithoutUV: missingUV, verticesOutsideUnitSquare: outside, coordinates: uv, faces, note: '画布显示0–1 UV区域,超出部分裁切;不加载mtl或纹理。' }, 'uv-report.json')];
} }))();
export const glb_inspect = /*#__PURE__*/ (() => ({ fields: [], async run({ files }) {
  const buffer = await files[0].arrayBuffer(), view = new DataView(buffer); assert(buffer.byteLength >= 20 && view.getUint32(0, true) === 0x46546c67 && view.getUint32(4, true) === 2 && view.getUint32(8, true) === buffer.byteLength, '不是有效GLB 2.0文件或长度不匹配。');
  let offset = 12, data, binaryBytes = 0; const chunks = [];
  while (offset < buffer.byteLength) { assert(offset + 8 <= buffer.byteLength, 'GLB分块头不完整。'); const length = view.getUint32(offset, true), type = view.getUint32(offset + 4, true); assert(length % 4 === 0 && offset + 8 + length <= buffer.byteLength, 'GLB分块长度或对齐错误。');
    if (chunks.length === 0) assert(type === 0x4e4f534a, 'GLB第一块须为JSON。');
    if (type === 0x4e4f534a) { assert(!data && length <= 2e6, 'JSON块重复或超过2MB。'); data = parseJSON(new TextDecoder('utf-8', { fatal: true }).decode(new Uint8Array(buffer, offset + 8, length)).trim()); }
    else if (type === 0x004e4942) { assert(!chunks.some((c) => c.type === type), 'BIN块重复。'); binaryBytes = length; }
    chunks.push({ type, length, offset }); offset += 8 + length;
  }
  assert(data?.asset?.version === '2.0', 'glTF版本必须为2.0。'); const buffers = data.buffers || [];
  for (const [i, b] of buffers.entries()) { assert(Number.isInteger(b.byteLength) && b.byteLength >= 0, 'buffer长度无效。'); if (!b.uri) assert(i === 0 && b.byteLength <= binaryBytes && binaryBytes - b.byteLength <= 3, '内嵌buffer长度与BIN不一致。'); }
  for (const b of data.bufferViews || []) { assert(Number.isInteger(b.buffer) && buffers[b.buffer] && Number.isInteger(b.byteLength) && b.byteLength >= 0 && Number.isInteger(b.byteOffset || 0) && (b.byteOffset || 0) >= 0 && (b.byteOffset || 0) + b.byteLength <= buffers[b.buffer].byteLength, 'bufferView超出buffer边界。'); }
  const references = [...buffers.map((b) => b.uri), ...(data.images || []).map((im) => im.uri)].filter(Boolean);
  return [json({ asset: data.asset, chunks, bytes: buffer.byteLength, binaryBytes, meshes: (data.meshes || []).map((m) => ({ name: m.name, primitives: m.primitives?.length || 0 })), nodes: data.nodes?.length || 0, materials: (data.materials || []).map((m) => ({ name: m.name, alphaMode: m.alphaMode || 'OPAQUE', doubleSided: Boolean(m.doubleSided) })), textures: data.textures?.length || 0, animations: data.animations?.length || 0, extensions: data.extensionsUsed || [], references, note: '检查容器、JSON与buffer边界,不解码网格或纹理,不验证所有glTF语义,不访问外部引用。' }, 'glb-report.json')];
} }))();
function centralDirectory(bytes) {
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); let end = -1;
  for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 65557); i--) if (view.getUint32(i, true) === 0x06054b50 && i + 22 + view.getUint16(i + 20, true) === bytes.length) { end = i; break; }
  assert(end >= 0, 'ZIP尾目录缺失或损坏。'); const count = view.getUint16(end + 10, true), start = view.getUint32(end + 16, true), size = view.getUint32(end + 12, true);
  assert(view.getUint16(end + 4, true) === 0 && view.getUint16(end + 6, true) === 0 && view.getUint16(end + 8, true) === count && count >= 1 && count <= 100 && start + size === end, '仅支持单卷非ZIP64文件,最多100项。');
  let offset = start, total = 0; const entries = [], names = new Set();
  for (let i = 0; i < count; i++) {
    assert(offset + 46 <= end && view.getUint32(offset, true) === 0x02014b50, 'ZIP中央目录损坏。'); const flags = view.getUint16(offset + 8, true), method = view.getUint16(offset + 10, true), crc = view.getUint32(offset + 16, true), compressed = view.getUint32(offset + 20, true), original = view.getUint32(offset + 24, true), nameLength = view.getUint16(offset + 28, true), extra = view.getUint16(offset + 30, true), comment = view.getUint16(offset + 32, true), attrs = view.getUint32(offset + 38, true), local = view.getUint32(offset + 42, true);
    assert(offset + 46 + nameLength + extra + comment <= end && !(flags & 1) && [0, 8].includes(method) && view.getUint16(offset + 34, true) === 0 && (attrs >>> 16 & 0xf000) !== 0xa000, '不支持加密、跨卷、链接或此压缩方法。');
    const nameBytes = bytes.slice(offset + 46, offset + 46 + nameLength); let name; try { name = new TextDecoder('utf-8', { fatal: true }).decode(nameBytes); } catch { throw new Error('ZIP文件名需使用UTF-8。'); }
    assert(name.length && name.length <= 200 && !/[\\:\x00-\x1f]/.test(name) && !name.startsWith('/') && !name.split('/').some((s) => s === '.' || s === '..') && !names.has(name), 'ZIP包含不安全或重复路径。'); names.add(name); total += original; assert(total <= 64 * 1024 * 1024 && original <= 32 * 1024 * 1024, 'ZIP解压总量最多64MB,单项最多32MB。');
    assert(local + 30 <= start && view.getUint32(local, true) === 0x04034b50 && view.getUint16(local + 6, true) === flags && view.getUint16(local + 8, true) === method, 'ZIP本地头与目录不一致。'); const localName = view.getUint16(local + 26, true), localExtra = view.getUint16(local + 28, true), dataStart = local + 30 + localName + localExtra; assert(dataStart + compressed <= start && localName === nameLength && nameBytes.every((n, j) => bytes[local + 30 + j] === n), 'ZIP数据越界或名称不一致。');
    entries.push({ name, compressedBytes: compressed, originalBytes: original, crc32: crc, method, directory: name.endsWith('/') }); offset += 46 + nameLength + extra + comment;
  }
  assert(offset === end, 'ZIP目录大小不一致。'); return { entries, total };
}
function crc32(bytes) { let crc = 0xffffffff; for (const byte of bytes) { crc ^= byte; for (let bit = 0; bit < 8; bit++) crc = crc >>> 1 ^ (crc & 1 ? 0xedb88320 : 0); } return (crc ^ 0xffffffff) >>> 0; }
export const zip_inspect = /*#__PURE__*/ (() => ({ fields: [choice('mode', '操作', [['list', '检查目录'], ['extract', '检查并提取']]), choice('kind', '提取范围', [['all', '全部文件'], ['images', '常见图片'], ['text', '文本文档']])], async run({ files, values: v }) {
  const bytes = new Uint8Array(await files[0].arrayBuffer()), report = centralDirectory(bytes); if (v.mode === 'list') return [json({ ...report, integrity: '目录与边界已检查;未解压时不验证CRC。' }, 'zip-directory.json')];
  const selected = report.entries.filter((e) => !e.directory && (v.kind === 'all' || (v.kind === 'images' ? /\.(png|jpg|jpeg|webp|gif|svg)$/i : /\.(txt|md|csv|json|xml)$/i).test(e.name))); assert(selected.length, '所选类型没有可提取文件。'); const wanted = new Map(selected.map((e) => [e.name, e])); let expanded; try { expanded = unzipSync(bytes, { filter: (f) => { const record = wanted.get(f.name); if (!record) return false; assert(f.originalSize === record.originalBytes && f.size === record.compressedBytes, 'ZIP解码目录不一致。'); return true; } }); } catch { throw new Error('ZIP解压失败或目录不一致。'); }
  const entries = []; for (const record of selected) { const data = expanded[record.name]; assert(data && data.length === record.originalBytes && crc32(data) === record.crc32, 'ZIP长度或CRC校验失败。'); entries.push(file(new Blob([data]), record.name)); }
  return [await zip(entries, 'selected-files.zip'), json({ ...report, extracted: selected.map((e) => e.name), integrity: '提取文件长度与CRC通过' }, 'zip-directory.json')];
} }))();
export const image_ascii = /*#__PURE__*/ (() => ({ fields: [num('columns', '字符列数', 64, 8, 160), text('ramp', '暗→亮字符序列', '@%#*+=-:. '), choice('invert', '亮度方向', [['normal', '原亮度'], ['invert', '反向']])], async run({ images, values: v }) {
  const input = source(images), ramp = [...v.ramp]; assert(ramp.length >= 2 && ramp.length <= 30 && !/[\r\n\t]/.test(v.ramp), '字符序列需要2–30个单行字符。'); const rows = Math.max(1, Math.round(input.height / input.width * v.columns * .5)); assert(rows <= 200, '输出超过200行,请减少列数。');
  const small = canvas(v.columns, rows, '#ffffff'); small.getContext('2d').drawImage(input, 0, 0, v.columns, rows); const p = pixels(small), lines = [];
  for (let y = 0; y < rows; y++) { let line = ''; for (let x = 0; x < v.columns; x++) { const i = (y * v.columns + x) * 4, l = luminance(...p.data.slice(i, i + 3)) / 255, ratio = v.invert === 'invert' ? 1 - l : l; line += ramp[Math.min(ramp.length - 1, Math.floor(ratio * ramp.length))]; } lines.push(line); }
  const out = canvas(v.columns * 10 + 32, rows * 20 + 32, '#ffffff'), ctx = out.getContext('2d'); ctx.font = '16px monospace'; ctx.fillStyle = '#183f32'; lines.forEach((line, i) => ctx.fillText(line, 16, 32 + i * 20));
  return [plain(lines.join('\n'), 'ascii.txt'), await png(out, 'ascii.png')];
} }))();