Files
Aislo/common_util/common_util_structure_station.ts
T
eomsangdonandClaude Opus 5.5 69ffd17317 feat(380-3): 노선 따라간 사토장 · 토취장 = 새 노선 일반 측점 맞춤 · test_322_2 마스터 판 독립
- follow_structures ↔ followStructures(intervalM): site 꼴 = 새 노선 일반 측점(격자 · 끝) 중 가장 가까운 곳 · 그 밖 정수 m 그대로
- 파이썬 snap_existing_station ↔ TS snapExistingStation · general_stations ↔ gridStations 짝
- 브라우저 노선 초안 따라감(Pipeline_Grade) = 측점 간격 넘김 · 서버 노선 저장 따라감 = 서버 간격
- test_322_2: B05 목록 고정 수 23 대신 both 목록 수와 같음(M02 켬끔 판마다 다름)
- 시험 test_380_3_site_follow(거울 · 가운데면 앞 측점 · 좌표 없음 그대로)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VmC34fsxxbweEG3RUjs3Mn
2026-10-17 15:40:32 +09:00

364 lines
17 KiB
TypeScript

/* =============================================================================
* common_util/common_util_structure_station.ts
* 구조물 · 관 기준 측점 = 정수 m(반올림 · .5 는 올림) · 노선 끝 안쪽(요구 167 · 272).
*
* 측점 값(측점 + 거리 · 누가거리)에 소수를 안 씀 — 일반 측점(격자)과 같은 m 면 서버 측점 만들기가
* 한 측점으로 합침(구조물 측점이 위). 234-1 의 「일반 측점 1 m 안 붙기」는 뺌(그냥 정수 · 사용자 167).
* 파이썬 짝 = `common_util/common_util_structure_station.py`(서버 자동 배치 · 노선 재투영).
* 거울 시험 = `resources/tester/test_234_1_structure_station.py`.
* 일반 측점 = 격자 · 시종점(구조물 측점 kind "irregular" 은 뺌) — 끝(노선 길이)을 넘지 않게 자르는 데만 ·
* 상세를 읽을 때 한 번 둔다.
*
* 심는 측점 = 구조물 표(catalog) 횡단도 부품(322-1) — anchor = 기준 하나 · span3 = 시작 · 기준 · 끝 · none = 없음.
*
* 측점 계획 한 벌(322-3 · `planStations`) — 관 · 구조물(현황) + 표 → 측점 · 역할 · 카드 이름 · 덮는 구조물 id ·
* 빈칸 경고 · 같은 m 는 하나(관이 먼저 · 이름 = 관 → 앞선 것). 파이썬 짝 = `common_util_structure_station.py`
* `plan_stations`(서버 `resolve_extra_stations`) · 거울 시험 = `resources/tester/test_322_3_plan_mirror.py`.
* 카드 목록 · B05 종단 · B06 종단 띠 · 3D 막대 · 미리 뜬 횡단 이름이 이 목록 하나를 씀.
*
* 측점 한 벌(272) — 측점을 심는 관 · 구조물(`plantedChainages`) = 서버 `resolve_extra_stations`
* (B05_Profile_Engine_Sections.py) 짝 · 같은 m 면 측점 하나 · 구조물이 위(`oneStationList`) = 서버
* `_merge_irregular_into_longitudinal`(B05_Profile_Router_Confirm.py) 짝. 거울 시험 =
* `resources/tester/test_272_1_station_list.py`. 종단 그래프 · 3D · 계획선 측점 줄(표 · ▲▼)이
* 이 목록 하나를 씀.
*
* 추가 측점(368-2 · 요구 240-21) — 사용자가 원지반선에서 넣은 정수 m(`plusStations`) · 측점 계획 끝에
* 붙임(주인 `plus-{m}` · 이름 "" · 같은 m 에 관 · 구조물이 있으면 그쪽이 이김) · 파이썬 `plan_stations(plus=)`
* 짝 · 읽는 곳은 화면이 `setPlusStations` 로 둠(초안 · 저장분 · 서버 묶음 = 없음).
* ========================================================================== */
import { cardTitle, catalogRow, shapeNeeds } from "./common_util_structure_catalog";
const EPS = 1e-6;
/* 같은 자리 거리(323-7 · 뜻마다 하나 · 파이썬은 `common_util_structure_station.py` 한 곳에서 가져다 씀):
* SAME_STATION_M 0.005 = 같은 측점(반올림 차이) — 여기
* EDGE_TOLERANCE_M · CHAINAGE_TOLERANCE_M 0.02 = 구간 끝 · 관 세트가 걸치는 측점(정본 0.01 m 끊음) — 벽 ·
* 포장 · 맹암거 · 관 세트 모듈(거울 시험이 tsc ESM 으로 따로 엮어 각자 둠 · 값은 파이썬 `EDGE_TOLERANCE_M`)
* PIPE_MATCH_M 0.51 = 관 · 구조물 자리와 측점 · 고름(정수 m · 옛 소수) — `design_selection` */
/** 같은 측점으로 볼 거리(m) — 서버 측점 만들기의 격자 붙임 폭(`Engine_Sections_Core`)과 같음. */
export const SAME_STATION_M = 0.005;
let general: number[] = [];
let listed: number[] = [];
/** 일반 측점 목록을 둔다 — 횡단 상세를 읽을 때마다(B05 · B06 한 노선). 구조물 측점까지 든 목록도 둠(380-2). */
export function setGeneralStations(
stations: ReadonlyArray<{ chainage_m: number; kind?: string }> | null | undefined,
): void {
general = (stations ?? [])
.filter((station) => station.kind !== "irregular")
.map((station) => station.chainage_m);
listed = (stations ?? []).map((station) => station.chainage_m);
}
export const generalStations = (): readonly number[] => general;
let plusSource: () => readonly number[] = () => [];
/** 추가 측점 읽는 곳을 둔다(368-2) — 부를 때마다 읽음(되돌리기 · 다른 보기가 바꿔도 같은 값). */
export function setPlusStations(source: (() => readonly number[]) | null): void {
plusSource = source ?? (() => []);
}
export const plusStations = (): readonly number[] => plusSource();
/** 추가 측점 주인 id 앞머리 — 측점 계획 · 종단 측점 id 가 `plus-{m}`. */
export const PLUS_OWNER_PREFIX = "plus-";
/** 기준 측점 = 정수 m(.5 는 올림) · 0 ~ 노선 끝(소수 끝은 그 아래 정수) 안. 두 번 맞춰도 같다. */
export function snapStructureStation(
chainageM: number,
stations: readonly number[] = general,
): number {
if (!Number.isFinite(chainageM)) return chainageM;
const end = stations.length ? Math.max(...stations) : Infinity;
const whole = Math.floor(chainageM + 0.5);
return Math.max(0, Math.min(whole, Math.floor(end + EPS)));
}
/** 방향키 한 걸음(1 m) — 맞춘 값이 제자리면 한 걸음 더 · 노선 밖이면 제자리. */
export function stepStructureStation(
fromM: number,
direction: 1 | -1,
stations: readonly number[] = general,
): number {
for (let steps = 1; steps <= 3; steps += 1) {
const next = snapStructureStation(fromM + direction * steps, stations);
if ((next - fromM) * direction > EPS) return next;
}
return fromM;
}
/** 이미 정수 m 인가(옛 소수 자료를 옮길 것을 가름). */
export const isSnappedStation = (
chainageM: number,
stations: readonly number[] = general,
): boolean => Math.abs(snapStructureStation(chainageM, stations) - chainageM) < EPS;
/* ── 기존 측점 맞춤(380-2 · 요구 241-8) — 새 측점을 안 심는 자리 꼴(site · 사토장 · 토취장) ── */
/** 기존 측점(일반 · 구조물 · 추가) — 오름차순 · 같은 m 하나.
* ponytail: 구조물 측점 = 마지막으로 읽은 횡단 상세 것 — 세션에서 새로 놓은 관 측점은 다시 읽을 때까지 빠짐. */
export const existingStations = (): number[] =>
[...new Set([...listed, ...plusSource()])].sort((a, b) => a - b);
/** 가장 가까운 기존 측점(가운데면 앞 측점) — 목록이 비면 정수 m 맞춤. 두 번 맞춰도 같다. */
export function snapExistingStation(
chainageM: number,
stations: readonly number[] = existingStations(),
): number {
if (!Number.isFinite(chainageM) || !stations.length) return snapStructureStation(chainageM);
return stations.reduce((best, at) => {
const [gap, bestGap] = [Math.abs(at - chainageM), Math.abs(best - chainageM)];
return gap < bestGap - EPS || (gap < bestGap + EPS && at < best) ? at : best;
});
}
/** 격자 측점 + 끝 측점 — 파이썬 `general_stations` 짝(노선 따라감 site 맞춤 · 380-3). */
export function gridStations(totalM: number, intervalM: number): number[] {
if (!(totalM > 0 && intervalM > 0)) return [0];
const values = Array.from(
{ length: Math.floor(totalM / intervalM) + 1 },
(_, i) => i * intervalM,
);
if (totalM - values[values.length - 1] > EPS) values.push(totalM);
return values;
}
/** 놓는 꼴 따라 맞춤 — site = 가장 가까운 기존 측점 · 그 밖 = 정수 m. */
export const snapStationFor = (chainageM: number, placement: string | null | undefined): number =>
placement === "site" ? snapExistingStation(chainageM) : snapStructureStation(chainageM);
/* ── 측점을 심는 자리(272 · 서버 `resolve_extra_stations` · `is_station_planting_type` 짝) ── */
export interface PlantingPipe {
chainage_m: number;
facility?: string | null;
start_m?: number | null;
end_m?: number | null;
}
export interface PlantingStructure {
type_id: string;
chainage_m?: number | null;
start_m?: number | null;
end_m?: number | null;
}
export interface PlantingType {
type_id: string;
group: string;
placement: string;
managed_by?: string | null;
}
/** 측점 하나 — 구간형(독립 기슭막이 · C · D군)은 시작 · 기준 · 끝 셋, 그 밖은 기준 하나. */
export interface StationMark {
chainage_m: number;
role: "start" | "anchor" | "end";
}
function marksOf(
start: number | null | undefined,
anchor: number | null | undefined,
end: number | null | undefined,
interval: boolean,
): StationMark[] {
const marks: Array<[StationMark["role"], number | null | undefined]> = interval
? [
["start", start],
["anchor", anchor],
["end", end],
]
: [["anchor", anchor]];
return marks.flatMap(([role, at]) =>
typeof at === "number" && Number.isFinite(at) ? [{ chainage_m: at, role }] : [],
);
}
/** 관 시설 하나가 심는 측점 — 표 횡단도(독립 기슭막이 = span3 · 물넘이포장 포함 그 밖 = anchor · 286-1). */
export function pipeStationMarks(pipe: PlantingPipe): StationMark[] {
const station = catalogRow(pipe.facility ?? "pipe")?.station ?? "anchor";
if (station === "none") return [];
return marksOf(pipe.start_m, pipe.chainage_m, pipe.end_m, station === "span3");
}
/** 구조물 하나가 심는 측점 — 표 횡단도(anchor = 기준 · span3 = 시작 · 기준 · 끝) · 관 지점 정본 소관 · 모르는 종류 = 없음. */
export function structureStationMarks(
structure: PlantingStructure,
type: PlantingType | undefined,
): StationMark[] {
const row = type && catalogRow(type.type_id);
if (!row || row.owner === "pipe_points" || row.station === "none") return [];
const anchor = structure.chainage_m ?? structure.start_m;
return marksOf(structure.start_m, anchor, structure.end_m, row.station === "span3");
}
/* ── 측점 계획 한 벌(322-3 · 파이썬 `plan_stations` 짝) ── */
export interface PlanPipe extends PlantingPipe {
/** 관 세션 id — 없으면 자리로 지음(`pipe-{누가거리 2자리}`). */
id?: string | null;
options?: Record<string, unknown> | null;
}
export interface PlanStructure extends PlantingStructure {
structure_id?: string | null;
options?: Record<string, unknown> | null;
}
export interface PlanType extends PlantingType {
options?: ReadonlyArray<{ key: string; default?: unknown }>;
}
/** 측점 한 곳 — 같은 m 에 놓인 관 · 구조물을 함께 덮음. */
export interface PlannedStation {
chainage_m: number;
role: StationMark["role"];
/** 카드 · 측점 이름 — 관이 있으면 첫 관 · 아니면 앞선 구조물(표 카드 이름). */
title: string;
/** 덮는 구조물 id(관 = 세션 id · 구조물 = structure_id). */
owners: string[];
/** 빈칸 경고 — 형상 부품 필수 칸 중 값이 빈 옵션 키(비면 그 그림이 안 섬). */
blank: string[];
}
const empty = (value: unknown): boolean => value === undefined || value === null || value === "";
/** 형상 부품 필수 칸 중 값이 빈 키(관경 · 벽 높이 · 맹암거 높이 · 물넘이 높이 — 정의 기본값으로 안 채움). */
export const blankKeys = (
typeId: string,
options: Record<string, unknown> | null | undefined,
): string[] => shapeNeeds(typeId).filter((key) => empty(options?.[key]));
/** 관 · 구조물 → 측점 계획(오름차순 · 같은 m 하나). 표에 없는 종류는 뺌. `registry` = 종류 → 옵션
* 기본값(카드 이름 빈칸 · 없으면 `types` 정의 기본값 · 횡단 관 세트 `registryDefaults` 와 같은 표). */
export function planStations(
pipes: ReadonlyArray<PlanPipe>,
structures: ReadonlyArray<PlanStructure>,
types: ReadonlyArray<PlanType>,
registry?: Readonly<Record<string, Record<string, unknown>>>,
plus: ReadonlyArray<number> = plusSource(),
): PlannedStation[] {
const byId = new Map(types.map((type) => [type.type_id, type]));
const defaults = (typeId: string): Record<string, unknown> =>
registry?.[typeId] ??
Object.fromEntries((byId.get(typeId)?.options ?? []).map((o) => [o.key, o.default]));
type Mark = StationMark & { title: string; owner: string; blank: string[]; pipe: boolean };
const own: Mark[] = [
...pipes.flatMap((pipe) => {
const facility = pipe.facility ?? "pipe";
if (!catalogRow(facility)) return [];
const title = cardTitle(facility, pipe.options, defaults(facility));
const owner = pipe.id ?? `pipe-${pipe.chainage_m.toFixed(2)}`;
const blank = blankKeys(facility, pipe.options);
return pipeStationMarks(pipe).map((m) => ({ ...m, title, owner, blank, pipe: true }));
}),
...structures.flatMap((structure) => {
const marks = structureStationMarks(structure, byId.get(structure.type_id));
const anchor = marks.find((m) => m.role === "anchor")?.chainage_m ?? 0;
const title = cardTitle(structure.type_id, structure.options, defaults(structure.type_id));
const owner = structure.structure_id ?? `structure-${anchor.toFixed(2)}`;
const blank = blankKeys(structure.type_id, structure.options);
return marks.map((m) => ({ ...m, title, owner, blank, pipe: false }));
}),
];
// 추가 측점 — 같은 m 에 관 · 구조물이 있으면 뺌(그쪽이 이김)
const added: Mark[] = plus
.filter((at) => own.every((m) => Math.abs(m.chainage_m - at) >= SAME_STATION_M))
.map((at) => ({
chainage_m: at,
role: "anchor",
title: "",
owner: `${PLUS_OWNER_PREFIX}${Math.round(at)}`,
blank: [],
pipe: false,
}));
const marks = [...own, ...added].sort((a, b) => a.chainage_m - b.chainage_m);
const out: Array<PlannedStation & { pipe: boolean }> = [];
for (const mark of marks) {
const last = out[out.length - 1];
if (last && Math.abs(mark.chainage_m - last.chainage_m) < SAME_STATION_M) {
if (mark.pipe && !last.pipe) Object.assign(last, { title: mark.title, pipe: true });
if (!last.owners.includes(mark.owner)) last.owners.push(mark.owner);
for (const key of mark.blank) if (!last.blank.includes(key)) last.blank.push(key);
continue;
}
out.push({
chainage_m: mark.chainage_m,
role: mark.role,
title: mark.title,
owners: [mark.owner],
blank: [...mark.blank],
pipe: mark.pipe,
});
}
return out.map(({ pipe: _pipe, ...station }) => station);
}
/** 측점을 심는 자리 전부(오름차순 · 같은 m 하나) — 측점 계획의 누가거리(서버 `resolve_extra_stations`). */
export function plantedChainages(
pipes: ReadonlyArray<PlanPipe>,
structures: ReadonlyArray<PlanStructure>,
types: ReadonlyArray<PlanType>,
): number[] {
return planStations(pipes, structures, types).map((station) => station.chainage_m);
}
/* ── 측점 한 벌(272 · 서버 `_merge_irregular_into_longitudinal` 짝) ── */
export interface ListedStation {
chainage_m: number;
kind?: string;
/** 구조물 측점이 얹힌 격자 자리 — 구조물이 떠나면 일반 측점으로 돌아옴(서버 표시). */
grid?: boolean;
structure?: string;
}
/**
* 측점 한 벌 = 서버 측점 중 일반 측점(격자 · 시종점 · 구조물이 떠난 격자 자리는 글 떼고 일반으로) +
* 지금 심긴 구조물 측점(`planted`). 같은 m 면 구조물 측점 하나(일반은 숨김) · 서버의 구조물 측점은
* 지금 목록이 갈음(옮긴 관의 옛 자리가 안 남음).
*/
export function oneStationList<S extends ListedStation, P extends { chainage_m: number }>(
server: ReadonlyArray<S>,
planted: ReadonlyArray<P>,
): Array<S | P> {
const general = server
.filter((station) => station.kind !== "irregular" || station.grid)
.filter((station) =>
planted.every((mark) => Math.abs(mark.chainage_m - station.chainage_m) >= SAME_STATION_M),
)
.map((station) => {
if (!station.grid && station.structure === undefined) return station;
const { grid: _grid, structure: _structure, ...rest } = station;
return { ...rest, kind: station.kind === "irregular" ? "regular" : station.kind } as S;
});
return [...general, ...planted].sort((a, b) => a.chainage_m - b.chainage_m);
}
/**
* 사라진 구조물 측점(`gone`)의 계획선 꼭짓점을 새 측점(`born`)으로 옮기거나 지운다 — 서버
* `_follow_moved_stations`(B05_Profile_Router_Confirm.py) 짝: 0.006m 안 반올림 차이 · 옛 소수 측점의
* 정수 m 맞춤 자리(272)면 높이 그대로 옮기고, 나머지는 지움(측점 없는 꼭짓점이 계획선을 꺾지 않게).
*/
export function followMovedNodes<N extends { chainage_m: number }>(
nodes: ReadonlyArray<N>,
gone: ReadonlyArray<number>,
born: ReadonlyArray<number>,
): N[] {
const target = (old: number): number | null => {
const near = born.find((value) => Math.abs(value - old) < 0.006);
if (near !== undefined) return near;
const snapped = Math.floor(old + 0.5);
return born.some((value) => Math.abs(value - snapped) < EPS) ? snapped : null;
};
return nodes.flatMap((node) => {
const old = gone.find((value) => Math.abs(value - node.chainage_m) < 0.006);
if (old === undefined) return [node];
const to = target(old);
return to === null ? [] : [{ ...node, chainage_m: to }];
});
}