# 마칭 스퀘어 등고선 (Marching squares contours)

격자 꼭짓점에서 높이를 읽고, 기준 높이를 가로지르는 변의 교점을 이으면 등고선이 됩니다. 이 지형에서는 40m에서 한 줄이 두 봉우리를 감싸고 76m에서 두 줄로 갈라집니다.

## 체험 방법

40 m와 76 m를 번갈아 누르고, 슬라이더로 두 봉우리 사이의 선이 끊어지는 높이를 찾아보세요.

## 재현 기준

높이 범위는 32~80m입니다. 두 봉우리는 고정하고 현재 등고선만 밝게 표시합니다.

## 기기별 조작

- PC · Tab으로 높이 슬라이더를 선택하고 방향키로 1m씩 조절하세요.
- iOS · 높이 슬라이더를 끌거나 40 m와 76 m 버튼을 누르세요.
- Android · 높이 슬라이더를 끌거나 40 m와 76 m 버튼을 누르세요.

## 적용할 때

지형도나 기상 지도에서 수치 격자를 경계선으로 바꾸는 과정을 보여줄 때 씁니다.

## 그대로 보낼 요청

> 높이가 다른 두 봉우리를 격자에 만들고, 선택한 높이를 지나는 변의 교점을 보간해 등고선을 그려줘. 기준 높이를 바꿀 때 닫힌 선 개수도 갱신해줘.

## 참고한 동작

