dxf: split into layer-key and block-partition workflows

This commit is contained in:
2026-04-13 09:22:03 +09:00
parent be58c7ed3c
commit bd79da2b64
13 changed files with 38154 additions and 0 deletions

48
dxf/README.md Normal file
View File

@@ -0,0 +1,48 @@
# DXF 정리 (Hyein/issue-sample)
`dxf` 작업을 아래 두 주제로 분리해서 정리했습니다.
1. 레이어 기반 위치 키 지정
2. 블록 정보 추출 + 도면 분할 표시
## 1) 레이어 기반 위치 키 지정
- 스크립트: `dxf/layer_position_keys.mjs`
- 목적: DXF 엔티티의 `layer + 위치(grid)` 기준 키 생성
- 출력: `dxf/layer_position_keys.json`
실행 예시:
```bash
node dxf/layer_position_keys.mjs --input dxf/center.dxf --output dxf/layer_position_keys.json --cell 2000
```
키 포맷:
- `LAYER::R{row}C{col}::####`
- 예: `CHAIR_A::R3C2::0014`
## 2) 블록 정보 추출 + 도면 분할 표시
- 스크립트: `dxf/block_partition_report.mjs`
- 목적: DXF `INSERT` 기반 블록 배치/크기/영역(zone) 추출
- 출력:
- `dxf/block_partition_report.json`
- `dxf/block_partition_report.html`
실행 예시:
```bash
node dxf/block_partition_report.mjs --input dxf/center.dxf --json dxf/block_partition_report.json --html dxf/block_partition_report.html --split 4
```
`--split 4` 는 전체 도면을 4x4 zone으로 분할해 `zoneKey`를 부여합니다.
## 이슈 정리 문서
- `dxf/issues/MASTER-01-layer-position-key.md`
- `dxf/issues/MASTER-02-block-partition-report.md`
- `dxf/issues/SUB-01-layer-rules-and-key-schema.md`
- `dxf/issues/SUB-02-layer-key-validation.md`
- `dxf/issues/SUB-03-block-extraction-pipeline.md`
- `dxf/issues/SUB-04-block-viewer-and-zone-info.md`

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,300 @@
import fs from "fs";
import path from "path";
import {
boundsFromPoints,
computeEntityListBounds,
first,
num,
parseDxfText,
readDxfText,
transformPoint,
} from "./lib/dxf_basic_parser.mjs";
function parseArgs(argv) {
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (!token.startsWith("--")) continue;
const key = token.slice(2);
const value = argv[i + 1];
if (!value || value.startsWith("--")) continue;
out[key] = value;
i += 1;
}
return out;
}
function toFixedNumber(value, fraction = 3) {
return Number(Number(value).toFixed(fraction));
}
function computeZoneKey(centerX, centerY, bounds, split) {
const width = Math.max(1, bounds.maxX - bounds.minX);
const height = Math.max(1, bounds.maxY - bounds.minY);
const col = Math.min(split - 1, Math.max(0, Math.floor(((centerX - bounds.minX) / width) * split)));
const row = Math.min(split - 1, Math.max(0, Math.floor(((centerY - bounds.minY) / height) * split)));
return `Z-R${row + 1}C${col + 1}`;
}
function buildBlockPartitionData(dxfPath, split) {
const { blocks, entities, headerBounds } = parseDxfText(readDxfText(dxfPath));
const drawingWidth = Math.max(1, headerBounds.maxX - headerBounds.minX);
const drawingHeight = Math.max(1, headerBounds.maxY - headerBounds.minY);
const drawingArea = drawingWidth * drawingHeight;
const blockDefs = new Map();
for (const block of blocks) {
const name = first(block, 2) ?? "*anonymous*";
const basePoint = { x: num(block, 10), y: num(block, 20) };
const localBounds = computeEntityListBounds(block.entities);
blockDefs.set(name, {
name,
basePoint,
localBounds,
entityCount: block.entities.length,
});
}
const partitions = [];
for (const entity of entities) {
if (entity.type !== "INSERT") continue;
const blockName = first(entity, 2) ?? "";
const blockLayer = first(entity, 8) ?? "0";
const blockDef = blockDefs.get(blockName);
if (!blockDef || !blockDef.localBounds) continue;
const insert = {
x: num(entity, 10),
y: num(entity, 20),
rotation: num(entity, 50),
xScale: num(entity, 41, 1),
yScale: num(entity, 42, 1),
};
const b = blockDef.localBounds;
const corners = [
{ x: b.minX, y: b.minY },
{ x: b.maxX, y: b.minY },
{ x: b.maxX, y: b.maxY },
{ x: b.minX, y: b.maxY },
].map((point) => transformPoint(point, insert, blockDef.basePoint));
const worldBounds = boundsFromPoints(corners);
if (!worldBounds) continue;
const area = Math.max(1, worldBounds.width * worldBounds.height);
const oversized =
area > drawingArea * 0.6 ||
worldBounds.width > drawingWidth * 0.9 ||
worldBounds.height > drawingHeight * 0.9;
if (oversized) continue;
const zoneKey = computeZoneKey(worldBounds.cx, worldBounds.cy, headerBounds, split);
partitions.push({
id: `P-${String(partitions.length + 1).padStart(4, "0")}`,
zoneKey,
blockName,
layer: blockLayer,
handle: first(entity, 5) ?? "",
rotation: toFixedNumber(insert.rotation, 2),
scale: {
x: toFixedNumber(insert.xScale, 4),
y: toFixedNumber(insert.yScale, 4),
},
center: {
x: toFixedNumber(worldBounds.cx),
y: toFixedNumber(worldBounds.cy),
},
bounds: {
minX: toFixedNumber(worldBounds.minX),
minY: toFixedNumber(worldBounds.minY),
maxX: toFixedNumber(worldBounds.maxX),
maxY: toFixedNumber(worldBounds.maxY),
width: toFixedNumber(worldBounds.width),
height: toFixedNumber(worldBounds.height),
},
blockEntityCount: blockDef.entityCount,
});
}
partitions.sort((a, b) => {
const dy = b.center.y - a.center.y;
if (Math.abs(dy) > 0.0001) return dy;
return a.center.x - b.center.x;
});
const byBlock = {};
const byZone = {};
for (const item of partitions) {
byBlock[item.blockName] = (byBlock[item.blockName] ?? 0) + 1;
byZone[item.zoneKey] = (byZone[item.zoneKey] ?? 0) + 1;
}
return {
meta: {
source: path.basename(dxfPath),
generatedAt: new Date().toISOString(),
split,
partitionCount: partitions.length,
blockDefinitionCount: blockDefs.size,
headerBounds,
},
byBlock,
byZone,
partitions,
};
}
function buildHtml(payload) {
return `<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>DXF block partition report</title>
<style>
:root {
--bg: #f2f4f8;
--card: #ffffff;
--line: #d8dee8;
--ink: #152230;
--muted: #6b7a8e;
--accent: #1861bf;
--accent-soft: rgba(24, 97, 191, 0.12);
}
* { box-sizing: border-box; }
body { margin: 0; font-family: "Segoe UI", "Pretendard", sans-serif; color: var(--ink); background: linear-gradient(180deg, #f8fafc 0%, var(--bg) 100%); }
.layout { display: grid; grid-template-columns: 1.8fr 1fr; gap: 14px; padding: 14px; min-height: 100vh; }
.panel { background: var(--card); border: 1px solid var(--line); border-radius: 14px; overflow: hidden; box-shadow: 0 10px 24px rgba(28, 39, 58, 0.06); }
.header { padding: 12px 14px; border-bottom: 1px solid var(--line); display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }
.header strong { font-size: 14px; }
.header span { font-size: 12px; color: var(--muted); }
.canvas-wrap { padding: 12px; }
svg { width: 100%; height: 78vh; border: 1px solid var(--line); border-radius: 10px; background: #f9fbfd; }
.list { max-height: 84vh; overflow: auto; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid #ecf0f6; white-space: nowrap; }
th { position: sticky; top: 0; background: #f8fafc; z-index: 1; font-weight: 600; }
tr:hover td { background: var(--accent-soft); }
.tag { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 11px; border: 1px solid #cadaf4; color: #124c95; background: #edf4ff; }
@media (max-width: 980px) {
.layout { grid-template-columns: 1fr; }
svg { height: 54vh; }
.list { max-height: none; }
}
</style>
</head>
<body>
<div class="layout">
<section class="panel">
<div class="header">
<strong>Block partition map</strong>
<span id="meta"></span>
</div>
<div class="canvas-wrap">
<svg id="map"></svg>
</div>
</section>
<section class="panel">
<div class="header">
<strong>Partition list</strong>
<span>${payload.partitions.length} items</span>
</div>
<div class="list">
<table>
<thead>
<tr>
<th>ID</th>
<th>Zone</th>
<th>Block</th>
<th>Layer</th>
<th>Size</th>
</tr>
</thead>
<tbody id="rows"></tbody>
</table>
</div>
</section>
</div>
<script>
const DATA = ${JSON.stringify(payload)};
const map = document.getElementById("map");
const rows = document.getElementById("rows");
const meta = document.getElementById("meta");
const W = 1600;
const H = 980;
map.setAttribute("viewBox", \`0 0 \${W} \${H}\`);
meta.textContent = \`\${DATA.meta.source} | partitions: \${DATA.meta.partitionCount}\`;
const bounds = DATA.meta.headerBounds;
const worldW = Math.max(1, bounds.maxX - bounds.minX);
const worldH = Math.max(1, bounds.maxY - bounds.minY);
const pad = 30;
const drawW = W - pad * 2;
const drawH = H - pad * 2;
function tx(x) { return pad + ((x - bounds.minX) / worldW) * drawW; }
function ty(y) { return pad + ((bounds.maxY - y) / worldH) * drawH; }
const bg = document.createElementNS("http://www.w3.org/2000/svg", "rect");
bg.setAttribute("x", pad);
bg.setAttribute("y", pad);
bg.setAttribute("width", drawW);
bg.setAttribute("height", drawH);
bg.setAttribute("fill", "#ffffff");
bg.setAttribute("stroke", "#dde5ef");
map.appendChild(bg);
DATA.partitions.forEach((item, index) => {
const x = tx(item.bounds.minX);
const y = ty(item.bounds.maxY);
const width = Math.max(2, tx(item.bounds.maxX) - tx(item.bounds.minX));
const height = Math.max(2, ty(item.bounds.minY) - ty(item.bounds.maxY));
const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", width);
rect.setAttribute("height", height);
rect.setAttribute("fill", "rgba(24,97,191,0.12)");
rect.setAttribute("stroke", "rgba(24,97,191,0.8)");
rect.setAttribute("stroke-width", "1.1");
map.appendChild(rect);
if (index % 4 === 0) {
const label = document.createElementNS("http://www.w3.org/2000/svg", "text");
label.setAttribute("x", x + 3);
label.setAttribute("y", Math.max(16, y + 12));
label.setAttribute("fill", "#0e3d7b");
label.setAttribute("font-size", "11");
label.textContent = item.id;
map.appendChild(label);
}
const tr = document.createElement("tr");
tr.innerHTML = \`
<td>\${item.id}</td>
<td><span class="tag">\${item.zoneKey}</span></td>
<td>\${item.blockName}</td>
<td>\${item.layer}</td>
<td>\${item.bounds.width} x \${item.bounds.height}</td>
\`;
rows.appendChild(tr);
});
</script>
</body>
</html>`;
}
const args = parseArgs(process.argv.slice(2));
const scriptDir = path.dirname(new URL(import.meta.url).pathname);
const dxfPath = path.resolve(args.input ?? path.join(scriptDir, "center.dxf"));
const outputJsonPath = path.resolve(args.json ?? path.join(scriptDir, "block_partition_report.json"));
const outputHtmlPath = path.resolve(args.html ?? path.join(scriptDir, "block_partition_report.html"));
const split = Math.max(2, Number(args.split ?? 4) || 4);
const report = buildBlockPartitionData(dxfPath, split);
fs.writeFileSync(outputJsonPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
fs.writeFileSync(outputHtmlPath, buildHtml(report), "utf8");
console.log(`saved: ${outputJsonPath}`);
console.log(`saved: ${outputHtmlPath}`);

View File

@@ -0,0 +1,33 @@
## [MASTER] DXF 레이어 기반 위치 키 체계
- label: `dxf`
- type: master issue
### 배경
DXF에서 레이어 정보를 기준으로 위치별 식별 키를 만들고, 후속 데이터 연계(좌석/자산/도면 포인트 매핑)에 사용할 표준 키 포맷을 확정한다.
### 목표
- 레이어별 키 발급 규칙 확정
- 위치(Grid) 기반 키 생성 파이프라인 구현
- 결과 JSON 검증 기준 수립
### 산출물
- `dxf/layer_position_keys.mjs`
- `dxf/layer_position_keys.json` (샘플 결과)
- `dxf/issues/SUB-01-layer-rules-and-key-schema.md`
- `dxf/issues/SUB-02-layer-key-validation.md`
### 체크리스트
- [ ] 키 포맷 확정 (`LAYER::R{row}C{col}::####`)
- [ ] 레이어명 정규화(대문자/특수문자 정리) 반영
- [ ] grid cell 크기 파라미터화
- [ ] 샘플 DXF 대상으로 결과 검증
### 하위 이슈
- #SUB-01 레이어 규칙/키 스키마
- #SUB-02 키 생성 결과 검증/품질 체크

View File

@@ -0,0 +1,34 @@
## [MASTER] DXF 블록 추출 및 도면 분할 리포트
- label: `dxf`
- type: master issue
### 배경
DXF 블록(`BLOCK`/`INSERT`) 정보를 추출해 도면을 블록 단위로 분할하고, 각 분할 영역의 정보를 사람이 확인 가능한 형태(JSON/HTML)로 제공한다.
### 목표
- 블록 정의/삽입 정보 파싱
- 블록별 world bounds 계산
- 분할 zone 키 지정 및 시각화
### 산출물
- `dxf/block_partition_report.mjs`
- `dxf/block_partition_report.json`
- `dxf/block_partition_report.html`
- `dxf/issues/SUB-03-block-extraction-pipeline.md`
- `dxf/issues/SUB-04-block-viewer-and-zone-info.md`
### 체크리스트
- [ ] `INSERT` 기준 블록 분할 데이터 생성
- [ ] 회전/스케일 반영한 bounds 계산
- [ ] zone 분할 키(`Z-RxCy`) 부여
- [ ] HTML 뷰어에서 분할/목록 동시 확인
### 하위 이슈
- #SUB-03 블록 추출 파이프라인
- #SUB-04 분할 뷰어 + zone 정보 UI

View File

@@ -0,0 +1,15 @@
## [SUB] 레이어 규칙 및 위치 키 스키마 정의
- label: `dxf`
- parent: MASTER-01
### 작업 내용
- 레이어명 정규화 규칙 확정
- 키 포맷 정의: `LAYER::R{row}C{col}::####`
- 엔티티 타입별 대표 좌표 기준 정의
### 완료 조건
- 키 포맷 예시와 예외 케이스 문서화
- 레이어/좌표 기반으로 키 중복 없이 생성 확인

View File

@@ -0,0 +1,15 @@
## [SUB] 레이어 위치 키 결과 검증
- label: `dxf`
- parent: MASTER-01
### 작업 내용
- `center.dxf` 대상으로 키 생성 결과 검증
- 레이어별 개수 집계와 위치 분포 점검
- key 누락/충돌 여부 체크
### 완료 조건
- `layer_position_keys.json` 결과 검토 완료
- 레이어별 count 및 샘플 key 검증 로그 확보

View File

@@ -0,0 +1,15 @@
## [SUB] 블록 추출 파이프라인 구현
- label: `dxf`
- parent: MASTER-02
### 작업 내용
- BLOCK 정의 파싱
- INSERT 엔티티와 매핑
- 회전/스케일 반영한 world bounds 계산
### 완료 조건
- `block_partition_report.json`에 블록/파티션 정보 출력
- block name, layer, bounds, zoneKey 필드 검증 완료

View File

@@ -0,0 +1,15 @@
## [SUB] 도면 분할 뷰어 및 zone 정보 제공
- label: `dxf`
- parent: MASTER-02
### 작업 내용
- 파티션 rectangle 시각화
- zone/tag/size 목록 테이블 표시
- 모바일 포함 반응형 확인
### 완료 조건
- `block_partition_report.html`에서 도면 분할이 시각적으로 확인 가능
- 파티션 목록과 zone 정보 동기화 확인

18278
dxf/layer_position_keys.json Normal file

File diff suppressed because it is too large Load Diff

119
dxf/layer_position_keys.mjs Normal file
View File

@@ -0,0 +1,119 @@
import fs from "fs";
import path from "path";
import {
boundsFromPoints,
extractPolylineVertices,
first,
num,
parseDxfText,
pointsFromLWPolyline,
readDxfText,
} from "./lib/dxf_basic_parser.mjs";
function parseArgs(argv) {
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (!token.startsWith("--")) continue;
const key = token.slice(2);
const value = argv[i + 1];
if (!value || value.startsWith("--")) continue;
out[key] = value;
i += 1;
}
return out;
}
function normalizeLayer(layerName) {
return String(layerName || "0")
.trim()
.toUpperCase()
.replace(/[^A-Z0-9_]/g, "_");
}
function representativePoint(entity, entities, index) {
if (entity.type === "INSERT") return { point: { x: num(entity, 10), y: num(entity, 20) }, nextIndex: index };
if (entity.type === "LINE") {
const x1 = num(entity, 10);
const y1 = num(entity, 20);
const x2 = num(entity, 11);
const y2 = num(entity, 21);
return { point: { x: (x1 + x2) / 2, y: (y1 + y2) / 2 }, nextIndex: index };
}
if (entity.type === "CIRCLE" || entity.type === "ARC") {
return { point: { x: num(entity, 10), y: num(entity, 20) }, nextIndex: index };
}
if (entity.type === "LWPOLYLINE") {
const points = pointsFromLWPolyline(entity);
const box = boundsFromPoints(points);
return { point: box ? { x: box.cx, y: box.cy } : null, nextIndex: index };
}
if (entity.type === "POLYLINE") {
const parsed = extractPolylineVertices(entities, index);
const box = boundsFromPoints(parsed.points);
return { point: box ? { x: box.cx, y: box.cy } : null, nextIndex: parsed.nextIndex };
}
return { point: null, nextIndex: index };
}
function buildLayerPositionKeys(dxfPath, cellSize) {
const dxfText = readDxfText(dxfPath);
const { entities, headerBounds } = parseDxfText(dxfText);
const minX = Number.isFinite(headerBounds.minX) ? headerBounds.minX : 0;
const minY = Number.isFinite(headerBounds.minY) ? headerBounds.minY : 0;
const items = [];
const sequenceByLayer = new Map();
for (let i = 0; i < entities.length; i += 1) {
const entity = entities[i];
const layerRaw = first(entity, 8) ?? "0";
const layer = normalizeLayer(layerRaw);
const extracted = representativePoint(entity, entities, i);
i = extracted.nextIndex;
if (!extracted.point) continue;
const col = Math.floor((extracted.point.x - minX) / cellSize);
const row = Math.floor((extracted.point.y - minY) / cellSize);
const seq = (sequenceByLayer.get(layer) ?? 0) + 1;
sequenceByLayer.set(layer, seq);
const key = `${layer}::R${row}C${col}::${String(seq).padStart(4, "0")}`;
items.push({
key,
layer,
sourceLayer: layerRaw,
type: entity.type,
x: Number(extracted.point.x.toFixed(3)),
y: Number(extracted.point.y.toFixed(3)),
grid: { row, col },
});
}
const byLayer = {};
for (const item of items) byLayer[item.layer] = (byLayer[item.layer] ?? 0) + 1;
return {
meta: {
source: path.basename(dxfPath),
generatedAt: new Date().toISOString(),
cellSize,
entityCount: entities.length,
keyedItemCount: items.length,
bounds: headerBounds,
},
byLayer,
items,
};
}
const args = parseArgs(process.argv.slice(2));
const scriptDir = path.dirname(new URL(import.meta.url).pathname);
const dxfPath = path.resolve(args.input ?? path.join(scriptDir, "center.dxf"));
const outputPath = path.resolve(args.output ?? path.join(scriptDir, "layer_position_keys.json"));
const cellSize = Number(args.cell ?? 2000);
const result = buildLayerPositionKeys(dxfPath, Number.isFinite(cellSize) && cellSize > 0 ? cellSize : 2000);
fs.writeFileSync(outputPath, `${JSON.stringify(result, null, 2)}\n`, "utf8");
console.log(`saved: ${outputPath}`);

