geo-figure-mcp 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # geo-figure-mcp — 지리 시험용 지도·그래프 만들기 (0.2)
1
+ # geo-figure-mcp — 지리 시험용 지도·그래프 만들기 (0.2.1)
2
2
 
3
3
  만든 사람: 김한솔 (한백고등학교 지리 교사)
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "geo-figure-mcp",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "지리 시험용 지도·그래프를 도형 하나하나 고칠 수 있는 PPTX·HWPX로 만드는 MCP 서버",
5
5
  "author": "김한솔 (한백고등학교)",
6
6
  "mcpName": "io.github.skyblue3925-svg/geo-figure-mcp",
package/server.json CHANGED
@@ -4,12 +4,12 @@
4
4
  "title": "Geo Figure (지리 시험 지도·그래프)",
5
5
  "description": "지리 시험용 지도·그래프를 실제 통계로, 도형 하나하나 고칠 수 있는 PPTX·HWPX로 만든다.",
6
6
  "repository": { "url": "https://github.com/skyblue3925-svg/geo-figure-mcp", "source": "github" },
7
- "version": "0.2.0",
7
+ "version": "0.2.1",
8
8
  "packages": [
9
9
  {
10
10
  "registryType": "npm",
11
11
  "identifier": "geo-figure-mcp",
12
- "version": "0.2.0",
12
+ "version": "0.2.1",
13
13
  "transport": { "type": "stdio" },
14
14
  "environmentVariables": [
15
15
  { "name": "GEO_FIGURE_OUT", "description": "만든 파일을 저장할 폴더 (기본: 문서/지리시험자료)", "isRequired": false, "isSecret": false }
package/src/build.js CHANGED
@@ -1,70 +1,73 @@
1
- // 그림 명세 → 장면 → PPTX·HWPX 파일
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import os from 'node:os';
5
- import { figure, withFooter, shift, bounds, S, DEFAULT_STYLE } from './scene.js';
6
- import { makeMap } from './maps.js';
7
- import { CHARTS } from './charts.js';
8
- import { contourMap, profileChart, landformDiagram, fetchGrid, fetchProfile, DEM_CITE } from './terrain.js';
9
- import { buildPptx } from './pptx.js';
10
- import { buildHwpx } from './hwpx.js';
11
-
12
- const STYLE_FILE = path.join(os.homedir(), '.geo-figure-mcp', 'style.json');
13
- export function loadStyle() { try { return { ...DEFAULT_STYLE, ...JSON.parse(fs.readFileSync(STYLE_FILE, 'utf8')) }; } catch { return { ...DEFAULT_STYLE }; } }
14
- export function saveStyle(patch) {
15
- const s = { ...loadStyle(), ...patch };
16
- fs.mkdirSync(path.dirname(STYLE_FILE), { recursive: true });
17
- fs.writeFileSync(STYLE_FILE, JSON.stringify(s, null, 1));
18
- return s;
19
- }
20
-
21
- async function part(p, st, cites) {
22
- if (p.map?.type === 'contour') {
23
- const grid = p.map.grid || await fetchGrid(p.map.bbox, p.map.resolution || 60);
24
- cites.add(DEM_CITE);
25
- return contourMap({ ...p.map, grid }, st);
26
- }
27
- if (p.map) {
28
- // 경계 자료의 출처 표시 의무(SGIS 공공누리 1유형 → vuski/admdongkor CC BY 4.0, Natural Earth)
29
- cites.add(p.map.region === 'korea' ? '지도: 통계청 SGIS(vuski/admdongkor 가공, CC BY 4.0)' : '지도: Natural Earth');
30
- return makeMap(p.map, st);
31
- }
32
- if (p.chart?.type === 'profile') {
33
- const points = p.chart.points || await fetchProfile(p.chart.from, p.chart.to, p.chart.samples || 120);
34
- if (!p.chart.points) cites.add(DEM_CITE);
35
- return profileChart({ ...p.chart, points }, st);
36
- }
37
- if (p.chart?.type === 'landform') return landformDiagram(p.chart, st);
38
- const fn = CHARTS[p.chart?.type];
39
- if (!fn) throw new Error(`모르는 그래프 종류: ${p.chart?.type}. 쓸 수 있는 것: ${Object.keys(CHARTS).join(', ')}`);
40
- return fn(p.chart, st);
41
- }
42
-
43
- // spec: { title, parts:[{ caption:'(가)', map:{...} | chart:{type,...} }], layout:'row'|'column', source, notes:[] }
44
- export async function makeFigure(spec, st = loadStyle()) {
45
- const cites = new Set();
46
- const parts = spec.parts || [spec];
47
- const placed = [];
48
- let x = 0, y = 0;
49
- const gap = 6;
50
- const row = (spec.layout || (parts.length > 1 ? 'row' : 'column')) === 'row';
51
- for (const p of parts) {
52
- let items = await part(p, st, cites);
53
- const b = bounds(items);
54
- items = shift(items, -b.x, -b.y + (p.caption ? 5 : 0));
55
- if (p.caption) items.unshift(S.text(b.w / 2, 1.8, p.caption, { size: st.size, name: '자료 이름' }));
56
- placed.push(S.group(p.caption ? `자료 ${p.caption}` : '자료', shift(items, x, y)));
57
- if (row) x += b.w + gap; else y += b.h + (p.caption ? 5 : 0) + gap;
58
- }
59
- const source = [spec.source, ...[...cites].filter((c) => !(spec.source || '').includes(c.slice(0, 14)))].filter(Boolean).join('; ');
60
- return withFooter(figure({ title: spec.title, items: placed, source, notes: spec.notes }), st);
61
- }
62
-
63
- export function exportFigures(figs, { outDir, name = '지리자료', formats = ['pptx', 'hwpx'], answerKey, style } = {}) {
64
- const st = style || loadStyle();
65
- fs.mkdirSync(outDir, { recursive: true });
66
- const files = [];
67
- if (formats.includes('pptx')) { const f = path.join(outDir, `${name}.pptx`); fs.writeFileSync(f, buildPptx(figs, { style: st, keyText: answerKey })); files.push(f); }
68
- if (formats.includes('hwpx')) { const f = path.join(outDir, `${name}.hwpx`); fs.writeFileSync(f, buildHwpx(figs, { style: st, keyText: answerKey })); files.push(f); }
69
- return files;
70
- }
1
+ // 그림 명세 → 장면 → PPTX·HWPX 파일
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import { figure, withFooter, shift, bounds, S, DEFAULT_STYLE } from './scene.js';
6
+ import { makeMap } from './maps.js';
7
+ import { CHARTS } from './charts.js';
8
+ import { contourMap, profileChart, landformDiagram, fetchGrid, fetchProfile, DEM_CITE } from './terrain.js';
9
+ import { buildPptx } from './pptx.js';
10
+ import { buildHwpx } from './hwpx.js';
11
+
12
+ const STYLE_FILE = path.join(os.homedir(), '.geo-figure-mcp', 'style.json');
13
+ export function loadStyle() { try { return { ...DEFAULT_STYLE, ...JSON.parse(fs.readFileSync(STYLE_FILE, 'utf8')) }; } catch { return { ...DEFAULT_STYLE }; } }
14
+ export function saveStyle(patch) {
15
+ const s = { ...loadStyle(), ...patch };
16
+ fs.mkdirSync(path.dirname(STYLE_FILE), { recursive: true });
17
+ fs.writeFileSync(STYLE_FILE, JSON.stringify(s, null, 1));
18
+ return s;
19
+ }
20
+
21
+ async function part(p, st, cites) {
22
+ if (p.map?.type === 'contour') {
23
+ const grid = p.map.grid || await fetchGrid(p.map.bbox, p.map.resolution || 60);
24
+ cites.add(DEM_CITE);
25
+ return contourMap({ ...p.map, grid }, st);
26
+ }
27
+ if (p.map) {
28
+ // 경계 자료의 출처 표시 의무(SGIS 공공누리 1유형 → vuski/admdongkor CC BY 4.0, Natural Earth)
29
+ cites.add(p.map.region === 'korea' ? '지도: 통계청 SGIS(vuski/admdongkor 가공, CC BY 4.0)' : '지도: Natural Earth');
30
+ return makeMap(p.map, st);
31
+ }
32
+ if (p.chart?.type === 'profile') {
33
+ const points = p.chart.points || await fetchProfile(p.chart.from, p.chart.to, p.chart.samples || 120);
34
+ if (!p.chart.points) cites.add(DEM_CITE);
35
+ return profileChart({ ...p.chart, points }, st);
36
+ }
37
+ if (p.chart?.type === 'landform') return landformDiagram(p.chart, st);
38
+ const fn = CHARTS[p.chart?.type];
39
+ if (!fn) throw new Error(`모르는 그래프 종류: ${p.chart?.type}. 쓸 수 있는 것: ${Object.keys(CHARTS).join(', ')}`);
40
+ return fn(p.chart, st);
41
+ }
42
+
43
+ // spec: { title, parts:[{ caption:'(가)', map:{...} | chart:{type,...} }], layout:'row'|'column', source, notes:[] }
44
+ export async function makeFigure(spec, st = loadStyle()) {
45
+ const cites = new Set();
46
+ const parts = spec.parts || [spec];
47
+ const placed = [];
48
+ let x = 0, y = 0;
49
+ const gap = 6;
50
+ const row = (spec.layout || (parts.length > 1 ? 'row' : 'column')) === 'row';
51
+ for (const p of parts) {
52
+ let items = await part(p, st, cites);
53
+ const b = bounds(items);
54
+ items = shift(items, -b.x, -b.y + (p.caption ? 5 : 0));
55
+ if (p.caption) items.unshift(S.text(b.w / 2, 1.8, p.caption, { size: st.size, name: '자료 이름' }));
56
+ placed.push(S.group(p.caption ? `자료 ${p.caption}` : '자료', shift(items, x, y)));
57
+ if (row) x += b.w + gap; else y += b.h + (p.caption ? 5 : 0) + gap;
58
+ }
59
+ // 묶음을 한 겹으로 편다: 파일에서는 그림 전체가 묶음 하나이고, 한 번 풀면 시군구·기호·선·범례가 모두 따로 움직인다
60
+ const flat = (arr) => arr.flatMap((it) => (it.t === 'group' ? flat(it.items) : [it]));
61
+ if (spec.grouping !== 'nested') placed.splice(0, placed.length, ...flat(placed));
62
+ const source = [spec.source, ...[...cites].filter((c) => !(spec.source || '').includes(c.slice(0, 14)))].filter(Boolean).join('; ');
63
+ return withFooter(figure({ title: spec.title, items: placed, source, notes: spec.notes }), st);
64
+ }
65
+
66
+ export function exportFigures(figs, { outDir, name = '지리자료', formats = ['pptx', 'hwpx'], answerKey, style } = {}) {
67
+ const st = style || loadStyle();
68
+ fs.mkdirSync(outDir, { recursive: true });
69
+ const files = [];
70
+ if (formats.includes('pptx')) { const f = path.join(outDir, `${name}.pptx`); fs.writeFileSync(f, buildPptx(figs, { style: st, keyText: answerKey })); files.push(f); }
71
+ if (formats.includes('hwpx')) { const f = path.join(outDir, `${name}.hwpx`); fs.writeFileSync(f, buildHwpx(figs, { style: st, keyText: answerKey })); files.push(f); }
72
+ return files;
73
+ }
package/src/charts.js CHANGED
@@ -1,177 +1,190 @@
1
- // 수능형 그래프 → 장면 도형. 눈금선 최소, 장식 없음, 흑백 구분, 범례는 그래프 위.
2
- import { S, SERIES_FILLS, DEFAULT_STYLE, textWidth } from './scene.js';
3
-
4
- export function niceTicks(min, max, n = 5) {
5
- if (min === max) max = min + 1;
6
- const span = max - min, raw = span / n, mag = 10 ** Math.floor(Math.log10(raw));
7
- const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => span / s <= n) || 10 * mag;
8
- const lo = Math.floor(min / step) * step, hi = Math.ceil(max / step) * step;
9
- const t = [];
10
- for (let v = lo; v <= hi + step / 1e6; v += step) t.push(+v.toFixed(10));
11
- return t;
12
- }
13
- const fmt = (v) => (Math.abs(v) >= 1000 ? v.toLocaleString('en-US') : String(+v.toFixed(2)));
14
-
15
- function legend(series, x, y, st, fills = SERIES_FILLS) {
16
- const items = [];
17
- let cx = x;
18
- series.forEach((s, i) => {
19
- items.push(S.rect(cx, y - 1.4, 2.8, 2.8, { fill: s.fill || fills[i % fills.length], stroke: 0.2, name: `범례 칸 ${s.name}` }));
20
- items.push(S.text(cx + 3.6, y, s.name, { size: st.small, anchor: 'l', name: `범례 ${s.name}` }));
21
- cx += 3.6 + textWidth(s.name, st.small) + 3;
22
- });
23
- return S.group('범례', items);
24
- }
25
-
26
- function yAxis(x, y0, y1, ticks, scale, st, unit, side = 'l') {
27
- const it = [S.line([[x, y0], [x, y1]], { stroke: st.line, name: '축' })];
28
- for (const t of ticks) {
29
- const y = scale(t);
30
- it.push(S.line(side === 'l' ? [[x - 1, y], [x, y]] : [[x, y], [x + 1, y]], { stroke: st.line, name: '눈금' }));
31
- it.push(S.text(side === 'l' ? x - 1.5 : x + 1.5, y, fmt(t), { size: st.small, anchor: side === 'l' ? 'r' : 'l', name: '눈금 값' }));
32
- }
33
- if (unit) it.push(S.text(x, y1 - 3, unit, { size: st.small, anchor: side === 'l' ? 'r' : 'l', name: '단위' }));
34
- return S.group(side === 'l' ? '세로축' : '오른쪽 세로축', it);
35
- }
36
-
37
- // 막대 / 누적 막대 (세로). spec: { categories, series:[{name, values}], stacked, unit, max, valueLabels: 'none'|'last'|'all', percent }
38
- export function barChart(spec, st = DEFAULT_STYLE) {
39
- const W = spec.width || st.width, H = spec.height || 52;
40
- const L = 11, T = spec.series.length > 1 ? 9 : 5, B = 7, R = 2;
41
- const cats = spec.categories, n = cats.length, ns = spec.series.length;
42
- const tot = cats.map((_, i) => spec.series.reduce((a, s) => a + (+s.values[i] || 0), 0));
43
- const vmax = spec.max ?? (spec.stacked ? Math.max(...tot) : Math.max(...spec.series.flatMap((s) => s.values.map(Number))));
44
- const vmin = Math.min(0, ...spec.series.flatMap((s) => s.values.map(Number)));
45
- const ticks = niceTicks(vmin, vmax, 5);
46
- const y0 = T, y1 = H - B, sc = (v) => y1 - ((v - ticks[0]) / (ticks.at(-1) - ticks[0])) * (y1 - y0);
47
- const items = [yAxis(L, y1, y0, ticks, sc, st, spec.unit)];
48
- items.push(S.line([[L, sc(0)], [W - R, sc(0)]], { stroke: st.line, name: '가로축' }));
49
- const band = (W - R - L) / n, bw = spec.stacked ? band * 0.5 : (band * 0.7) / ns;
50
- cats.forEach((c, i) => {
51
- const bars = [];
52
- let acc = 0;
53
- spec.series.forEach((s, k) => {
54
- const v = +s.values[i] || 0, fill = s.fill || SERIES_FILLS[k % SERIES_FILLS.length];
55
- const x = spec.stacked ? L + band * i + (band - bw) / 2 : L + band * i + band * 0.15 + bw * k;
56
- const a = spec.stacked ? acc : 0, b = a + v;
57
- acc = b;
58
- const top = sc(Math.max(a, b)), bot = sc(Math.min(a, b));
59
- bars.push(S.rect(x, top, bw, bot - top, { fill, stroke: 0.2, name: `${c} ${s.name}` }));
60
- const show = spec.valueLabels === 'all' || (spec.valueLabels === 'last' && k === ns - 1);
61
- if (show && v && (!spec.stacked || bot - top >= 3.2)) bars.push(S.text(x + bw / 2, spec.stacked ? (top + bot) / 2 : top - 1.8, fmt(v), { size: st.small - 0.5, box: spec.stacked, name: '값' }));
62
- });
63
- bars.push(S.text(L + band * i + band / 2, y1 + 3.2, c, { size: st.small, name: `항목 ${c}` }));
64
- items.push(S.group(`막대 ${c}`, bars));
65
- });
66
- if (ns > 1) items.push(legend(spec.series, L, 2.5, st));
67
- return items;
68
- }
69
-
70
- // 산점도·버블. spec: { points:[{label,x,y,size?}], xLabel, yLabel, xTicks?, yTicks?, sizeLabel }
71
- export function scatterChart(spec, st = DEFAULT_STYLE) {
72
- const W = spec.width || st.width, H = spec.height || 62;
73
- const L = 11, T = 6, B = 10, R = 4;
74
- const xs = spec.points.map((p) => +p.x), ys = spec.points.map((p) => +p.y);
75
- const pad = (a, b) => [a - (b - a) * 0.08, b + (b - a) * 0.08];
76
- const xt = spec.xTicks || niceTicks(...pad(Math.min(...xs), Math.max(...xs)), 5);
77
- const yt = spec.yTicks || niceTicks(...pad(Math.min(...ys), Math.max(...ys)), 5);
78
- const sx = (v) => L + ((v - xt[0]) / (xt.at(-1) - xt[0])) * (W - R - L);
79
- const sy = (v) => H - B - ((v - yt[0]) / (yt.at(-1) - yt[0])) * (H - B - T);
80
- const items = [yAxis(L, H - B, T, yt, sy, st, spec.yLabel)];
81
- const xa = [S.line([[L, H - B], [W - R, H - B]], { stroke: st.line, name: '축' })];
82
- for (const t of xt) { xa.push(S.line([[sx(t), H - B], [sx(t), H - B + 1]], { stroke: st.line, name: '눈금' })); xa.push(S.text(sx(t), H - B + 3, fmt(t), { size: st.small, name: '눈금 값' })); }
83
- if (spec.xLabel) xa.push(S.text(W - R, H - B + 6.8, spec.xLabel, { size: st.small, anchor: 'r', name: '가로축 이름' }));
84
- items.push(S.group('가로축', xa));
85
- const smax = Math.max(...spec.points.map((p) => +p.size || 0));
86
- spec.points.forEach((p) => {
87
- const r = p.size ? 1 + 4 * Math.sqrt(+p.size / smax) : 0.9;
88
- const cx = sx(+p.x), cy = sy(+p.y);
89
- const g = [p.size ? S.ellipse(cx - r, cy - r, 2 * r, 2 * r, { fill: { k: 'solid', gray: '#D9D9D9' }, stroke: 0.25, name: '원' }) : S.dot(cx, cy, r, { name: '점' })];
90
- g.push(S.text(cx + r + 0.8, cy - r * 0.3 - 0.6, p.label, { size: st.size, bold: true, anchor: 'l', name: `기호 ${p.label}` }));
91
- items.push(S.group(`점 ${p.label}`, g));
92
- });
93
- if (spec.sizeLabel) items.push(S.text(W - R, T - 3, `* 원의 크기는 ${spec.sizeLabel}`, { size: st.small - 0.5, anchor: 'r', name: '원 크기 설명' }));
94
- return items;
95
- }
96
-
97
- // 기후 그래프(월 강수 막대 + 기온 꺾은선), 지점 여러 개는 2열로 나란히.
98
- // spec: { stations:[{label, temp[12], precip[12]}], tRange:[min,max], pRange:[0,max] }
99
- export function climateChart(spec, st = DEFAULT_STYLE) {
100
- const cols = spec.cols || (spec.stations.length > 1 ? 2 : 1);
101
- const cw = (spec.width || st.width) / cols, ch = spec.cellHeight || 38;
102
- const allT = spec.stations.flatMap((s) => s.temp), allP = spec.stations.flatMap((s) => s.precip);
103
- const tt = niceTicks(Math.min(spec.tRange?.[0] ?? 0, ...allT), Math.max(spec.tRange?.[1] ?? -99, ...allT), 4);
104
- const pt = niceTicks(0, Math.max(spec.pRange?.[1] ?? 0, ...allP), tt.length - 1);
105
- const items = [];
106
- spec.stations.forEach((s, i) => {
107
- const ox = (i % cols) * cw, oy = Math.floor(i / cols) * ch;
108
- const L = ox + 9, R = ox + cw - 9, T = oy + 7, B = oy + ch - 6;
109
- const sy = (v) => B - ((v - tt[0]) / (tt.at(-1) - tt[0])) * (B - T);
110
- const sp = (v) => B - (v / pt.at(-1)) * (B - T);
111
- const g = [S.text((L + R) / 2, oy + 2.5, s.label, { size: st.size, bold: true, name: `지점 ${s.label}` })];
112
- g.push(yAxis(L, B, T, tt, sy, st, i === 0 ? '(℃)' : ''));
113
- g.push(yAxis(R, B, T, pt, sp, st, i === cols - 1 ? '(mm)' : '', 'r'));
114
- g.push(S.line([[L, B], [R, B]], { stroke: st.line, name: '가로축' }));
115
- const bw = (R - L) / 12;
116
- const bars = s.precip.map((p, m) => S.rect(L + bw * m + bw * 0.15, sp(p), bw * 0.7, B - sp(p), { fill: { k: 'solid', gray: '#BFBFBF' }, stroke: 0.15, name: `${m + 1}월 강수` }));
117
- g.push(S.group('강수량 막대', bars));
118
- g.push(S.line(s.temp.map((t, m) => [L + bw * m + bw / 2, sy(t)]), { stroke: 0.45, name: '기온 선' }));
119
- [1, 4, 7, 10, 12].forEach((m) => g.push(S.text(L + bw * (m - 1) + bw / 2, B + 2.4, String(m), { size: st.small - 1, name: '월' })));
120
- items.push(S.group(`기후 그래프 ${s.label}`, g));
121
- });
122
- items.push(S.group('범례', [
123
- S.line([[1, -2.2], [5, -2.2]], { stroke: 0.45, name: '범례 선' }), S.text(5.8, -2.2, '기온', { size: st.small, anchor: 'l' }),
124
- S.rect(14, -3.6, 2.8, 2.8, { fill: { k: 'solid', gray: '#BFBFBF' }, stroke: 0.15 }), S.text(17.6, -2.2, '강수량', { size: st.small, anchor: 'l' }),
125
- ]));
126
- return items;
127
- }
128
-
129
- // 편차 그래프: 기준값과의 차이 막대 (0선 강조). spec: { categories, series:[{name, values}], base, unit }
130
- export function deviationChart(spec, st = DEFAULT_STYLE) {
131
- const items = barChart({ ...spec, stacked: false }, st);
132
- items.push(S.text(spec.width || st.width, 2.5, `* 0 = ${spec.base}`, { size: st.small - 0.5, anchor: 'r', name: '기준 설명' }));
133
- return items;
134
- }
135
-
136
- // 인구 피라미드. spec: { groups:[연령 라벨(아래→위)], male[], female[], unit:'%' }
137
- export function pyramidChart(spec, st = DEFAULT_STYLE) {
138
- const W = spec.width || 60, H = spec.height || 50, mid = W / 2, gap = 7, B = 7, T = 5;
139
- const n = spec.groups.length, bh = (H - B - T) / n;
140
- const vmax = spec.max || Math.max(...spec.male, ...spec.female);
141
- const ticks = niceTicks(0, vmax, 3);
142
- const sw = (v) => (v / ticks.at(-1)) * (mid - gap / 2 - 2);
143
- const items = [];
144
- spec.groups.forEach((g, i) => {
145
- const y = H - B - bh * (i + 1);
146
- items.push(S.rect(mid - gap / 2 - sw(spec.male[i]), y, sw(spec.male[i]), bh, { fill: { k: 'solid', gray: '#A6A6A6' }, stroke: 0.15, name: `남 ${g}` }));
147
- items.push(S.rect(mid + gap / 2, y, sw(spec.female[i]), bh, { fill: { k: 'solid', gray: '#FFFFFF' }, stroke: 0.15, name: `여 ${g}` }));
148
- if (i % (spec.labelEvery || 2) === 0) items.push(S.text(mid, y + bh / 2, g, { size: st.small - 1, name: '연령' }));
149
- });
150
- const ax = [S.line([[2, H - B], [W - 2, H - B]], { stroke: st.line, name: '축' })];
151
- ticks.forEach((t) => { [mid - gap / 2 - sw(t), mid + gap / 2 + sw(t)].forEach((x) => { ax.push(S.line([[x, H - B], [x, H - B + 1]], { stroke: st.line })); ax.push(S.text(x, H - B + 3, fmt(t), { size: st.small - 1 })); }); });
152
- items.push(S.group('가로축', ax));
153
- items.push(S.text(mid - gap, 2, '남', { size: st.small, anchor: 'r' }), S.text(mid + gap, 2, '여', { size: st.small, anchor: 'l' }));
154
- if (spec.unit) items.push(S.text(W - 2, H - 1.5, `(${spec.unit})`, { size: st.small - 1, anchor: 'r' }));
155
- return items;
156
- }
157
-
158
- // 삼각 그래프. spec: { points:[{label,a,b,c}], names:[a,b,c] } — a 아래왼쪽, b 위, c 아래오른쪽 꼭짓점 (합 100)
159
- export function triangleChart(spec, st = DEFAULT_STYLE) {
160
- const s = spec.side || 55, h = (s * Math.sqrt(3)) / 2, ox = 8, oy = 6;
161
- const P = (a, b, c) => { const t = a + b + c; return [ox + s * (c / t) + s * 0.5 * (b / t), oy + h - h * (b / t)]; };
162
- const items = [S.poly([[P(100, 0, 0), P(0, 100, 0), P(0, 0, 100)]], { stroke: st.line, name: '삼각형' })];
163
- const grid = [];
164
- for (let k = 20; k < 100; k += 20) {
165
- grid.push(S.line([P(k, 100 - k, 0), P(k, 0, 100 - k)], { stroke: 0.1, gray: '#808080', name: '눈금선' }));
166
- grid.push(S.line([P(100 - k, k, 0), P(0, k, 100 - k)], { stroke: 0.1, gray: '#808080', name: '눈금선' }));
167
- grid.push(S.line([P(100 - k, 0, k), P(0, 100 - k, k)], { stroke: 0.1, gray: '#808080', name: '눈금선' }));
168
- }
169
- items.push(S.group('눈금선', grid));
170
- const [na, nb, nc] = spec.names;
171
- items.push(S.text(P(100, 0, 0)[0] - 1, P(100, 0, 0)[1] + 3, na, { size: st.small, anchor: 'r' }), S.text(P(0, 100, 0)[0], oy - 3, nb, { size: st.small }), S.text(P(0, 0, 100)[0] + 1, P(0, 0, 100)[1] + 3, nc, { size: st.small, anchor: 'l' }));
172
- spec.points.forEach((p) => { const [x, y] = P(+p.a, +p.b, +p.c); items.push(S.group(`점 ${p.label}`, [S.dot(x, y, 0.9), S.text(x + 1.6, y - 1.6, p.label, { size: st.size, bold: true, anchor: 'l' })])); });
173
- if (spec.unit) items.push(S.text(ox + s, oy + h + 7, `(단위: ${spec.unit})`, { size: st.small - 1, anchor: 'r' }));
174
- return items;
175
- }
176
-
177
- export const CHARTS = { bar: barChart, stacked: (s, st) => barChart({ ...s, stacked: true }, st), scatter: scatterChart, bubble: scatterChart, climate: climateChart, deviation: deviationChart, pyramid: pyramidChart, triangle: triangleChart };
1
+ // 수능형 그래프 → 장면 도형. 눈금선 최소, 장식 없음, 흑백 구분, 범례는 그래프 위.
2
+ import { S, SERIES_FILLS, DEFAULT_STYLE, textWidth } from './scene.js';
3
+
4
+ export function niceTicks(min, max, n = 5) {
5
+ if (min === max) max = min + 1;
6
+ const span = max - min, raw = span / n, mag = 10 ** Math.floor(Math.log10(raw));
7
+ const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => span / s <= n) || 10 * mag;
8
+ const lo = Math.floor(min / step) * step, hi = Math.ceil(max / step) * step;
9
+ const t = [];
10
+ for (let v = lo; v <= hi + step / 1e6; v += step) t.push(+v.toFixed(10));
11
+ return t;
12
+ }
13
+ const fmt = (v) => (Math.abs(v) >= 1000 ? v.toLocaleString('en-US') : String(+v.toFixed(2)));
14
+
15
+ function legend(series, x, y, st, fills = SERIES_FILLS) {
16
+ const items = [];
17
+ let cx = x;
18
+ series.forEach((s, i) => {
19
+ items.push(S.rect(cx, y - 1.4, 2.8, 2.8, { fill: s.fill || fills[i % fills.length], stroke: 0.2, name: `범례 칸 ${s.name}` }));
20
+ items.push(S.text(cx + 3.6, y, s.name, { size: st.small, anchor: 'l', name: `범례 ${s.name}` }));
21
+ cx += 3.6 + textWidth(s.name, st.small) + 3;
22
+ });
23
+ return S.group('범례', items);
24
+ }
25
+
26
+ function yAxis(x, y0, y1, ticks, scale, st, unit, side = 'l') {
27
+ const it = [S.line([[x, y0], [x, y1]], { stroke: st.line, name: '축' })];
28
+ for (const t of ticks) {
29
+ const y = scale(t);
30
+ it.push(S.line(side === 'l' ? [[x - 1, y], [x, y]] : [[x, y], [x + 1, y]], { stroke: st.line, name: '눈금' }));
31
+ it.push(S.text(side === 'l' ? x - 1.5 : x + 1.5, y, fmt(t), { size: st.small, anchor: side === 'l' ? 'r' : 'l', name: '눈금 값' }));
32
+ }
33
+ if (unit) it.push(S.text(x, y1 - 3, unit, { size: st.small, anchor: side === 'l' ? 'r' : 'l', name: '단위' }));
34
+ return S.group(side === 'l' ? '세로축' : '오른쪽 세로축', it);
35
+ }
36
+
37
+ // 막대 / 누적 막대 (세로). spec: { categories, series:[{name, values}], stacked, unit, max, valueLabels: 'none'|'last'|'all', percent }
38
+ export function barChart(spec, st = DEFAULT_STYLE) {
39
+ const W = spec.width || st.width, H = spec.height || 52;
40
+ const L = 11, T = spec.series.length > 1 ? 9 : 5, B = 7, R = 2;
41
+ const cats = spec.categories, n = cats.length, ns = spec.series.length;
42
+ const tot = cats.map((_, i) => spec.series.reduce((a, s) => a + (+s.values[i] || 0), 0));
43
+ const vmax = spec.max ?? (spec.stacked ? Math.max(...tot) : Math.max(...spec.series.flatMap((s) => s.values.map(Number))));
44
+ const vmin = Math.min(0, ...spec.series.flatMap((s) => s.values.map(Number)));
45
+ const ticks = niceTicks(vmin, vmax, 5);
46
+ const y0 = T, y1 = H - B, sc = (v) => y1 - ((v - ticks[0]) / (ticks.at(-1) - ticks[0])) * (y1 - y0);
47
+ const items = [yAxis(L, y1, y0, ticks, sc, st, spec.unit)];
48
+ items.push(S.line([[L, sc(0)], [W - R, sc(0)]], { stroke: st.line, name: '가로축' }));
49
+ const band = (W - R - L) / n, bw = spec.stacked ? band * 0.5 : (band * 0.7) / ns;
50
+ cats.forEach((c, i) => {
51
+ const bars = [];
52
+ let acc = 0;
53
+ spec.series.forEach((s, k) => {
54
+ const v = +s.values[i] || 0, fill = s.fill || SERIES_FILLS[k % SERIES_FILLS.length];
55
+ const x = spec.stacked ? L + band * i + (band - bw) / 2 : L + band * i + band * 0.15 + bw * k;
56
+ const a = spec.stacked ? acc : 0, b = a + v;
57
+ acc = b;
58
+ const top = sc(Math.max(a, b)), bot = sc(Math.min(a, b));
59
+ bars.push(S.rect(x, top, bw, bot - top, { fill, stroke: 0.2, name: `${c} ${s.name}` }));
60
+ const show = spec.valueLabels === 'all' || (spec.valueLabels === 'last' && k === ns - 1);
61
+ if (show && v && (!spec.stacked || bot - top >= 3.2)) bars.push(S.text(x + bw / 2, spec.stacked ? (top + bot) / 2 : top - 1.8, fmt(v), { size: st.small - 0.5, box: spec.stacked, name: '값' }));
62
+ });
63
+ bars.push(S.text(L + band * i + band / 2, y1 + 3.2, c, { size: st.small, name: `항목 ${c}` }));
64
+ items.push(S.group(`막대 ${c}`, bars));
65
+ });
66
+ if (ns > 1) items.push(legend(spec.series, L, 2.5, st));
67
+ return items;
68
+ }
69
+
70
+ // 산점도·버블. spec: { points:[{label,x,y,size?}], xLabel, yLabel, xTicks?, yTicks?, sizeLabel }
71
+ export function scatterChart(spec, st = DEFAULT_STYLE) {
72
+ const W = spec.width || st.width, H = spec.height || 62;
73
+ const L = 11, T = 6, B = 10, R = 4;
74
+ const xs = spec.points.map((p) => +p.x), ys = spec.points.map((p) => +p.y);
75
+ const pad = (a, b) => [a - (b - a) * 0.08, b + (b - a) * 0.08];
76
+ const xt = spec.xTicks || niceTicks(...pad(Math.min(...xs), Math.max(...xs)), 5);
77
+ const yt = spec.yTicks || niceTicks(...pad(Math.min(...ys), Math.max(...ys)), 5);
78
+ const sx = (v) => L + ((v - xt[0]) / (xt.at(-1) - xt[0])) * (W - R - L);
79
+ const sy = (v) => H - B - ((v - yt[0]) / (yt.at(-1) - yt[0])) * (H - B - T);
80
+ const items = [yAxis(L, H - B, T, yt, sy, st, spec.yLabel)];
81
+ const xa = [S.line([[L, H - B], [W - R, H - B]], { stroke: st.line, name: '축' })];
82
+ for (const t of xt) { xa.push(S.line([[sx(t), H - B], [sx(t), H - B + 1]], { stroke: st.line, name: '눈금' })); xa.push(S.text(sx(t), H - B + 3, fmt(t), { size: st.small, name: '눈금 값' })); }
83
+ if (spec.xLabel) xa.push(S.text(W - R, H - B + 6.8, spec.xLabel, { size: st.small, anchor: 'r', name: '가로축 이름' }));
84
+ items.push(S.group('가로축', xa));
85
+ const smax = Math.max(...spec.points.map((p) => +p.size || 0));
86
+ spec.points.forEach((p) => {
87
+ const r = p.size ? 1 + 4 * Math.sqrt(+p.size / smax) : 0.9;
88
+ const cx = sx(+p.x), cy = sy(+p.y);
89
+ const g = [p.size ? S.ellipse(cx - r, cy - r, 2 * r, 2 * r, { fill: { k: 'solid', gray: '#D9D9D9' }, stroke: 0.25, name: '원' }) : S.dot(cx, cy, r, { name: '점' })];
90
+ g.push(S.text(cx + r + 0.8, cy - r * 0.3 - 0.6, p.label, { size: st.size, bold: true, anchor: 'l', name: `기호 ${p.label}` }));
91
+ items.push(S.group(`점 ${p.label}`, g));
92
+ });
93
+ if (spec.sizeLabel) items.push(S.text(W - R, T - 3, `* 원의 크기는 ${spec.sizeLabel}`, { size: st.small - 0.5, anchor: 'r', name: '원 크기 설명' }));
94
+ return items;
95
+ }
96
+
97
+ // 기후 그래프(월 강수 막대 + 기온 꺾은선), 지점 여러 개는 2열로 나란히.
98
+ // spec: { stations:[{label, temp[12], precip[12]}], tRange:[min,max], pRange:[0,max] }
99
+ export function climateChart(spec, st = DEFAULT_STYLE) {
100
+ const cols = spec.cols || (spec.stations.length > 1 ? 2 : 1);
101
+ const cw = (spec.width || st.width) / cols, ch = spec.cellHeight || 38;
102
+ const allT = spec.stations.flatMap((s) => s.temp), allP = spec.stations.flatMap((s) => s.precip);
103
+ const tt = niceTicks(Math.min(spec.tRange?.[0] ?? 0, ...allT), Math.max(spec.tRange?.[1] ?? -99, ...allT), 4);
104
+ const pt = niceTicks(0, Math.max(spec.pRange?.[1] ?? 0, ...allP), tt.length - 1);
105
+ const items = [];
106
+ spec.stations.forEach((s, i) => {
107
+ const ox = (i % cols) * cw, oy = Math.floor(i / cols) * ch;
108
+ const L = ox + 9, R = ox + cw - 9, T = oy + 7, B = oy + ch - 6;
109
+ const sy = (v) => B - ((v - tt[0]) / (tt.at(-1) - tt[0])) * (B - T);
110
+ const sp = (v) => B - (v / pt.at(-1)) * (B - T);
111
+ const g = [S.text((L + R) / 2, oy + 2.5, s.label, { size: st.size, bold: true, name: `지점 ${s.label}` })];
112
+ g.push(yAxis(L, B, T, tt, sy, st, i === 0 ? '(℃)' : ''));
113
+ g.push(yAxis(R, B, T, pt, sp, st, i === cols - 1 ? '(mm)' : '', 'r'));
114
+ g.push(S.line([[L, B], [R, B]], { stroke: st.line, name: '가로축' }));
115
+ const bw = (R - L) / 12;
116
+ const bars = s.precip.map((p, m) => S.rect(L + bw * m + bw * 0.15, sp(p), bw * 0.7, B - sp(p), { fill: { k: 'solid', gray: '#BFBFBF' }, stroke: 0.15, name: `${m + 1}월 강수` }));
117
+ g.push(S.group('강수량 막대', bars));
118
+ g.push(S.line(s.temp.map((t, m) => [L + bw * m + bw / 2, sy(t)]), { stroke: 0.45, name: '기온 선' }));
119
+ [1, 4, 7, 10, 12].forEach((m) => g.push(S.text(L + bw * (m - 1) + bw / 2, B + 2.4, String(m), { size: st.small - 1, name: '월' })));
120
+ items.push(S.group(`기후 그래프 ${s.label}`, g));
121
+ });
122
+ items.push(S.group('범례', [
123
+ S.line([[1, -2.2], [5, -2.2]], { stroke: 0.45, name: '범례 선' }), S.text(5.8, -2.2, '기온', { size: st.small, anchor: 'l' }),
124
+ S.rect(14, -3.6, 2.8, 2.8, { fill: { k: 'solid', gray: '#BFBFBF' }, stroke: 0.15 }), S.text(17.6, -2.2, '강수량', { size: st.small, anchor: 'l' }),
125
+ ]));
126
+ return items;
127
+ }
128
+
129
+ // 편차 그래프: 기준값과의 차이 막대 (0선 강조). spec: { categories, series:[{name, values}], base, unit }
130
+ export function deviationChart(spec, st = DEFAULT_STYLE) {
131
+ const items = barChart({ ...spec, stacked: false }, st);
132
+ items.push(S.text(spec.width || st.width, 2.5, `* 0 = ${spec.base}`, { size: st.small - 0.5, anchor: 'r', name: '기준 설명' }));
133
+ return items;
134
+ }
135
+
136
+ // 인구 피라미드. spec: { groups:[연령 라벨(아래→위)], male[], female[], unit:'%' }
137
+ export function pyramidChart(spec, st = DEFAULT_STYLE) {
138
+ const W = spec.width || 60, H = spec.height || 50, mid = W / 2, gap = 7, B = 7, T = 5;
139
+ const n = spec.groups.length, bh = (H - B - T) / n;
140
+ const vmax = spec.max || Math.max(...spec.male, ...spec.female);
141
+ const ticks = niceTicks(0, vmax, 3);
142
+ const sw = (v) => (v / ticks.at(-1)) * (mid - gap / 2 - 2);
143
+ const items = [];
144
+ spec.groups.forEach((g, i) => {
145
+ const y = H - B - bh * (i + 1);
146
+ items.push(S.rect(mid - gap / 2 - sw(spec.male[i]), y, sw(spec.male[i]), bh, { fill: { k: 'solid', gray: '#A6A6A6' }, stroke: 0.15, name: `남 ${g}` }));
147
+ items.push(S.rect(mid + gap / 2, y, sw(spec.female[i]), bh, { fill: { k: 'solid', gray: '#FFFFFF' }, stroke: 0.15, name: `여 ${g}` }));
148
+ if (i % (spec.labelEvery || 2) === 0) items.push(S.text(mid, y + bh / 2, g, { size: st.small - 1, name: '연령' }));
149
+ });
150
+ const ax = [S.line([[2, H - B], [W - 2, H - B]], { stroke: st.line, name: '축' })];
151
+ ticks.forEach((t) => { [mid - gap / 2 - sw(t), mid + gap / 2 + sw(t)].forEach((x) => { ax.push(S.line([[x, H - B], [x, H - B + 1]], { stroke: st.line })); ax.push(S.text(x, H - B + 3, fmt(t), { size: st.small - 1 })); }); });
152
+ items.push(S.group('가로축', ax));
153
+ items.push(S.text(mid - gap, 2, '남', { size: st.small, anchor: 'r' }), S.text(mid + gap, 2, '여', { size: st.small, anchor: 'l' }));
154
+ if (spec.unit) items.push(S.text(W - 2, H - 1.5, `(${spec.unit})`, { size: st.small - 1, anchor: 'r' }));
155
+ return items;
156
+ }
157
+
158
+ // 삼각 그래프. spec: { points:[{label,a,b,c}], names:[a,b,c] } — a 아래왼쪽, b 위, c 아래오른쪽 꼭짓점 (합 100)
159
+ export function triangleChart(spec, st = DEFAULT_STYLE) {
160
+ const s = spec.side || 55, h = (s * Math.sqrt(3)) / 2, ox = 22, oy = 6;
161
+ const P = (a, b, c) => { const t = a + b + c; return [ox + s * (c / t) + s * 0.5 * (b / t), oy + h - h * (b / t)]; };
162
+ const items = [S.poly([[P(100, 0, 0), P(0, 100, 0), P(0, 0, 100)]], { stroke: st.line, name: '삼각형' })];
163
+ const grid = [];
164
+ for (let k = 20; k < 100; k += 20) {
165
+ grid.push(S.line([P(k, 100 - k, 0), P(k, 0, 100 - k)], { stroke: 0.1, gray: '#808080', name: '눈금선' }));
166
+ grid.push(S.line([P(100 - k, k, 0), P(0, k, 100 - k)], { stroke: 0.1, gray: '#808080', name: '눈금선' }));
167
+ grid.push(S.line([P(100 - k, 0, k), P(0, 100 - k, k)], { stroke: 0.1, gray: '#808080', name: '눈금선' }));
168
+ }
169
+ items.push(S.group('눈금선', grid));
170
+ const [na, nb, nc] = spec.names || spec.axes || ['A', 'B', 'C'];
171
+ const u = spec.unit || '%';
172
+ const fs = st.small - 1.5;
173
+ // 눈금 숫자: a(왼쪽 아래 꼭짓점이 100)는 아랫변, b(위 꼭짓점이 100)는 왼쪽 변, c(오른쪽 아래 꼭짓점이 100)는 오른쪽 변에 적는다
174
+ for (let k = 0; k <= 100; k += 20) {
175
+ const pa = P(k, 0, 100 - k); items.push(S.text(pa[0], pa[1] + 2.2, String(k), { size: fs, name: `눈금 ${na} ${k}` }));
176
+ const pb = P(100 - k, k, 0); items.push(S.text(pb[0] - 1.2, pb[1], String(k), { size: fs, anchor: 'r', name: `눈금 ${nb} ${k}` }));
177
+ const pc = P(0, 100 - k, k); items.push(S.text(pc[0] + 1.2, pc[1], String(k), { size: fs, anchor: 'l', name: `눈금 ${nc} ${k}` }));
178
+ }
179
+ // 축 이름과 커지는 방향
180
+ const mid = (p, q) => [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2];
181
+ const A = P(100, 0, 0), B = P(0, 100, 0), C = P(0, 0, 100);
182
+ const mb = mid(A, C), ml = mid(A, B), mr = mid(B, C);
183
+ items.push(S.text(mb[0], mb[1] + 6, `← ${na}(${u})`, { size: st.small, name: `축 ${na}` }));
184
+ items.push(S.text(ml[0] - 7, ml[1], `${nb}(${u}) ↑`, { size: st.small, anchor: 'r', name: `축 ${nb}` }));
185
+ items.push(S.text(mr[0] + 7, mr[1], `↓ ${nc}(${u})`, { size: st.small, anchor: 'l', name: `축 ${nc}` }));
186
+ spec.points.forEach((p) => { const [va, vb, vc] = p.values || [p.a, p.b, p.c]; const [x, y] = P(+va, +vb, +vc); items.push(S.group(`점 ${p.label}`, [S.dot(x, y, 0.9), S.text(x + 1.6, y - 1.6, p.label, { size: st.size, bold: true, anchor: 'l' })])); });
187
+ return items;
188
+ }
189
+
190
+ export const CHARTS = { bar: barChart, stacked: (s, st) => barChart({ ...s, stacked: true }, st), scatter: scatterChart, bubble: scatterChart, climate: climateChart, deviation: deviationChart, pyramid: pyramidChart, triangle: triangleChart };