[D3 · Contour polygons](https://d3js.org/d3-contour/contour)

## 독립 실행 코드

아래 전체 코드를 HTML로 저장해 브라우저에서 엽니다.

```html
<!doctype html>
<html lang="ko" data-motion-locales="inline">
<head><script>if(new URLSearchParams(location.search).get('reduce')==='1')document.documentElement.classList.add('motion-reduced');</script>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>두 봉우리의 등고선</title>
<style>
*{box-sizing:border-box}
:root{font:15px/1.4 system-ui,"Malgun Gothic",sans-serif;color:#1e3f40;background:#e9eee6;color-scheme:light;--accent:#226064}
body{margin:0;padding:clamp(10px,3vw,26px);min-height:100svh;display:grid;align-content:center}
main{width:min(100%,740px);margin:auto}
header,.readout{display:flex;align-items:baseline;justify-content:space-between;gap:8px 18px;flex-wrap:wrap}
header{margin:0 0 9px}h1{margin:0;font-size:clamp(20px,4vw,33px);letter-spacing:-.05em;line-height:1.12}
header small{font:650 12px/1.3 ui-monospace,monospace}
figure{margin:0}canvas{display:block;width:100%;height:auto;aspect-ratio:700/250;border-radius:7px;background:#14383a}
.readout{padding:6px 0;font:650 clamp(11px,1.8vw,14px)/1.35 ui-monospace,monospace}
.controls{display:flex;gap:6px 9px;align-items:center;flex-wrap:wrap;border-top:1px solid currentColor;padding-top:8px}
button{min-height:35px;padding:7px 12px;border:1px solid currentColor;background:transparent;color:inherit;border-radius:5px;cursor:pointer;font:650 13px/1.2 system-ui,sans-serif}
button:active,button[aria-pressed="true"]{color:white;background:var(--accent);border-color:var(--accent)}
button:focus-visible,input:focus-visible{outline:3px solid var(--accent);outline-offset:3px}
label{display:flex;align-items:center;gap:7px;flex:1 1 124px;min-width:0;font-size:12px;font-weight:650}
label span{flex:none;white-space:nowrap}
input[type="range"]{accent-color:var(--accent);flex:1 1 70px;min-width:55px;width:auto;margin:0}
@media(max-width:450px){header small{font-size:10px}.readout{gap:3px 7px}button{min-height:36px;padding:6px 9px}.controls{gap:5px}.controls label{flex-basis:100%}}
</style></head>
<body><main><header><h1 data-t="title"></h1><small data-t="method"></small></header>
<figure><canvas id="board" width="700" height="250" role="img"></canvas>
<figcaption class="readout"><span id="status"></span><output id="reading"></output></figcaption></figure>
<div class="controls"><button id="low" data-t="low"></button><button id="high" data-t="high"></button><label><span data-t="level"></span><input id="level" type="range" min="32" max="80" step="1" value="40"></label></div></main>
<script>
'use strict';
const words={
 "title": [
  "두 봉우리의 등고선",
  "Contours of two peaks",
  "Curvas de dos cumbres",
  "双峰等高线"
 ],
 "method": [
  "마칭 스퀘어",
  "Marching squares",
  "Marching squares",
  "行进方格"
 ],
 "description": [
  "같은 높이를 잇는 선이 두 봉우리를 감싸는 지형도",
  "Contours connect equal heights around two summits",
  "Las curvas unen alturas iguales alrededor de dos cimas",
  "等高线围绕两座山峰连接相同的高度"
 ],
 "low": [
  "40 m",
  "40 m",
  "40 m",
  "40 m"
 ],
 "high": [
  "76 m",
  "76 m",
  "76 m",
  "76 m"
 ],
 "level": [
  "높이",
  "Elevation",
  "Altura",
  "高度"
 ],
 "loops": [
  "닫힌 선",
  "Closed contours",
  "Curvas cerradas",
  "闭合曲线"
 ]
};
const languages=["ko","en","es","zh-Hans"];
const params=new URLSearchParams(location.search);
const preferred=params.get('lang')||document.documentElement.lang;
const code=languages.includes(preferred)?preferred:'ko';
const tr=k=>words[k][languages.indexOf(code)];
const by=id=>document.getElementById(id);
document.documentElement.lang=code;
document.title=tr('title');
document.querySelectorAll('[data-t]').forEach(el=>el.textContent=tr(el.dataset.t));
const board=by('board'),ctx=board.getContext('2d');
board.setAttribute('aria-label',tr('description'));
const reduced=()=>params.get('reduce')==='1'||document.documentElement.classList.contains('motion-reduced')||matchMedia('(prefers-reduced-motion: reduce)').matches;
let animation=0;
function animate(from,to,duration,render){
  cancelAnimationFrame(animation);
  if(reduced()||from===to){render(to);return;}
  const start=performance.now();
  function frame(now){
    const fraction=Math.min(1,(now-start)/duration);
    render(from+(to-from)*fraction);
    if(fraction<1)animation=requestAnimationFrame(frame);
  }
  animation=requestAnimationFrame(frame);
}

const cols=56, rows=30, dx=620/cols, dy=204/rows;
function heightAt(x,y){
  const hill=(cx,cy,amp)=>amp*Math.exp(-0.5*(((x-cx)/.14)**2+((y-cy)/.205)**2));
  return hill(.31,.53,92)+hill(.70,.43,88);
}
const grid=Array.from({length:rows+1},(_,j)=>Array.from({length:cols+1},(_,i)=>heightAt(i/cols,j/rows)));
function contour(level){
  const segments=[],links=new Map();
  function connect(a,b){
    segments.push([a,b]);
    for(const [p,q] of [[a,b],[b,a]]){
      if(!links.has(p.key))links.set(p.key,[]);
      links.get(p.key).push(q.key);
    }
  }
  for(let j=0;j<rows;j++)for(let i=0;i<cols;i++){
    const corners=[[i,j],[i+1,j],[i+1,j+1],[i,j+1]];
    const values=corners.map(([x,y])=>grid[y][x]);
    const hits=[];
    for(let k=0;k<4;k++){
      const next=(k+1)%4;
      if((values[k]>=level)===(values[next]>=level))continue;
      const [x,y]=corners[k],[u,v]=corners[next];
      const t=(level-values[k])/(values[next]-values[k]);
      const key=(y===v?'h':'v')+Math.min(x,u)+','+Math.min(y,v);
      hits.push({key,x:40+dx*(x+t*(u-x)),y:23+dy*(y+t*(v-y))});
    }
    if(hits.length===2)connect(hits[0],hits[1]);
    else if(hits.length===4){
      const centreHigh=values.reduce((a,b)=>a+b,0)/4>=level;
      const pair=centreHigh===(values[0]>=level)?[[0,1],[2,3]]:[[0,3],[1,2]];
      for(const [a,b] of pair)connect(hits[a],hits[b]);
    }
  }
  const seen=new Set();let loops=0;
  for(const key of links.keys()){
    if(seen.has(key))continue;
    let closed=true;const pending=[key];
    while(pending.length){
      const p=pending.pop();if(seen.has(p))continue;seen.add(p);
      const near=links.get(p);if(near.length!==2)closed=false;pending.push(...near);
    }
    if(closed)loops++;
  }
  return {segments,loops};
}
function linework(shape,color,width){
  ctx.strokeStyle=color;ctx.lineWidth=width;ctx.beginPath();
  for(const [a,b] of shape.segments){ctx.moveTo(a.x,a.y);ctx.lineTo(b.x,b.y);}
  ctx.stroke();
}
const backdrop=document.createElement('canvas');backdrop.width=700;backdrop.height=250;
ctx.fillStyle='#14383a';ctx.fillRect(0,0,700,250);
ctx.strokeStyle='#275052';ctx.lineWidth=.7;ctx.beginPath();
for(let x=40;x<=661;x+=31){ctx.moveTo(x,13);ctx.lineTo(x,236);}
for(let y=23;y<=229;y+=17){ctx.moveTo(26,y);ctx.lineTo(674,y);}ctx.stroke();
for(const h of [12,18,24,30,36,42,48,54,60,66,72,78,84,90])linework(contour(h),'#70a69a',1);
ctx.font='600 14px ui-monospace, monospace';ctx.fillStyle='#c7dccc';
for(const [x,y,label] of [[.31,.53,'A'],[.70,.43,'B']]){
 const px=40+620*x,py=23+204*y;
 ctx.fillText('+',px-4,py+5);ctx.fillText(label,px+9,py-3);
}
backdrop.getContext('2d').drawImage(board,0,0);
let current=40;
function show(v){
  current=Math.round(v);const shape=contour(current);
  ctx.drawImage(backdrop,0,0);linework(shape,'#ffca78',3.8);
  by('level').value=current;by('status').textContent=tr('level')+'  '+current+' m';
  by('reading').textContent=tr('loops')+'  '+shape.loops;
  board.dataset.level=current;board.dataset.loops=shape.loops;
}
by('level').oninput=e=>{cancelAnimationFrame(animation);show(+e.target.value);};
by('low').onclick=()=>animate(current,40,520,show);
by('high').onclick=()=>animate(current,76,520,show);
show(40);
</script></body></html>
```

