import { Delaunay, contours, geoPath, geoIdentity } from 'd3';
import { num, text, choice, color, assert, parseJSON, csvRows, numeric, seeded, source, pixels, canvas, png, json, svgDoc, svgResults, label } from './common.js';
const seed = () => num('seed', '随机种子', 42, 0, 1000000);
const stroke = () => color('stroke', '线条颜色', '#167d68');
export const maze_art = /*#__PURE__*/ (() => ({ fields: [num('columns', '列数', 16, 4, 40), num('rows', '行数', 12, 4, 40), seed(), stroke()], async run({ values: v }) {
  const random = seeded(v.seed), cells = Array.from({ length: v.columns * v.rows }, () => ({ visited: false, walls: [1, 1, 1, 1] })), stack = [0], directions = [[0, -1], [1, 0], [0, 1], [-1, 0]]; cells[0].visited = true;
  while (stack.length) { const i = stack.at(-1), x = i % v.columns, y = Math.floor(i / v.columns), options = directions.map(([dx, dy], d) => ({ x: x + dx, y: y + dy, d })).filter((n) => n.x >= 0 && n.x < v.columns && n.y >= 0 && n.y < v.rows && !cells[n.y * v.columns + n.x].visited); if (!options.length) { stack.pop(); continue; } const n = options[Math.floor(random() * options.length)], next = n.y * v.columns + n.x; cells[i].walls[n.d] = 0; cells[next].walls[(n.d + 2) % 4] = 0; cells[next].visited = true; stack.push(next); }
  const parent = new Int32Array(cells.length).fill(-1), queue = [0]; parent[0] = 0;
  for (let q = 0; q < queue.length; q++) { const i = queue[q]; directions.forEach(([dx, dy], d) => { const x = i % v.columns + dx, y = Math.floor(i / v.columns) + dy, n = y * v.columns + x; if (!cells[i].walls[d] && parent[n] === -1) { parent[n] = i; queue.push(n); } }); }
  const solution = [cells.length - 1]; while (solution.at(-1) !== 0) solution.push(parent[solution.at(-1)]); solution.reverse();
  const size = Math.min(600 / v.columns, 440 / v.rows), w = v.columns * size + 40, h = v.rows * size + 40; let lines = '';
  cells.forEach((cell, i) => { const x = 20 + i % v.columns * size, y = 20 + Math.floor(i / v.columns) * size; if (cell.walls[0] && i !== 0) lines += `M${x} ${y}h${size}`; if (cell.walls[3]) lines += `M${x} ${y}v${size}`; if (i % v.columns === v.columns - 1) lines += `M${x + size} ${y}v${size}`; if (i >= cells.length - v.columns && i !== cells.length - 1) lines += `M${x} ${y + size}h${size}`; });
  const body = `<path d="${lines}" fill="none" stroke="${v.stroke}" stroke-width="2"/>`, route = solution.map((i) => [20 + (i % v.columns + .5) * size, 20 + (Math.floor(i / v.columns) + .5) * size]);
  return [...await svgResults(svgDoc(body, w, h, '迷宫'), 'maze'), ...await svgResults(svgDoc(body + `<polyline points="${route.map((p) => p.join(',')).join(' ')}" fill="none" stroke="#d36b48" stroke-width="3"/>`, w, h, '迷宫解答'), 'solution', false), json({ columns: v.columns, rows: v.rows, seed: v.seed, walls: cells.map((c) => c.walls), solution }, 'maze.json')];
} }))();
export const parametric_art = /*#__PURE__*/ (() => ({ fields: [choice('curve', '曲线', [['rose', '玫瑰线'], ['lissajous', '李萨如'], ['hypotrochoid', '内旋轮线']]), num('a', '参数A', 5, 1, 12), num('b', '参数B', 3, 1, 12), num('points', '采样点数', 1500, 100, 5000, 100), stroke()], async run({ values: v }) {
  const points = Array.from({ length: v.points }, (_, i) => { const t = i / (v.points - 1) * Math.PI * 2 * (v.curve === 'hypotrochoid' ? v.b : 1); let x, y;
    if (v.curve === 'rose') { const r = Math.cos(v.a * t); x = r * Math.cos(t); y = r * Math.sin(t); } else if (v.curve === 'lissajous') { x = Math.sin(v.a * t + Math.PI / 2); y = Math.sin(v.b * t); } else { const R = v.a + v.b, r = v.b, d = r * .65; x = ((R - r) * Math.cos(t) + d * Math.cos((R - r) / r * t)) / (R - r + d); y = ((R - r) * Math.sin(t) - d * Math.sin((R - r) / r * t)) / (R - r + d); } return [320 + x * 260, 260 + y * 210]; });
  return [...await svgResults(svgDoc(`<polyline points="${points.map((p) => p.join(',')).join(' ')}" fill="none" stroke="${v.stroke}" stroke-width="1.5"/>`, 640, 520, '参数曲线'), 'parametric'), json({ curve: v.curve, a: v.a, b: v.b, points }, 'curve.json')];
} }))();
export const fractal_art = /*#__PURE__*/ (() => ({ fields: [choice('mode', '分形', [['mandelbrot', 'Mandelbrot'], ['julia', 'Julia']]), num('size', '图像边长', 384, 128, 768, 128), num('iterations', '迭代上限', 100, 20, 400, 10), num('zoom', '放大倍率', 1, 1, 100, .5), num('centerX', '中心实部', -.5, -2, 2, .01), num('centerY', '中心虚部', 0, -2, 2, .01)], async run({ values: v }) {
  const node = canvas(v.size, v.size), out = new ImageData(v.size, v.size); let inside = 0;
  for (let y = 0; y < v.size; y++) { for (let x = 0; x < v.size; x++) { const re = v.centerX + (x / (v.size - 1) - .5) * 3.2 / v.zoom, im = v.centerY + (y / (v.size - 1) - .5) * 3.2 / v.zoom; let zr = v.mode === 'julia' ? re : 0, zi = v.mode === 'julia' ? im : 0, cr = v.mode === 'julia' ? -.7 : re, ci = v.mode === 'julia' ? .27015 : im, i = 0; while (zr * zr + zi * zi <= 4 && i < v.iterations) { const temp = zr * zr - zi * zi + cr; zi = 2 * zr * zi + ci; zr = temp; i++; } const index = (y * v.size + x) * 4; if (i === v.iterations) { inside++; out.data.set([20, 38, 33, 255], index); } else { const t = Math.sqrt(i / v.iterations); out.data.set([40 + 210 * t, 80 + 140 * t, 130 + 80 * Math.sin(t * Math.PI), 255], index); } } if (y % 32 === 0) await new Promise((r) => setTimeout(r, 0)); }
  node.getContext('2d').putImageData(out, 0, 0); return [await png(node, 'fractal.png'), json({ ...v, insideAtIterationLimit: inside, totalPixels: v.size * v.size, juliaConstant: v.mode === 'julia' ? [-.7, .27015] : null }, 'fractal.json')];
} }))();
export const lsystem_art = /*#__PURE__*/ (() => ({ fields: [text('axiom', '初始串', 'F'), text('rules', '替换规则JSON', '{"F":"F[+F]F[-F]F"}', true), num('iterations', '替换次数', 4, 0, 7), num('angle', '转向角度', 25, 1, 180), stroke()], async run({ values: v }) {
  const rules = parseJSON(v.rules, 50); assert(rules && !Array.isArray(rules) && typeof rules === 'object', '规则须为JSON对象。'); for (const [k, val] of Object.entries(rules)) assert(/^[A-Z]$/.test(k) && typeof val === 'string' && /^[A-Z+\-\[\]]{0,100}$/.test(val), '规则键为单个大写字母,值仅允许大写字母、+、−和方括号。'); assert(/^[A-Z+\-\[\]]{1,100}$/.test(v.axiom), '初始串字符无效。');
  let program = v.axiom; for (let i = 0; i < v.iterations; i++) { assert([...program].reduce((n, c) => n + (rules[c]?.length ?? 1), 0) <= 50000, '展开长度超过50000,请降低次数。'); program = [...program].map((c) => rules[c] ?? c).join(''); }
  let x = 0, y = 0, angle = -90; const stack = [], segments = [], points = [[0, 0]];
  for (const c of program) { if (c === 'F') { const nx = x + Math.cos(angle * Math.PI / 180), ny = y + Math.sin(angle * Math.PI / 180); segments.push([[x, y], [nx, ny]]); x = nx; y = ny; points.push([x, y]); } else if (c === '+') angle += v.angle; else if (c === '-') angle -= v.angle; else if (c === '[') { assert(stack.length < 500, '分支嵌套过深。'); stack.push([x, y, angle]); } else if (c === ']') { assert(stack.length, '方括号不配对。'); [x, y, angle] = stack.pop(); } }
  assert(!stack.length && segments.length, '方括号不配对或没有F绘图指令。'); const xs = points.map((p) => p[0]), ys = points.map((p) => p[1]), bounds = [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)], scale = Math.min(640 / Math.max(.01, bounds[2] - bounds[0]), 460 / Math.max(.01, bounds[3] - bounds[1]));
  const d = segments.map(([a, b]) => `M${a}L${b}`).join(''); const body = `<g transform="translate(${30 - bounds[0] * scale} ${30 - bounds[1] * scale}) scale(${scale})"><path d="${d}" fill="none" stroke="${v.stroke}" stroke-width="${1.3 / scale}"/></g>`;
  return [...await svgResults(svgDoc(body, 700, 520, 'L系统'), 'lsystem'), json({ ...v, expandedLength: program.length, segments: segments.length, bounds }, 'lsystem.json')];
} }))();
export const contour_art = /*#__PURE__*/ (() => ({ fields: [text('grid', '数值网格CSV(无列名)', '0,1,2,1,0\n1,3,5,3,1\n2,5,9,5,2\n1,3,5,3,1\n0,1,2,1,0', true), num('levels', '等值层数', 6, 2, 20), stroke()], async run({ values: v }) {
  const rows = csvRows(v.grid, 100), height = rows.length, width = rows[0].length; assert(width >= 2 && height >= 2, '网格至少2行2列。'); const values = rows.flat().map((n) => numeric(n)), min = Math.min(...values), max = Math.max(...values); assert(max > min, '网格不能全为同一数值。'); const thresholds = Array.from({ length: v.levels }, (_, i) => min + (max - min) * (i + 1) / (v.levels + 1)), shapes = contours().size([width, height]).thresholds(thresholds)(values), scale = Math.min(600 / width, 420 / height), path = geoPath(geoIdentity().scale(scale).translate([20, 20]));
  const body = shapes.map((shape, i) => `<path d="${path(shape)}" fill="${v.stroke}" fill-opacity="${.08 + .55 * i / v.levels}" stroke="${v.stroke}" stroke-width="1"/>`).join('');
  return [...await svgResults(svgDoc(body, width * scale + 40, height * scale + 40, '等值线'), 'contours'), json({ width, height, thresholds, contours: shapes }, 'contours.geojson')];
} }))();
export const package_net = /*#__PURE__*/ (() => ({ fields: [num('length', '盒长(mm)', 80, 20, 200), num('width', '盒宽(mm)', 50, 15, 150), num('height', '盒高(mm)', 100, 20, 250), num('tab', '侧粘边(mm)', 10, 3, 30)], async run({ values: v }) {
  assert(v.tab < Math.min(v.length, v.width) / 2, '粘边应小于最短侧边的一半。'); const L = v.length, W = v.width, H = v.height, T = v.tab, flap = W / 2, m = 10, xs = [0, L, L + W, 2 * L + W, 2 * (L + W)], totalW = xs[4] + T + m * 2, totalH = H + W + m * 2; let cuts = '', folds = '';
  // Four side panels with half-width top/bottom flaps and a side glue tab.
  for (let i = 0; i < 4; i++) { const a = xs[i], b = xs[i + 1], inset = Math.min(3, (b - a) / 10); cuts += `M${a} ${flap}L${a + inset} 0H${b - inset}L${b} ${flap} M${a} ${flap + H}L${a + inset} ${W + H}H${b - inset}L${b} ${flap + H}`; folds += `M${a} ${flap}H${b}M${a} ${flap + H}H${b}`; if (i) folds += `M${a} ${flap}V${flap + H}`; }
  cuts += `M0 ${flap}V${flap + H} M${xs[4]} ${flap}L${xs[4] + T} ${flap + 5}V${flap + H - 5}L${xs[4]} ${flap + H}`; folds += `M${xs[4]} ${flap}V${flap + H}`;
  const body = `<g transform="translate(${m} ${m})"><path d="${cuts}" fill="none" stroke="#151515" stroke-width=".3"/><path d="${folds}" fill="none" stroke="#167d68" stroke-width=".3" stroke-dasharray="2 1"/></g>`;
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${totalW}mm" height="${totalH}mm" viewBox="0 0 ${totalW} ${totalH}">${body}</svg>`;
  return [...await svgResults(svg, 'box-net'), json({ lengthMM: L, widthMM: W, heightMM: H, glueTabMM: T, sheetMM: [totalW, totalH], foldLines: 'green dashed', cutLines: 'black solid', note: '半宽上下封口襟片的直角纸盒。按100%比例打印,需胶带或胶水封口;未计材料厚度和公差。' }, 'box-dimensions.json')];
} }))();
export const jigsaw_template = /*#__PURE__*/ (() => ({ fields: [num('columns', '拼图列数', 4, 2, 12), num('rows', '拼图行数', 3, 2, 12), seed()], async run({ values: v }) {
  const random = seeded(v.seed), w = 600, h = 420, cw = w / v.columns, ch = h / v.rows, amplitude = Math.min(cw, ch) * .16, paths = [];
  function edge(x, y, dx, dy) { const sign = random() < .5 ? -1 : 1, nx = -dy / Math.hypot(dx, dy) * amplitude * sign, ny = dx / Math.hypot(dx, dy) * amplitude * sign; return `M${x} ${y} L${x + dx * .35} ${y + dy * .35} C${x + dx * .4 + nx} ${y + dy * .4 + ny} ${x + dx * .4 + nx} ${y + dy * .4 + ny} ${x + dx * .5 + nx} ${y + dy * .5 + ny} C${x + dx * .6 + nx} ${y + dy * .6 + ny} ${x + dx * .6 + nx} ${y + dy * .6 + ny} ${x + dx * .65} ${y + dy * .65} L${x + dx} ${y + dy}`; }
  for (let row = 1; row < v.rows; row++) for (let col = 0; col < v.columns; col++) paths.push(edge(col * cw, row * ch, cw, 0));
  for (let col = 1; col < v.columns; col++) for (let row = 0; row < v.rows; row++) paths.push(edge(col * cw, row * ch, 0, ch));
  const body = `<g transform="translate(20 20)"><rect width="${w}" height="${h}" fill="none" stroke="#183f32"/><path d="${paths.join(' ')}" fill="none" stroke="#183f32" stroke-width="1.2"/></g>`;
  return [...await svgResults(svgDoc(body, w + 40, h + 40, '拼图刀模'), 'jigsaw'), json({ rows: v.rows, columns: v.columns, pieces: v.rows * v.columns, seed: v.seed, sharedEdges: paths.length, note: '内部边界仅绘制一次,相邻拼块共享同一曲线;不含切缝补偿。' }, 'jigsaw.json')];
} }))();
export const low_poly = /*#__PURE__*/ (() => ({ fields: [num('points', '随机采样点数', 150, 20, 1500, 10), seed()], async run({ images, values: v }) {
  const input = source(images), p = pixels(input), w = input.width, h = input.height; assert(w >= 4 && h >= 4, '图片至少4×4像素。'); const random = seeded(v.seed), points = [[0, 0], [w, 0], [w, h], [0, h]];
  for (let i = 0; i < v.points; i++) points.push([random() * w, random() * h]); const triangles = [...Delaunay.from(points).trianglePolygons()], node = canvas(w, h), ctx = node.getContext('2d'); let svg = '';
  for (const tri of triangles) { const x = Math.min(w - 1, Math.max(0, Math.floor((tri[0][0] + tri[1][0] + tri[2][0]) / 3))), y = Math.min(h - 1, Math.max(0, Math.floor((tri[0][1] + tri[1][1] + tri[2][1]) / 3))), i = (y * w + x) * 4, rgba = `rgba(${p.data[i]},${p.data[i + 1]},${p.data[i + 2]},${p.data[i + 3] / 255})`;
    ctx.beginPath(); tri.forEach(([x, y], i) => i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)); ctx.closePath(); ctx.fillStyle = rgba; ctx.fill(); svg += `<polygon points="${tri.map((q) => q.join(',')).join(' ')}" fill="${rgba}"/>`;
  }
  return [await png(node, 'low-poly.png'), ...await svgResults(`<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${svg}</svg>`, 'low-poly', false), json({ points: points.length, triangles: triangles.length, seed: v.seed, sampling: '每个三角形重心像素取色,保留该点Alpha。' }, 'low-poly.json')];
} }))();