View File

@@ -0,0 +1,231 @@
import fs from "fs";
export function readDxfText(filePath) {
return fs.readFileSync(filePath, "utf8").replace(/\r/g, "");
}
export function parseDxfText(text) {
const pairs = parsePairs(text);
const sections = parseSections(pairs);
return {
sections,
headerBounds: parseHeaderBounds(sections.get("HEADER") ?? []),
entities: collectEntities(sections.get("ENTITIES") ?? []),
blocks: collectBlocks(sections.get("BLOCKS") ?? []),
};
}
export function first(item, code) {
const hit = item.pairs.find(([group]) => group === String(code));
return hit ? hit[1].trim() : undefined;
}
export function all(item, code) {
return item.pairs.filter(([group]) => group === String(code)).map(([, value]) => value.trim());
}
export function num(item, code, fallback = 0) {
const value = first(item, code);
return value == null || value === "" ? fallback : Number(value);
}
export function pointsFromLWPolyline(entity) {
const xs = all(entity, 10).map(Number);
const ys = all(entity, 20).map(Number);
const points = [];
for (let i = 0; i < xs.length; i += 1) {
points.push({ x: xs[i], y: ys[i] ?? 0 });
}
return points;
}
export function extractPolylineVertices(entityList, startIndex) {
const entity = entityList[startIndex];
const closed = (num(entity, 70) & 1) === 1;
const points = [];
let i = startIndex + 1;
while (i < entityList.length) {
const next = entityList[i];
if (next.type === "VERTEX") {
points.push({ x: num(next, 10), y: num(next, 20) });
i += 1;
continue;
}
if (next.type === "SEQEND") break;
break;
}
return { points, closed, nextIndex: i };
}
export function boundsFromPoints(points) {
if (!points.length) return null;
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const point of points) {
minX = Math.min(minX, point.x);
minY = Math.min(minY, point.y);
maxX = Math.max(maxX, point.x);
maxY = Math.max(maxY, point.y);
}
return {
minX,
minY,
maxX,
maxY,
width: maxX - minX,
height: maxY - minY,
cx: (minX + maxX) / 2,
cy: (minY + maxY) / 2,
};
}
export function transformPoint(point, insert, basePoint) {
const theta = (insert.rotation * Math.PI) / 180;
const localX = (point.x - basePoint.x) * insert.xScale;
const localY = (point.y - basePoint.y) * insert.yScale;
return {
x: insert.x + localX * Math.cos(theta) - localY * Math.sin(theta),
y: insert.y + localX * Math.sin(theta) + localY * Math.cos(theta),
};
}
export function computeEntityListBounds(entityList) {
const points = [];
for (let i = 0; i < entityList.length; i += 1) {
const entity = entityList[i];
if (entity.type === "LINE") {
points.push({ x: num(entity, 10), y: num(entity, 20) });
points.push({ x: num(entity, 11), y: num(entity, 21) });
continue;
}
if (entity.type === "CIRCLE" || entity.type === "ARC") {
const cx = num(entity, 10);
const cy = num(entity, 20);
const r = Math.abs(num(entity, 40));
points.push({ x: cx - r, y: cy - r });
points.push({ x: cx + r, y: cy + r });
continue;
}
if (entity.type === "INSERT") {
points.push({ x: num(entity, 10), y: num(entity, 20) });
continue;
}
if (entity.type === "LWPOLYLINE") {
points.push(...pointsFromLWPolyline(entity));
continue;
}
if (entity.type === "POLYLINE") {
const parsed = extractPolylineVertices(entityList, i);
points.push(...parsed.points);
i = parsed.nextIndex;
}
}
return boundsFromPoints(points);
}
function parsePairs(text) {
const lines = text.split("\n");
const pairs = [];
for (let i = 0; i < lines.length - 1; i += 2) {
pairs.push([lines[i].trim(), lines[i + 1]]);
}
return pairs;
}
function parseSections(pairs) {
const sections = new Map();
let sectionName = null;
let bucket = null;
for (const [code, value] of pairs) {
if (code === "0" && value === "SECTION") {
sectionName = null;
bucket = [];
continue;
}
if (code === "2" && bucket && sectionName === null) {
sectionName = value.trim();
sections.set(sectionName, bucket);
continue;
}
if (code === "0" && value === "ENDSEC") {
sectionName = null;
bucket = null;
continue;
}
if (bucket) bucket.push([code, value]);
}
return sections;
}
function collectEntities(sectionPairs) {
const entities = [];
let entity = null;
for (const [code, value] of sectionPairs) {
if (code === "0") {
if (entity) entities.push(entity);
if (value === "EOF") break;
entity = { type: value.trim(), pairs: [] };
}
if (entity) entity.pairs.push([code, value]);
}
if (entity) entities.push(entity);
return entities;
}
function collectBlocks(sectionPairs) {
const blocks = [];
let block = null;
let entity = null;
for (const [code, value] of sectionPairs) {
if (code === "0" && value === "BLOCK") {
block = { pairs: [], entities: [] };
entity = null;
continue;
}
if (code === "0" && value === "ENDBLK") {
if (entity) {
block.entities.push(entity);
entity = null;
}
if (block) blocks.push(block);
block = null;
continue;
}
if (!block) continue;
if (!entity) {
if (code === "0") entity = { type: value.trim(), pairs: [[code, value]] };
else block.pairs.push([code, value]);
continue;
}
if (code === "0") {
block.entities.push(entity);
entity = { type: value.trim(), pairs: [[code, value]] };
} else {
entity.pairs.push([code, value]);
}
}
return blocks;
}
function parseHeaderBounds(headerPairs) {
const header = {};
let current = null;
for (const [code, rawValue] of headerPairs) {
const value = rawValue.trim();
if (code === "9") {
current = value;
header[current] = {};
continue;
}
if (!current) continue;
header[current][code] = value;
}
return {
minX: Number(header.$EXTMIN?.["10"] ?? 0),
minY: Number(header.$EXTMIN?.["20"] ?? 0),
maxX: Number(header.$EXTMAX?.["10"] ?? 0),
maxY: Number(header.$EXTMAX?.["20"] ?? 0),
};
}