diff --git a/A00_Common/design/design_selection.ts b/A00_Common/design/design_selection.ts index de688e943..0e16185a5 100644 --- a/A00_Common/design/design_selection.ts +++ b/A00_Common/design/design_selection.ts @@ -97,6 +97,9 @@ export function resolveSelection( return { pipeChainageM: null, structureId: hit?.structure_id ?? null }; } +/** 측점 하나 고름(횡단 카드 · 종단 측점선)이 덮어 열어도 되는 군 — 노면공(G군)은 뺌(152-5 · B05 = B06 216-1). */ +export const coversAtStation = (group: string | undefined): boolean => group !== "G"; + /* ── 세션 값 + 알림 ─────────────────────────────────────────────────────── */ interface Stored { diff --git a/A00_Common/design/design_view_profile.ts b/A00_Common/design/design_view_profile.ts index 4124b09a5..9a1fe7824 100644 --- a/A00_Common/design/design_view_profile.ts +++ b/A00_Common/design/design_view_profile.ts @@ -31,7 +31,13 @@ import { restoreStructurePick, wireStructurePick, } from "../../B05_Profile/B05_Profile_UI_Structure_Pick_Session"; -import { NO_SELECTION, nearestWithin, readSelection, selectDesign } from "./design_selection"; +import { + coversAtStation, + NO_SELECTION, + nearestWithin, + readSelection, + selectDesign, +} from "./design_selection"; import type { DesignPageHost } from "./design_page"; import { bindDesignView, @@ -223,6 +229,11 @@ export async function mountProfileView( selectMarker: (id) => viewer.markers.selectStation(id), selectGraph: (id, chainageM) => selectGraphAt(id, chainageM ?? null), selectSidebar: (chainageM) => panel.structures.selectPipeByChainage(chainageM), + // 측점선 · 3D 띠 고름 = 횡단 카드 고름(B06 showAtChainage)과 같은 규칙 · 같은 함수(216-1) + openAtStation: (chainageM) => + panel.structures.selectAt({ chainageM, structureId: null }, (entry) => + coversAtStation(bridge.typeGroup(entry.type_id)), + ), selectBasin: (chainageM) => profilePanel.drainage.selectBasinByChainage(chainageM), selectPipeForm: (chainageM) => profilePanel.drainage.selectPipeAtChainage(chainageM), markStation: (chainageM) => profilePanel.drainage.markStation(chainageM), diff --git a/B04_PreProcess/B04_PreProcess_Router_Basins.py b/B04_PreProcess/B04_PreProcess_Router_Basins.py index 20429f91a..bbbb4973c 100644 --- a/B04_PreProcess/B04_PreProcess_Router_Basins.py +++ b/B04_PreProcess/B04_PreProcess_Router_Basins.py @@ -91,7 +91,7 @@ def _build( return detail, carried -# 관 보호공 · 유입 집수정 높이 칸 — 새 관 기본 = 관경 + 0.5(139-1) +# 관 보호공 · 유입 집수정 높이 칸 — 새 관 기본 = 관경 + 0.5(139-1) · 유입 흙막이만 + 0.7(211-1) PIPE_HEIGHT_KEYS = ("inlet_revet_height_m", "outlet_revet_height_m", "inlet_basin_height_m") @@ -130,7 +130,10 @@ def _apply_new_defaults( if diameter_m > 0: for key in PIPE_HEIGHT_KEYS: if key in keys: - options.setdefault(key, pipe_wall_min_height_m(diameter_m)) + side = ( + "inlet" if key == "inlet_revet_height_m" else "" + ) # 유입 흙막이 + 0.7(211-1) + options.setdefault(key, pipe_wall_min_height_m(diameter_m, side)) if point.facility == "ford_bridge" and "ford_height_m" not in options: flow = (flows or {}).get(round(point.chainage_m, 2)) height = ford_height_m(flow, float(options.get("ford_width_m") or 0)) diff --git a/B05_Profile/B05_Profile_Engine_Grade_Alignment.py b/B05_Profile/B05_Profile_Engine_Grade_Alignment.py index 254b252d8..82e8e274f 100644 --- a/B05_Profile/B05_Profile_Engine_Grade_Alignment.py +++ b/B05_Profile/B05_Profile_Engine_Grade_Alignment.py @@ -158,6 +158,62 @@ def tangent_elevation(pvi_s: np.ndarray, pvi_z: np.ndarray, targets: np.ndarray) return np.interp(targets, pvi_s, pvi_z) +#: 반올림만 다른 같은 측점(m) — 관 측점 0.001m(자동설계) ↔ 0.01m(화면 저장) 차이. +#: 화면 `SAME_STATION_SNAP_M`(B05_Profile_UI_Profile_Alignment.ts) 와 짝. +SAME_STATION_SNAP_M = 0.006 + + +def _nearest_station(value: float, station_s: np.ndarray) -> float | None: + if not station_s.size: + return None + near = float(station_s[int(np.argmin(np.abs(station_s - value)))]) + return near if abs(near - value) < SAME_STATION_SNAP_M else None + + +def snap_to_stations( + base_s: np.ndarray, + base_z: np.ndarray, + edits: dict[str, dict[str, float]], + station_s: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, dict[str, dict[str, float]]]: + """측점 0.006m 안의 꼭짓점(base_pvi) · 편집 키를 그 측점으로 모은다(213-1). + + 관 측점이 반올림으로 옮겨도(263.206 → 263.21) 꼭짓점 · 편집 키는 옛 글자로 남아, 새 측점 + 편집과 0.004m 사이 두 꼭짓점이 됨(−15000% 계단 · 숨은 측점). 겹치면 측점 위 것이 이김. + 옮긴 꼭짓점은 옛 선의 측점 높이를 받아 측점 계획고가 안 바뀜. 양 끝 · 측점에서 먼 키는 그대로. + """ + last = len(base_s) - 1 + nodes: dict[float, tuple[float, float, float]] = {} + for index, (s, z) in enumerate(zip(base_s.tolist(), base_z.tolist())): + near = None if index in (0, last) else _nearest_station(s, station_s) + at = s if near is None else near + gap = 0.0 if near is None else abs(near - s) + slot = round(at, _KEY_DECIMALS) + if slot not in nodes or gap < nodes[slot][0]: + # 옮긴 꼭짓점 높이 = 옛 선의 그 측점 높이 — 측점 계획고가 그대로 + nodes[slot] = (gap, at, z if near is None else float(np.interp(at, base_s, base_z))) + ordered = [nodes[slot] for slot in sorted(nodes)] + snapped: dict[str, dict[str, float]] = {} + for name, values in edits.items(): + best: dict[str, tuple[float, float]] = {} + for key, value in values.items(): + try: + chainage = float(key) + except (TypeError, ValueError): + chainage = float("nan") + near = _nearest_station(chainage, station_s) if np.isfinite(chainage) else None + target = key if near is None else chainage_key(near) + gap = 0.0 if near is None else abs(near - chainage) + if target not in best or gap < best[target][0]: + best[target] = (gap, value) + snapped[name] = {key: value for key, (_, value) in best.items()} + return ( + np.array([item[1] for item in ordered], dtype=np.float64), + np.array([item[2] for item in ordered], dtype=np.float64), + snapped, + ) + + def resolve_pvi( base_s: np.ndarray, base_z: np.ndarray, @@ -407,6 +463,22 @@ def build_alignment( if value is not None } + station_s = np.array( + sorted( + float(station["chainage_m"]) + for station in stations + if isinstance(station.get("chainage_m"), (int, float)) + ), + dtype=np.float64, + ) + base_s, base_z, snapped = snap_to_stations( + base_s, + base_z, + {"station_offsets": station_offsets, "curve_radii": curve_radii}, + station_s, + ) + station_offsets, curve_radii = snapped["station_offsets"], snapped["curve_radii"] + pvi_s, pvi_z, sources = resolve_pvi(base_s, base_z, station_offsets) curves, warnings = build_curves( pvi_s, pvi_z, policy, curve_radii, only_explicit=only_explicit_curves diff --git a/B05_Profile/B05_Profile_Router_Confirm.py b/B05_Profile/B05_Profile_Router_Confirm.py index c21c05004..8e5117630 100644 --- a/B05_Profile/B05_Profile_Router_Confirm.py +++ b/B05_Profile/B05_Profile_Router_Confirm.py @@ -214,27 +214,41 @@ def _follow_moved_stations(data: dict[str, Any], before: list[float]) -> dict[st None, ) moves[chainage_key(old)] = None if near is None else chainage_key(near) + + def moved(value: float) -> tuple[bool, str | None]: + """옛 측점 0.006m 안이면 (참, 옮길 키 · 지우면 None) — 옛 글자(263.206)도 같은 측점(213-1). + 남은 측점 위 값은 그대로.""" + if chainage_key(value) in after_keys: + return False, None + for old_key, new_key in moves.items(): + if abs(float(old_key) - value) < _SAME_STATION_M: + return True, new_key + return False, None + edits = stored.get("edits") or {} next_edits: dict[str, dict[str, Any]] = {} changed = False for name in ("station_offsets", "curve_radii"): values = dict(edits.get(name) or {}) - for old_key, new_key in moves.items(): - if old_key in values: - value = values.pop(old_key) - if new_key is not None: - values.setdefault(new_key, value) - changed = True + # 옛 측점 글자 그대로인 키가 먼저 — 반올림 글자보다 이김 + for key in sorted(values, key=lambda item: item not in moves): + hit, new_key = moved(float(key)) + if not hit: + continue + value = values.pop(key) + if new_key is not None: + values.setdefault(new_key, value) + changed = True next_edits[name] = values base: list[dict[str, Any]] = [] for node in stored["base_pvi"]: - key = chainage_key(node["chainage_m"]) - if key not in moves: + hit, new_key = moved(float(node["chainage_m"])) + if not hit: base.append(node) continue changed = True - if moves[key] is not None: - base.append({**node, "chainage_m": float(moves[key])}) + if new_key is not None: + base.append({**node, "chainage_m": float(new_key)}) if not changed: return None stored["base_pvi"] = base diff --git a/B05_Profile/B05_Profile_UI_Page_Structures.ts b/B05_Profile/B05_Profile_UI_Page_Structures.ts index c52541f09..296298433 100644 --- a/B05_Profile/B05_Profile_UI_Page_Structures.ts +++ b/B05_Profile/B05_Profile_UI_Page_Structures.ts @@ -361,6 +361,8 @@ export function createStructuresBridge(deps: StructuresBridgeDeps) { }, /** 그래프·3D가 쓰는 현재 비정규 측점 목록(물넘이포장 제외 — 알약 레인 몫). */ irregularStations: () => withoutFordPavement(irregularStations), + /** 구조물 종류의 군(A~G · 모르면 undefined) — 측점 고름이 덮어 열 구조물을 가름(216-1). */ + typeGroup: (typeId: string) => structureTypeMap.get(typeId)?.group, /** 관 지점 목록이 바뀜 — 측점 투영과 알약 레인을 한 번에 맞춘다. */ setPipes(pipes: PipeProjection[]): void { pipeStations = pipesToStations(pipes); diff --git a/B05_Profile/B05_Profile_UI_Profile_Alignment.ts b/B05_Profile/B05_Profile_UI_Profile_Alignment.ts index 1a6c62b19..c30957a82 100644 --- a/B05_Profile/B05_Profile_UI_Profile_Alignment.ts +++ b/B05_Profile/B05_Profile_UI_Profile_Alignment.ts @@ -182,6 +182,65 @@ export function toAlignmentBase(alignment: ProfileAlignment): AlignmentBase { }; } +/** 반올림만 다른 같은 측점(m) — 서버 `SAME_STATION_SNAP_M`(B05_Profile_Engine_Grade_Alignment.py) 와 짝. */ +const SAME_STATION_SNAP_M = 0.006; + +function nearestStation(value: number, stationS: number[]): number | null { + let near: number | null = null; + stationS.forEach((station) => { + if (near === null || Math.abs(station - value) < Math.abs(near - value)) near = station; + }); + return near !== null && Math.abs(near - value) < SAME_STATION_SNAP_M ? near : null; +} + +function snapKeys(values: Record, stationS: number[]): Record { + const best = new Map(); + Object.entries(values).forEach(([key, value]) => { + const chainage = Number(key); + const near = Number.isFinite(chainage) ? nearestStation(chainage, stationS) : null; + const target = near === null ? key : chainageKey(near); + const gap = near === null ? 0 : Math.abs(near - chainage); + const held = best.get(target); + if (!held || gap < held.gap) best.set(target, { gap, value }); + }); + return Object.fromEntries([...best].map(([key, entry]) => [key, entry.value])); +} + +/** + * 측점 0.006m 안의 꼭짓점(base_pvi) · 편집 키를 그 측점으로 모은다(213-1) — 서버 + * `snap_to_stations` 와 같은 규칙. 관 측점이 반올림으로 옮겨도(263.206 → 263.21) 옛 글자로 남아 + * 0.004m 사이 두 꼭짓점이 되던 흠. 겹치면 측점 위 것이 이김 · 옮긴 꼭짓점은 옛 선의 측점 높이 + * (측점 계획고 그대로) · 양 끝 · 측점에서 먼 키는 그대로. + */ +function snapToStations( + base: AlignmentBase, + edits: AlignmentEdits, +): { basePvi: AlignmentNode[]; edits: AlignmentEdits } { + const stationS = base.stations.map((station) => station.chainage_m); + const baseS = base.basePvi.map((node) => node.chainage_m); + const baseZ = base.basePvi.map((node) => node.elevation_m); + const last = base.basePvi.length - 1; + const nodes = new Map(); + base.basePvi.forEach((node, index) => { + const near = index === 0 || index === last ? null : nearestStation(node.chainage_m, stationS); + const at = near ?? node.chainage_m; + const gap = near === null ? 0 : Math.abs(near - node.chainage_m); + const slot = Number(at.toFixed(3)); + const held = nodes.get(slot); + // 옮긴 꼭짓점 높이 = 옛 선의 그 측점 높이 — 측점 계획고가 그대로 + const elevation = near === null ? node.elevation_m : interpolate(baseS, baseZ, at); + if (!held || gap < held.gap) + nodes.set(slot, { gap, node: { chainage_m: at, elevation_m: elevation } }); + }); + return { + basePvi: [...nodes.keys()].sort((a, b) => a - b).map((slot) => nodes.get(slot)!.node), + edits: { + station_offsets: snapKeys(edits.station_offsets, stationS), + curve_radii: snapKeys(edits.curve_radii, stationS), + }, + }; +} + /** 자동 변화점에 사용자 편집 측점을 합쳐 최종 변화점 집합을 만든다. */ function resolvePvi( base: AlignmentBase, @@ -316,8 +375,10 @@ function normalizeEdits(edits: AlignmentEdits | undefined): AlignmentEdits { }; } -export function buildAlignment(base: AlignmentBase, input: AlignmentEdits): ProfileAlignment { - const edits = normalizeEdits(input); +export function buildAlignment(raw: AlignmentBase, input: AlignmentEdits): ProfileAlignment { + const snapped = snapToStations(raw, normalizeEdits(input)); + const base: AlignmentBase = { ...raw, basePvi: snapped.basePvi }; + const edits = snapped.edits; const warnings: string[] = []; const nodes = resolvePvi(base, edits.station_offsets); const pviS = nodes.map((node) => node.chainage_m); diff --git a/B05_Profile/B05_Profile_UI_Selection.ts b/B05_Profile/B05_Profile_UI_Selection.ts index cc4f393ed..23efb7f6f 100644 --- a/B05_Profile/B05_Profile_UI_Selection.ts +++ b/B05_Profile/B05_Profile_UI_Selection.ts @@ -27,6 +27,9 @@ export interface SelectionSyncPorts { selectGraph: (stationId: string | null, chainageM?: number | null) => void; /** 좌측 구조물 폼 선택(누가거리 기준). */ selectSidebar: (chainageM: number | null) => void; + /** 측점 하나 고름(측점선 · 3D 띠) → 좌측 폼 — 횡단 카드 고름과 같은 규칙(관 → 덮는 구조물 · 노면공 뺌 → + * 없으면 폼 비움 · 216-1). 없으면 selectSidebar. */ + openAtStation?: (chainageM: number | null) => void; /** 배수유역도 세부유역 강조(누가거리 기준). */ selectBasin: (chainageM: number | null) => void; /** 배수유역도 계획선 위 측점 마킹(누가거리 기준). 유역 없는 구조물도 위치를 보여 준다. */ @@ -79,17 +82,18 @@ export function createSelectionSync(ports: SelectionSyncPorts): SelectionSync { // 측점선 · 3D 띠 · 표 고름도 고름 한 칸에 — 일반 측점을 안 적어 옛 배관 고름이 이겼음(188-1) const at = stationId === null ? null : (station?.chainage_m ?? ports.regularChainage?.(stationId)); - if (at !== undefined) ports.remember?.(at); - // 규칙 측점을 고른 것이면 구조물 폼은 건드리지 않는다(고를 항목이 없다). - if (stationId !== null && !stationId.startsWith(prefix)) return; + if (at === undefined) return; // 모르는 측점 — 폼 · 고름 한 칸 안 건드림 ports.setSyncing(true); try { - ports.selectSidebar(station ? station.chainage_m : null); + // 일반 측점도 폼이 따라감 — 일반 측점이면 폼을 안 건드려 옛 폼이 남았음(B06 카드 규칙 · 216-1) + (ports.openAtStation ?? ports.selectSidebar)(at); ports.selectPipeForm?.(station && isPipeStation(station) ? station.chainage_m : null); ports.selectStructure3D?.(station ? station.chainage_m : null); } finally { ports.setSyncing(false); } + // 폼이 연 구조물 · 푼 관 알림이 적은 고름을 이 측점으로 덮음 — 마지막 고름 하나(188-1) + ports.remember?.(at); }, selectStationOfPipe(chainageM) { if (ports.isSyncing()) return; diff --git a/B05_Profile/B05_Profile_UI_Structures_Panel.ts b/B05_Profile/B05_Profile_UI_Structures_Panel.ts index 6ea28ae39..2b7e97e5e 100644 --- a/B05_Profile/B05_Profile_UI_Structures_Panel.ts +++ b/B05_Profile/B05_Profile_UI_Structures_Panel.ts @@ -617,8 +617,8 @@ export function createStructuresSection( loadPipeForm(pipe); }, resolveAt: (selection) => resolveSelection(selection, pipeFacilities, structures), - selectAt(selection) { - const hit = resolveSelection(selection, pipeFacilities, structures); + selectAt(selection, coverable) { + const hit = resolveSelection(selection, pipeFacilities, structures, coverable); if (hit.pipeChainageM !== null) this.selectPipeByChainage(hit.pipeChainageM); else this.selectById(hit.structureId); return hit; diff --git a/B05_Profile/B05_Profile_UI_Structures_Panel_Types.ts b/B05_Profile/B05_Profile_UI_Structures_Panel_Types.ts index 7183dc422..589623338 100644 --- a/B05_Profile/B05_Profile_UI_Structures_Panel_Types.ts +++ b/B05_Profile/B05_Profile_UI_Structures_Panel_Types.ts @@ -174,8 +174,11 @@ export interface StructuresSection { /** 측점 · 구조물 고름 한 값을 폼이 열 항목으로 푼다 — 열지는 않는다(관 계열이 먼저). */ resolveAt: (selection: DesignSelection) => ResolvedSelection; /** 고름 한 값으로 폼을 연다(관 → 구조물 순) — 어느 화면에서 골라도 같은 거리 · 같은 순서다. - * 고를 항목이 없으면 폼을 해제한다. 푼 결과를 돌려준다. */ - selectAt: (selection: DesignSelection) => ResolvedSelection; + * 고를 항목이 없으면 폼을 해제한다. 푼 결과를 돌려준다. `coverable` = 덮어 열어도 되는 구조물(측점 고름 · 216-1). */ + selectAt: ( + selection: DesignSelection, + coverable?: (entry: StructureInstance) => boolean, + ) => ResolvedSelection; /** 종단 그래프 우클릭으로 타입을 지정해 추가한다. */ addAt: (chainageM: number, typeId: string) => void; /** 종단 그래프에서 마크를 끌어 옮긴다. 옮겼으면 true. */ diff --git a/B06_Section/B06_Section_Api_Types.ts b/B06_Section/B06_Section_Api_Types.ts index 88f8e135f..7c09a92ed 100644 --- a/B06_Section/B06_Section_Api_Types.ts +++ b/B06_Section/B06_Section_Api_Types.ts @@ -633,8 +633,16 @@ export interface CrossSectionPatch { export type CrossCellSource = | { src: "area"; key: string } | { src: "length"; start: [number, number]; end: [number, number] } + | { src: "length" | "area"; pieces: CrossPickPiece[] } | { src: "text"; text: string }; +/** [상세] 고른 선 조각(209-1) — 어느 선 · 두 끝 [offset, 표고](m). */ +export interface CrossPickPiece { + line: "design" | "ground" | "spoil" | "structure"; + start: [number, number]; + end: [number, number]; +} + /** [상세] 표 손질 — 칸 출처(표 키 →) · 더한 행(`after` 아래 · 없으면 끝) · 더한 열(오른쪽 끝). */ export interface CrossDetailTable { cells: Record; diff --git a/B06_Section/B06_Section_Engine_Culvert.py b/B06_Section/B06_Section_Engine_Culvert.py index 24ce66c42..4f50a3c08 100644 --- a/B06_Section/B06_Section_Engine_Culvert.py +++ b/B06_Section/B06_Section_Engine_Culvert.py @@ -78,19 +78,23 @@ REVET_FACE_SLOPE = 0.3 # `test_b06_pipe_wall_height_mirror`. REVET_HEIGHT_STEP_M = 0.1 # 높이 눈금 REVET_EMBED_DEPTH_M = 0.5 # 근입 깊이 +# 관 보호공 **유입** 흙막이 빈 칸 기본 = 관경(올림) + 0.7 — 유출 · 집수정은 근입 0.5 그대로(211-1). +# ⚠ TS 짝 `common_util_culvert_sets.INLET_REVET_ADD_M` · `_Cross_Culvert_Const.INLET_REVET_ADD_M`. +INLET_REVET_ADD_M = 0.7 # 옛 정의 기본 높이(10-6 표 · 관경 무관) — 관경 > 1.0 관에 이 값이면 관 윗면보다 낮은 벽이라 # 읽을 때 관경 기준 값으로 봄(139-1). OLD_PIPE_WALL_DEFAULT_M = 1.5 -def pipe_wall_min_height_m(diameter_m: float) -> float: +def pipe_wall_min_height_m(diameter_m: float, side: str = "") -> float: """관 벽 **순수 높이**(근입 포함) 기본값 = 관경(0.1m 로 올림) + 근입 0.5 — 벽 윗면 = 관 윗면(139-1). - 관 · 유입 집수정 높이 칸의 새 기본값이자 빈 칸 값. + 관 · 유입 집수정 높이 칸의 새 기본값이자 빈 칸 값. `side="inlet"`(유입 흙막이) = + 0.7(211-1). """ raw = float(diameter_m) steps = math.ceil(raw / REVET_HEIGHT_STEP_M - 1e-9) - return round(steps * REVET_HEIGHT_STEP_M + REVET_EMBED_DEPTH_M, 3) + add = INLET_REVET_ADD_M if side == "inlet" else REVET_EMBED_DEPTH_M + return round(steps * REVET_HEIGHT_STEP_M + add, 3) def pipe_wall_height_m(stored: float | None, diameter_m: float) -> float | None: @@ -211,10 +215,11 @@ def _side_spec( spec["basin_form"] = str(options.get("inlet_structure") or "") or None return spec - # 높이를 안 적었으면 **관경 기준 높이**(관경 + 0.5 · 139-1) · 옛 1.5 도 관경 > 1.0 이면 그 값. + # 높이를 안 적었으면 **관경 기준 높이**(관경 + 0.5 · 유입 + 0.7 · 139-1 · 211-1) · + # 옛 1.5 도 관경 > 1.0 이면 관경 + 0.5(저장 값 해석 · 안 바뀜). height = pipe_wall_height_m(_number(options.get(f"{side}_revet_height_m"), None), diameter_m) if height is None: - height = pipe_wall_min_height_m(diameter_m) + height = pipe_wall_min_height_m(diameter_m, side) length = _number( options.get(f"{side}_revet_length_m"), None, diff --git a/B06_Section/B06_Section_Router_CrossTable.py b/B06_Section/B06_Section_Router_CrossTable.py index e13d35579..74d30efed 100644 --- a/B06_Section/B06_Section_Router_CrossTable.py +++ b/B06_Section/B06_Section_Router_CrossTable.py @@ -50,7 +50,7 @@ def cross_quantity_sheet(source: dict[str, Any], design: dict[str, Any] | None) key: _format(value) if isinstance(value, (int, float)) else "-" for key, value in table.items() } - _values, texts, repick = edited_cells(design) + _values, texts, repick = edited_cells(design, source.get("samples")) text.update(texts) return { "quantity_table": table, diff --git a/B06_Section/B06_Section_Schema.py b/B06_Section/B06_Section_Schema.py index d0ee0e92c..fae03161c 100644 --- a/B06_Section/B06_Section_Schema.py +++ b/B06_Section/B06_Section_Schema.py @@ -135,14 +135,24 @@ class BoxAdjustPatch(BaseModel): right: BoxSideAdjustPatch = Field(default_factory=BoxSideAdjustPatch) +class CrossPickPiece(BaseModel): + """[상세] 고른 선 조각(209-1) — 어느 선 · 두 끝(m · offset, 표고).""" + + line: Literal["design", "ground", "spoil", "structure"] + start: list[float] = Field(..., min_length=2, max_length=2) + end: list[float] = Field(..., min_length=2, max_length=2) + + class CrossCellSource(BaseModel): - """[상세] 표 칸 출처(179-4) — area = 설계 면적 칸 · length = 두 끝(m · offset, 표고) · text.""" + """[상세] 표 칸 출처(179-4) — area = 설계 면적 칸 · length = 두 끝(m · offset, 표고) · text · + pieces(209-1) = 고른 선 조각 목록(length = 길이 합 · area = 닫힌 넓이).""" src: Literal["area", "length", "text"] key: str | None = Field(default=None, max_length=40) start: list[float] | None = Field(default=None, min_length=2, max_length=2) end: list[float] | None = Field(default=None, min_length=2, max_length=2) text: str | None = Field(default=None, max_length=200) + pieces: list[CrossPickPiece] | None = Field(default=None, min_length=1, max_length=200) class CrossDetailRow(BaseModel): diff --git a/B06_Section/B06_Section_UI_Cross_Culvert_Const.ts b/B06_Section/B06_Section_UI_Cross_Culvert_Const.ts index 673bfeaaf..a6ac1bf2b 100644 --- a/B06_Section/B06_Section_UI_Cross_Culvert_Const.ts +++ b/B06_Section/B06_Section_UI_Cross_Culvert_Const.ts @@ -71,6 +71,10 @@ export function pipeWallThicknessM(kind: string | null, diameterM: number): numb */ export const REVET_EMBED_DEPTH_M = 0.5; +/** 관 보호공 **유입** 흙막이 빈 칸 기본 순수 높이 = 관경(올림) + 0.7(211-1) — 유출은 근입 0.5 그대로. + * ⚠ 파이썬 짝 `INLET_REVET_ADD_M` · 세트 짝 `common_util_culvert_sets.INLET_REVET_ADD_M`(거울 시험). */ +export const INLET_REVET_ADD_M = 0.7; + /* 기슭막이 높이는 형태와 무관하게 **사용자 입력 그대로** — 형태별 높이 한계·원지반 맞춤 * 자동 자르기 없음. 형태가 바꾸는 것은 안 무늬뿐. 높이 기준은 **순수 높이**(벽 바닥~상단, * 근입 0.5m 포함). 단 하나 — 벽 윗면은 노면 위로 올라오지 않음(`buildRevetWallGeometry`). */ @@ -138,7 +142,7 @@ export function revetWallSpec( // 관경 기준 높이는 기본값만 — 하한은 그림이 서는 값뿐(54-51 · 사용자가 고름). const preferred = hiddenPipe ? (spec.revet_height_m ?? autoHeightM ?? REVET_EMBED_DEPTH_M) - : (spec.revet_height_m ?? pipeWallMinPureHeight(diameterM)); // 칸 값 → 그림(139-1) + : (spec.revet_height_m ?? pipeWallMinPureHeight(diameterM, spec.role)); // 칸 값 → 그림(139-1) const pureHeight = Math.max(adjust.h ?? preferred, WALL_MIN_PURE_HEIGHT_M); return { form, @@ -155,10 +159,12 @@ export const PIPE_CONNECT_GRADE = Math.tan((3 * Math.PI) / 180); /** * 배관 기슭막이 관 하부 여유(m) — 관 invert 아래 벽 바닥까지의 깊이 = 근입 0.5. * **순수 높이 기본 = 관경 + 0.5**(땅속 근입 0.5 포함 벽 전체 높이 · 벽 윗면 = 관 윗면 · - * 10-6 표 Ø1000 = 1.5 · 139-1). 칸을 비우면 이 값. + * 10-6 표 Ø1000 = 1.5 · 139-1 · 유입 흙막이 = 관경 + 0.7 · 211-1). 칸을 비우면 이 값. */ -export function pipeWallMinPureHeight(diameterM: number): number { - return revetTargetHeight(diameterM) + REVET_EMBED_DEPTH_M; +export function pipeWallMinPureHeight(diameterM: number, side = ""): number { + return ( + revetTargetHeight(diameterM) + (side === "inlet" ? INLET_REVET_ADD_M : REVET_EMBED_DEPTH_M) + ); } /** 벽 순수 높이 하한(m) — 0 이하는 그림이 안 섬. 관경 · 근입 하한 없음(54-51). */ export const WALL_MIN_PURE_HEIGHT_M = 0.1; diff --git a/B06_Section/B06_Section_UI_Cross_Detail.ts b/B06_Section/B06_Section_UI_Cross_Detail.ts index 4f52eab17..260405b9b 100644 --- a/B06_Section/B06_Section_UI_Cross_Detail.ts +++ b/B06_Section/B06_Section_UI_Cross_Detail.ts @@ -332,6 +332,7 @@ export function openCrossDetail(section: CrossSection): void { axes = drawn.axes; const handle = attachDetailZoom(clone, axes, zoom, (next) => (zoom = next)); cad.replaceChildren(clone, ...(handle ? [buildZoomControls(handle)] : [])); + tablePick.redraw(); // 선 조각 고르기(209-1) } showPicked(); }, @@ -367,11 +368,11 @@ export function openCrossDetail(section: CrossSection): void { }, stop: () => { resize.disconnect(); - detachTable(); + tablePick.detach(); }, }; // 표 손질(179-4) — 우클릭 · 그래프 고르기 · 더한 칸 글 → 세션 초안 → 표 다시 받음 - const detachTable = attachDetailTable({ + const tablePick = attachDetailTable({ tableBox, cad, section: () => state.section, diff --git a/B06_Section/B06_Section_UI_Cross_Detail_Geom.ts b/B06_Section/B06_Section_UI_Cross_Detail_Geom.ts new file mode 100644 index 000000000..f137535dc --- /dev/null +++ b/B06_Section/B06_Section_UI_Cross_Detail_Geom.ts @@ -0,0 +1,227 @@ +/* ============================================================================= + * B06_Section_UI_Cross_Detail_Geom.ts + * [상세] 그래프 고르기 기하(209-1) — 선을 만나는 점에서 조각으로 나눔 · 조각 길 · 길이 · 닫힌 넓이. + * + * 짝(① 파이썬 · TS) = `B07_DesignDetail/B07_DesignDetail_Engine_Cross_Table_Edit.py` + * (`piece_path` · `sub_path` · `path_length` · `ring_area` · `ground_runs` — [저장] 뒤 정본 셈) · + * 거울 시험 `resources/tester/test_209_1_detail_select.py`. + * 나눔(`splitAtCrossings`)은 화면 몫 — 서버는 저장된 조각 두 끝만 검산. + * ========================================================================== */ + +import type { CrossDesign, CrossPickPiece, SectionSample } from "./B06_Section_Api_Types"; + +export type Pt = [number, number]; +export type LineKind = CrossPickPiece["line"]; +/** 고를 수 있는 조각 — 어느 선 · 그 선 위 꺾은선(m). */ +export interface SplitPiece { + line: LineKind; + points: Pt[]; +} + +/** 서버 `LINE_TOLERANCE_M` 과 같은 값 — 두 끝이 선에서 이만큼 안이면 「선 위」 · 고리 끝 맞음. */ +export const LINE_TOLERANCE_M = 0.05; +/** 다른 선 끝이 이만큼 안이면 닿음으로 보고 자름(m) — 설계선 표고 0.1 mm 반올림. */ +const TOUCH_M = 0.01; +/** 이보다 짧은 조각은 버림(m) — 누를 수도 없음. */ +const MIN_PIECE_M = 0.02; + +const dist = (a: Pt, b: Pt): number => Math.hypot(a[0] - b[0], a[1] - b[1]); + +/* ── 서버 짝(검산 · 값) ─────────────────────────────────────────────────── */ + +/** 원지반선 — 무효 표고 샘플마다 끊은 꺾은선들(서버 `ground_runs` · 카드 `appendGroundProfile`). */ +export function groundRuns(samples: ReadonlyArray | undefined): Pt[][] { + const runs: Pt[][] = [[]]; + for (const sample of samples ?? []) { + const x = sample.offset_m; + const y = sample.elevation_m ?? sample.z; + if (sample.valid === false || typeof x !== "number" || typeof y !== "number") runs.push([]); + else runs[runs.length - 1].push([x, y]); + } + return runs.filter((run) => run.length > 1); +} + +const polyline = (raw: ReadonlyArray<{ offset_m: number; elevation_m: number }> | undefined) => + (raw ?? []).map((p): Pt => [p.offset_m, p.elevation_m]).filter((p) => p.every(Number.isFinite)); + +/** 서버가 아는 선(서버 `pick_lines`) — 고른 조각 위치 검산 대상. */ +export function pickLines( + design: CrossDesign | undefined, + samples: ReadonlyArray | undefined, +): Record { + return { + design: [polyline(design?.design_line)], + ground: groundRuns(samples), + spoil: [polyline(design?.spoil_fill_line)], + }; +} + +/** 선 위 자리(앞 끝에서 잰 길이 m) — 허용 안 가장 가까운 곳 · 없으면 null. */ +function locate(point: Pt, run: Pt[]): number | null { + let best: [number, number] | null = null; + let along = 0; + for (let i = 0; i + 1 < run.length; i++) { + const [ax, ay] = run[i]; + const [bx, by] = run[i + 1]; + const dx = bx - ax; + const dy = by - ay; + const size = Math.hypot(dx, dy); + const raw = size === 0 ? 0 : ((point[0] - ax) * dx + (point[1] - ay) * dy) / size ** 2; + const t = Math.max(0, Math.min(1, raw)); + const gap = Math.hypot(point[0] - (ax + t * dx), point[1] - (ay + t * dy)); + if (gap <= LINE_TOLERANCE_M && (best === null || gap < best[0])) best = [gap, along + t * size]; + along += size; + } + return best ? best[1] : null; +} + +function at(run: Pt[], s: number): Pt { + for (let i = 0; i + 1 < run.length; i++) { + const [ax, ay] = run[i]; + const [bx, by] = run[i + 1]; + const size = Math.hypot(bx - ax, by - ay); + if (s <= size) { + const t = size === 0 ? 0 : s / size; + return [ax + t * (bx - ax), ay + t * (by - ay)]; + } + s -= size; + } + return run[run.length - 1]; +} + +/** 선 위 두 자리 사이 꺾은선(s0 → s1 차례) — 사이 꼭짓점 포함(서버 `sub_path`). */ +export function subPath(run: Pt[], s0: number, s1: number): Pt[] { + const lo = Math.min(s0, s1); + const hi = Math.max(s0, s1); + const inner: Pt[] = []; + let along = 0; + for (let i = 0; i + 1 < run.length; i++) { + along += dist(run[i], run[i + 1]); + if (lo < along && along < hi) inner.push(run[i + 1]); + } + const path = [at(run, lo), ...inner, at(run, hi)]; + return s0 <= s1 ? path : path.reverse(); +} + +/** 고른 조각 → 그 선 위 꺾은선 · 두 끝이 선 밖이면 null(구조물 선 = 두 끝 직선 · 검산 없음). */ +export function piecePath(piece: CrossPickPiece, lines: Record): Pt[] | null { + if (piece.line === "structure") return [piece.start, piece.end]; + for (const run of lines[piece.line] ?? []) { + const s0 = locate(piece.start, run); + const s1 = locate(piece.end, run); + if (s0 !== null && s1 !== null) return subPath(run, s0, s1); + } + return null; +} + +export const pathLength = (path: Pt[]): number => + path.slice(1).reduce((sum, p, i) => sum + dist(path[i], p), 0); + +const near = (a: Pt, b: Pt): boolean => dist(a, b) <= LINE_TOLERANCE_M; + +/** 조각 길들을 끝끼리 이어 한 고리가 되면 그 넓이(㎡) · 안 닫힘 · 남는 조각 = null(서버 `ring_area`). */ +export function ringArea(paths: Pt[][]): number | null { + if (!paths.length) return null; + const ring = [...paths[0]]; + const rest = paths.slice(1).map((path) => [...path]); + while (rest.length) { + const tail = ring[ring.length - 1]; + const index = rest.findIndex((p) => near(p[0], tail) || near(p[p.length - 1], tail)); + if (index < 0) return null; + const [path] = rest.splice(index, 1); + ring.push(...(near(path[0], tail) ? path : path.reverse()).slice(1)); + } + if (ring.length < 4 || !near(ring[0], ring[ring.length - 1])) return null; + ring.push(ring[0]); // 끝이 허용 안에서만 맞음 — 닫는 변을 꼭 넣음 + let twice = 0; + for (let i = 0; i + 1 < ring.length; i++) + twice += ring[i][0] * ring[i + 1][1] - ring[i + 1][0] * ring[i][1]; + const area = Math.abs(twice) / 2; + return area > 1e-9 ? area : null; +} + +/** 고른 조각들 값(서버 `cell_value` 조각 갈래) — 길이 합 · 닫힌 넓이 · 못 셈 = null. */ +export function piecesValue( + kind: "length" | "area", + pieces: CrossPickPiece[], + lines: Record, +): number | null { + const paths = pieces.map((piece) => piecePath(piece, lines)); + if (!paths.length || paths.some((path) => path === null)) return null; + const valid = paths as Pt[][]; + return kind === "length" ? valid.reduce((sum, p) => sum + pathLength(p), 0) : ringArea(valid); +} + +/* ── 나눔(화면 몫) ───────────────────────────────────────────────────────── */ + +const cross = (a: Pt, b: Pt): number => a[0] * b[1] - a[1] * b[0]; +const sub = (a: Pt, b: Pt): Pt => [a[0] - b[0], a[1] - b[1]]; + +/** 점이 선분 a→b 위 어디(0~1)에 닿나 — `TOUCH_M` 밖이면 null. */ +function touchAt(point: Pt, a: Pt, b: Pt): number | null { + const d = sub(b, a); + const size2 = d[0] ** 2 + d[1] ** 2; + if (size2 === 0) return null; + const t = Math.max(0, Math.min(1, ((point[0] - a[0]) * d[0] + (point[1] - a[1]) * d[1]) / size2)); + return dist(point, [a[0] + t * d[0], a[1] + t * d[1]]) <= TOUCH_M ? t : null; +} + +/** + * 선들을 서로 만나는 점(교차 · 다른 선 끝이 닿는 점)에서 조각으로 나눔. + * 자르는 자리 = 꺾은선 위치(선분 번호 + 0~1). 같은 선끼리는 안 자름. + * ponytail: 겹쳐 나란한 선분(같은 직선 위)은 교점 없음으로 봄 — 끝 닿음만 자름. + */ +export function splitAtCrossings(lines: SplitPiece[]): SplitPiece[] { + const out: SplitPiece[] = []; + lines.forEach((line, li) => { + const cuts: number[] = []; + const pts = line.points; + for (let i = 0; i + 1 < pts.length; i++) { + const p = pts[i]; + const r = sub(pts[i + 1], p); + lines.forEach((other, oi) => { + if (oi === li) return; + const q = other.points; + for (let j = 0; j + 1 < q.length; j++) { + const s = sub(q[j + 1], q[j]); + const denom = cross(r, s); + if (Math.abs(denom) > 1e-12) { + const t = cross(sub(q[j], p), s) / denom; + const u = cross(sub(q[j], p), r) / denom; + if (t >= 0 && t <= 1 && u >= 0 && u <= 1) cuts.push(i + t); + } + } + for (const end of [q[0], q[q.length - 1]]) { + const t = touchAt(end, p, pts[i + 1]); + if (t !== null) cuts.push(i + t); + } + }); + } + const at = (c: number): Pt => { + const i = Math.min(Math.floor(c), pts.length - 2); + const t = c - i; + return [ + pts[i][0] + t * (pts[i + 1][0] - pts[i][0]), + pts[i][1] + t * (pts[i + 1][1] - pts[i][1]), + ]; + }; + const marks = [0, ...cuts.sort((a, b) => a - b), pts.length - 1]; + for (let k = 0; k + 1 < marks.length; k++) { + const [c0, c1] = [marks[k], marks[k + 1]]; + const inner = pts.slice(Math.floor(c0) + 1, Math.ceil(c1)); + const points = [at(c0), ...inner, at(c1)]; + if (pathLength(points) >= MIN_PIECE_M) out.push({ line: line.line, points }); + } + }); + return out; +} + +/** 조각 → 저장 꼴(두 끝 · 0.1 mm 반올림). */ +export function pieceSource(piece: SplitPiece): CrossPickPiece { + const round = (p: Pt): Pt => [Math.round(p[0] * 1e4) / 1e4, Math.round(p[1] * 1e4) / 1e4]; + return { + line: piece.line, + start: round(piece.points[0]), + end: round(piece.points[piece.points.length - 1]), + }; +} diff --git a/B06_Section/B06_Section_UI_Cross_Detail_Select.ts b/B06_Section/B06_Section_UI_Cross_Detail_Select.ts new file mode 100644 index 000000000..b3e8540ec --- /dev/null +++ b/B06_Section/B06_Section_UI_Cross_Detail_Select.ts @@ -0,0 +1,245 @@ +/* ============================================================================= + * B06_Section_UI_Cross_Detail_Select.ts + * [상세] 그림 선 고르기(209-1) — 설계선 · 구조물 선 · 원지반선 · 사토장선을 만나는 점에서 조각으로 + * 나눠(`_Cross_Detail_Geom.splitAtCrossings`) 조각마다 투명 판정 선 · 누름 = 하나 고름 · + * Shift/Ctrl+누름 = 더하기/빼기 · 고른 것 값 = [+ − ⤢] 왼쪽 두 줄(카드 179-1 · 195-1 꼴): + * 하나 = 길이 · 경사비율 / 수평 · 높이 · 여럿 = 길이 합 / 닫힌 넓이(안 닫히면 「닫히지 않음」). + * 칸에 넣기 = 표 우클릭 「그래프에서 고르기」 동안만(`_Cross_Detail_Table` 이 [칸에 넣기] · Enter 로 씀). + * ponytail: 그림을 다시 그리면(칸 크기 · 카드 다시 그림) 고름을 지움 — 조각 키 기억은 필요할 때. + * ========================================================================== */ + +import type { CrossDesign, CrossPickPiece } from "./B06_Section_Api_Types"; +import type { CrossAxesOptions } from "./B06_Section_UI_Cross_Axes"; +import { CROSS_PAD } from "./B06_Section_UI_Section_Common"; +import { + DESIGN_LINE_ATTR, + mergeStraightPieces, + pieceLabel, +} from "./B06_Section_UI_Cross_Design_Pick"; +import { + pathLength, + pieceSource, + ringArea, + splitAtCrossings, + type Pt, + type SplitPiece, +} from "./B06_Section_UI_Cross_Detail_Geom"; + +const SVG_NS = "http://www.w3.org/2000/svg"; +export const PIECE_HIT_CLASS = "b06-detail__piece"; + +/** 화면 px → m(카드 `x` · `toDisplayY` 의 역 · 축 옵션). */ +export function pxToM(axes: CrossAxesOptions): (p: number[]) => Pt { + return ([px, py]) => { + const display = axes.displayMax - (py - CROSS_PAD.top) / axes.pixelsPerMeter; + return [ + axes.maxOffset - (px - CROSS_PAD.left) / axes.pixelsPerMeter, + axes.elevationMid + (display - axes.elevationMid) / axes.exaggeration, + ]; + }; +} + +function mToPx(axes: CrossAxesOptions): (p: Pt) => string { + return ([offset, elevation]) => { + const display = axes.elevationMid + (elevation - axes.elevationMid) * axes.exaggeration; + const x = CROSS_PAD.left + (axes.maxOffset - offset) * axes.pixelsPerMeter; + const y = CROSS_PAD.top + (axes.displayMax - display) * axes.pixelsPerMeter; + return `${x},${y}`; + }; +} + +function pointsOf(el: Element): number[][] { + if (el.tagName.toLowerCase() === "line") { + const n = (name: string) => Number(el.getAttribute(name)); + return [ + [n("x1"), n("y1")], + [n("x2"), n("y2")], + ]; + } + return (el.getAttribute("points") ?? "") + .trim() + .split(/\s+/) + .map((pair) => pair.split(",").map(Number)) + .filter((p) => p.length === 2 && p.every(Number.isFinite)); +} + +/** 그림 도형 층 요소 → 고를 조각(m) — 설계 · 구조물 선은 같은 방향 토막을 직선 하나로 합친 뒤 나눔. */ +export function collectPieces(elements: Element[], axes: CrossAxesOptions): SplitPiece[] { + const toM = pxToM(axes); + const runs: Parameters[0] = []; + const others: SplitPiece[] = []; + for (const el of elements) { + const points = pointsOf(el).map(toM); + if (points.length < 2) continue; + if (el.classList.contains("b06-chart__design-cross")) + runs.push({ + points: points.map(([offset, elevation]) => ({ offset, elevation })), + structure: !el.hasAttribute(DESIGN_LINE_ATTR), + }); + else if (el.classList.contains("b06-chart__cross-profile")) + others.push({ line: "ground", points }); + else if (el.classList.contains("b06-chart__spoil-fill")) others.push({ line: "spoil", points }); + } + const straight = mergeStraightPieces(runs).map((piece): SplitPiece => ({ + line: piece.structure ? "structure" : "design", + points: [ + [piece.from.offset, piece.from.elevation], + [piece.to.offset, piece.to.elevation], + ], + })); + return splitAtCrossings([...straight, ...others]); +} + +/** 고름 바꿈 — 더하기(Shift/Ctrl) = 넣고 빼기 · 아니면 그 하나(다시 누르면 비움). */ +export function toggleSelection(selected: number[], index: number, additive: boolean): number[] { + if (additive) + return selected.includes(index) ? selected.filter((i) => i !== index) : [...selected, index]; + return selected.length === 1 && selected[0] === index ? [] : [index]; +} + +const LINE_NAME: Record = { + design: "설계선", + structure: "구조물 선", + ground: "원지반선", + spoil: "사토장선", +}; + +/** 고른 것 값 두 줄 — 하나 = 길이 · 경사비율 / 수평 · 높이(카드 꼴) · 여럿 = 길이 합 / 넓이. */ +export function selectionLabel(design: CrossDesign | undefined, pieces: SplitPiece[]): string { + if (!pieces.length) return ""; + if (pieces.length === 1) { + const [piece] = pieces; + const from = piece.points[0]; + const to = piece.points[piece.points.length - 1]; + if (design && piece.points.length === 2 && piece.line !== "ground" && piece.line !== "spoil") + return pieceLabel(design, { + from: { offset: from[0], elevation: from[1] }, + to: { offset: to[0], elevation: to[1] }, + structure: piece.line === "structure", + }); + return ( + `${LINE_NAME[piece.line]} 길이 ${pathLength(piece.points).toFixed(2)}m\n` + + `수평 ${Math.abs(to[0] - from[0]).toFixed(2)}m · 높이 ${Math.abs(to[1] - from[1]).toFixed(2)}m` + ); + } + const total = pieces.reduce((sum, piece) => sum + pathLength(piece.points), 0); + const area = ringArea(pieces.map((piece) => piece.points)); + return ( + `${pieces.length}개 · 길이 합 ${total.toFixed(2)}m\n` + + (area === null ? "면적 닫히지 않음" : `면적 ${area.toFixed(2)}㎡`) + ); +} + +/** 고른 조각 → 칸 출처(209-1 저장 꼴) — 면적은 닫혀야 · 길이는 하나 이상. */ +export function selectionSource( + kind: "area" | "length", + pieces: SplitPiece[], +): { src: "area" | "length"; pieces: CrossPickPiece[] } | null { + if (!pieces.length) return null; + if (kind === "area" && ringArea(pieces.map((piece) => piece.points)) === null) return null; + return { src: kind, pieces: pieces.map(pieceSource) }; +} + +/* ── 모달 배선 ─────────────────────────────────────────────────────────── */ + +export interface DetailSelect { + /** 그림을 새로 그린 뒤 — 조각 · 판정 선 · 값 칸 다시(고름 지움). */ + redraw: () => void; + /** 고르기 갈래(표 우클릭) — 있으면 [칸에 넣기] 단추 · 면적이면 누름 = 늘 더하기. */ + setMode: (kind: "area" | "length" | null) => void; + source: (kind: "area" | "length") => ReturnType; + clear: () => void; + detach: () => void; +} + +export function attachDetailSelect(input: { + cad: HTMLElement; + design: () => CrossDesign | undefined; + axes: () => CrossAxesOptions | null; + /** 조각 누름 뒤(더하기 여부) — 표가 길이 고르기 한 번 누름이면 바로 칸에 넣음. */ + picked: (additive: boolean) => void; + /** [칸에 넣기] 단추. */ + commit: () => void; +}): DetailSelect { + const { cad } = input; + let pieces: SplitPiece[] = []; + let hits: SVGPolylineElement[] = []; + let selected: number[] = []; + let mode: "area" | "length" | null = null; + + const label = document.createElement("span"); + label.className = "b06-cross-card__line-dims b06-detail__measure"; + const put = document.createElement("button"); + put.type = "button"; + put.className = "b06-cross-card__zoom-btn b06-detail__commit"; + put.textContent = "칸에 넣기"; + put.title = "고른 선을 칸에 넣음(Enter)"; + put.addEventListener("click", (event) => { + event.stopPropagation(); + input.commit(); + }); + + const show = (): void => { + const chosen = selected.map((i) => pieces[i]); + hits.forEach((hit, i) => hit.classList.toggle("is-selected", selected.includes(i))); + label.textContent = selectionLabel(input.design(), chosen); + label.hidden = !chosen.length; + put.hidden = !mode || !selectionSource(mode, chosen); + // [+ − ⤢] 왼쪽(카드 꼴) — 그림을 다시 그리면 막대가 새로 생김 + const bar = cad.querySelector(".b06-cross-card__zoom"); + if (bar && label.parentElement !== bar) bar.prepend(label, put); + }; + + const onClick = (event: MouseEvent): void => { + const hit = (event.target as Element).closest?.(`.${PIECE_HIT_CLASS}`); + const additive = event.shiftKey || event.ctrlKey || event.metaKey || mode === "area"; + if (!hit) { + if (!additive && !mode && selected.length) { + selected = []; + show(); + } + return; + } + event.stopPropagation(); + selected = toggleSelection(selected, hits.indexOf(hit as SVGPolylineElement), additive); + show(); + input.picked(additive); + }; + cad.addEventListener("click", onClick); + + return { + redraw() { + selected = []; + const axes = input.axes(); + const layer = cad.querySelector("g.b06-chart__plot-layer"); + pieces = axes && layer ? collectPieces([...layer.querySelectorAll("*")], axes) : []; + const toPx = axes ? mToPx(axes) : null; + hits = toPx + ? pieces.map((piece) => { + const hit = document.createElementNS(SVG_NS, "polyline"); + hit.setAttribute("points", piece.points.map(toPx).join(" ")); + hit.setAttribute("class", `${PIECE_HIT_CLASS} ${PIECE_HIT_CLASS}--${piece.line}`); + layer?.append(hit); + return hit; + }) + : []; + show(); + }, + setMode(kind) { + mode = kind; + show(); + }, + source: (kind) => + selectionSource( + kind, + selected.map((i) => pieces[i]), + ), + clear() { + selected = []; + show(); + }, + detach() { + cad.removeEventListener("click", onClick); + }, + }; +} diff --git a/B06_Section/B06_Section_UI_Cross_Detail_Table.ts b/B06_Section/B06_Section_UI_Cross_Detail_Table.ts index 4413240e1..24bf4203d 100644 --- a/B06_Section/B06_Section_UI_Cross_Detail_Table.ts +++ b/B06_Section/B06_Section_UI_Cross_Detail_Table.ts @@ -6,7 +6,9 @@ * 값은 서버(`B07_DesignDetail_Engine_Cross_Table_Edit`)가 그릴 때마다 다시 셈 — 모달 · B07 도면 표 한 벌. * 조작 직후 그 칸 글만 `localCellValue` 로 즉시 — 짝(① 파이썬 · TS) · 거울 시험 * `resources/tester/test_179_4_detail_table.py`. - * 고르기: 면적 = 면적 띠 · 사토장(띠 → 표 키) · 길이 = 보라 판정 선 두 끝(화면 px → m · 축 옵션). + * 고르기: 면적 = 면적 띠 · 사토장(띠 → 표 키) 또는 닫힌 선 조각들 · 길이 = 선 조각(들) — + * 조각 = 선이 만나는 점에서 나눈 것(209-1 · `_Cross_Detail_Select`) · 저장 = 조각 두 끝 목록. + * 길이는 한 번 누름 = 바로 칸에 · Shift/Ctrl+누름 = 여럿 → Enter · [칸에 넣기]. * ========================================================================== */ import { readState, writeState } from "../A00_Common/b_page_state"; @@ -17,8 +19,10 @@ import type { CrossDetailTable, CrossSection, } from "./B06_Section_Api_Fetch"; +import type { SectionSample } from "./B06_Section_Api_Types"; import type { CrossAxesOptions } from "./B06_Section_UI_Cross_Axes"; -import { CROSS_PAD } from "./B06_Section_UI_Section_Common"; +import { pickLines, piecesValue } from "./B06_Section_UI_Cross_Detail_Geom"; +import { attachDetailSelect, PIECE_HIT_CLASS } from "./B06_Section_UI_Cross_Detail_Select"; /** 서버 `MAX_ROWS` · `MAX_COLUMNS` · `LINE_TOLERANCE_M` 와 같은 값. */ export const MAX_ROWS = 12; @@ -162,7 +166,6 @@ const AREA_BANDS: ReadonlyArray<[string, string]> = [ ["b06-chart__spoil-fill", "spoil_fill"], ]; export const AREA_PICK_SELECTOR = ".b06-chart__area, .b06-chart__spoil-fill"; -export const LENGTH_PICK_SELECTOR = ".b06-chart__design-hit"; export function areaSourceOf(target: Element): CrossCellSource | null { const hit = target.closest(AREA_PICK_SELECTOR); @@ -170,27 +173,6 @@ export function areaSourceOf(target: Element): CrossCellSource | null { return band ? { src: "area", key: band[1] } : null; } -const round4 = (value: number): number => Math.round(value * 1e4) / 1e4; - -/** 판정 선 두 끝 → [offset, 표고](m) — 도형 층 좌표(카드 `x` · `toDisplayY` 의 역). */ -export function lengthSourceOf(target: Element, axes: CrossAxesOptions): CrossCellSource | null { - const hit = target.closest(LENGTH_PICK_SELECTOR); - const points = (hit?.getAttribute("points") ?? "") - .trim() - .split(/\s+/) - .map((pair) => pair.split(",").map(Number)); - if (points.length < 2 || points.some((p) => p.length !== 2 || !p.every(Number.isFinite))) - return null; - const toM = ([px, py]: number[]): [number, number] => { - const display = axes.displayMax - (py - CROSS_PAD.top) / axes.pixelsPerMeter; - return [ - round4(axes.maxOffset - (px - CROSS_PAD.left) / axes.pixelsPerMeter), - round4(axes.elevationMid + (display - axes.elevationMid) / axes.exaggeration), - ]; - }; - return { src: "length", start: toM(points[0]), end: toM(points[points.length - 1]) }; -} - /* ── 칸 값(짝 ① · 서버 `cell_value` 거울) ─────────────────────────────────── */ const AREA_DESIGN: Readonly> = { @@ -219,9 +201,15 @@ function onLine([px, py]: [number, number], line: ReadonlyArray<[number, number] return false; } -/** 조작 직후 칸 숫자(서버가 [저장] · 다시 받을 때 정본으로 다시 셈) — 글 · 못 셈 = null. */ -export function localCellValue(source: CrossCellSource, design: CrossDesign | undefined) { +/** 조작 직후 칸 숫자(서버가 [저장] · 다시 받을 때 정본으로 다시 셈) — 글 · 못 셈 = null. + * `samples` = 측점 원지반(조각 검산 · 209-1). */ +export function localCellValue( + source: CrossCellSource, + design: CrossDesign | undefined, + samples?: ReadonlyArray, +) { const record = (design ?? {}) as unknown as Record; + if ("pieces" in source) return piecesValue(source.src, source.pieces, pickLines(design, samples)); if (source.src === "area") return finite(record[AREA_DESIGN[source.key] ?? ""]); if (source.src !== "length") return null; const line = (design?.design_line ?? []) @@ -292,12 +280,16 @@ export interface DetailTableHost { let menu: ReturnType | null = null; const PICK_HINT = { - area: "면적 띠를 누름 · Esc 취소", - length: "보라 선을 누름 · Esc 취소", + area: "면적 띠를 누름 · 또는 닫힌 영역의 선들을 차례로 누름 → Enter · Esc 취소", + length: "선을 누름 · Shift/Ctrl+누름 = 여럿 → Enter · Esc 취소", } as const; -/** 표 우클릭 · 그래프 고르기 · 더한 칸 글 손질을 검. 돌려준 함수 = 떼기(모달 닫힐 때). */ -export function attachDetailTable(host: DetailTableHost): () => void { +/** 표 우클릭 · 그래프 고르기 · 더한 칸 글 손질을 검. detach = 떼기(모달 닫힐 때) · + * redraw = 그림을 새로 그린 뒤(선 조각 · 판정 선 다시 · 209-1). */ +export function attachDetailTable(host: DetailTableHost): { + detach: () => void; + redraw: () => void; +} { menu ??= createMapContextMenu("b06-detail"); const ctxMenu = menu; if (!ctxMenu.element.isConnected) { @@ -318,9 +310,30 @@ export function attachDetailTable(host: DetailTableHost): () => void { picking = null; delete cad.dataset.pick; delete cad.dataset.pickHint; + select.setMode(null); document.removeEventListener("keydown", onKey, true); }; + /** 고른 출처를 칸에 — 칸 글 즉시(짝 ①) · 세션 초안 → 서버 표 다시 받음. */ + const commit = (source: CrossCellSource | null): void => { + if (!picking || !source) return; + const { key } = picking; + stopPick(); + select.clear(); + const section = host.section(); + const shown = localCellValue(source, section.design, section.samples); + const td = tableBox.querySelector(`td[data-cell="${CSS.escape(key)}"]`); + if (td) td.textContent = shown === null ? "다시 고름" : shown.toFixed(2); + edit((table) => setCell(table, key, source)); + }; + const commitSelection = (): void => { + if (picking) commit(select.source(picking.kind)); + }; const onKey = (event: KeyboardEvent): void => { + if (event.key === "Enter") { + event.preventDefault(); + commitSelection(); + return; + } if (event.key !== "Escape") return; event.stopPropagation(); // 모달은 그대로 — 고르기만 취소 stopPick(); @@ -329,29 +342,30 @@ export function attachDetailTable(host: DetailTableHost): () => void { picking = { kind, key }; cad.dataset.pick = kind; cad.dataset.pickHint = PICK_HINT[kind]; + select.setMode(kind); document.addEventListener("keydown", onKey, true); }; + // 선 조각 고름(209-1) — 길이 한 번 누름(더하기 아님) = 바로 칸에 + const select = attachDetailSelect({ + cad, + design: () => host.section().design, + axes: host.axes, + picked: (additive) => { + if (picking?.kind === "length" && !additive) commitSelection(); + }, + commit: commitSelection, + }); + // 면적 띠 · 사토장 누름 = 그 띠 면적(179-4 그대로) — 선 조각 누름은 위가 맡음 const onPick = (event: MouseEvent): void => { - if (!picking) return; - const selector = picking.kind === "area" ? AREA_PICK_SELECTOR : LENGTH_PICK_SELECTOR; - // 겹친 요소(띠 위 판정 선 등) 아래까지 — 그 자리 맨 위 대상 + if (picking?.kind !== "area" || (event.target as Element).closest(`.${PIECE_HIT_CLASS}`)) + return; const hit = document .elementsFromPoint(event.clientX, event.clientY) - .find((el) => cad.contains(el) && el.closest(selector)); - const axes = host.axes(); - const source = !hit - ? null - : picking.kind === "area" - ? areaSourceOf(hit) - : axes && lengthSourceOf(hit, axes); + .find((el) => cad.contains(el) && el.closest(AREA_PICK_SELECTOR)); + const source = hit ? areaSourceOf(hit) : null; if (!source) return; event.stopPropagation(); - const { key } = picking; - stopPick(); - const shown = localCellValue(source, host.section().design); - const td = tableBox.querySelector(`td[data-cell="${CSS.escape(key)}"]`); - if (td) td.textContent = shown === null ? "다시 고름" : shown.toFixed(2); - edit((table) => setCell(table, key, source)); + commit(source); }; cad.addEventListener("click", onPick); @@ -401,12 +415,16 @@ export function attachDetailTable(host: DetailTableHost): () => void { tableBox.addEventListener("focusout", onBlur); tableBox.addEventListener("keydown", onEnter); - return () => { - stopPick(); - ctxMenu.close(); - cad.removeEventListener("click", onPick); - tableBox.removeEventListener("contextmenu", onMenu); - tableBox.removeEventListener("focusout", onBlur); - tableBox.removeEventListener("keydown", onEnter); + return { + detach: () => { + stopPick(); + ctxMenu.close(); + select.detach(); + cad.removeEventListener("click", onPick); + tableBox.removeEventListener("contextmenu", onMenu); + tableBox.removeEventListener("focusout", onBlur); + tableBox.removeEventListener("keydown", onEnter); + }, + redraw: () => select.redraw(), }; } diff --git a/B06_Section/B06_Section_UI_Page_Structures_Panel.ts b/B06_Section/B06_Section_UI_Page_Structures_Panel.ts index 0abc4bfc5..d3dbdd338 100644 --- a/B06_Section/B06_Section_UI_Page_Structures_Panel.ts +++ b/B06_Section/B06_Section_UI_Page_Structures_Panel.ts @@ -38,6 +38,7 @@ import { } from "../common_util/common_util_summary_item"; import { readStructurePick } from "../B05_Profile/B05_Profile_UI_Structure_Pick_Session"; import { + coversAtStation, coversChainage, NO_SELECTION, PIPE_MATCH_M, @@ -163,7 +164,7 @@ export function createB06StructuresPanel(deps: B06StructuresPanelDeps): B06Struc let markTypes: StructureType[] = []; /** 카드 누름이 덮어 여는 구조물 — 노면공(G군)은 뺌(152-5 · 목록 · 알약 고름은 id 길로 그대로). */ const coverable = (entry: StructureInstance): boolean => - markTypes.find((type) => type.type_id === entry.type_id)?.group !== "G"; + coversAtStation(markTypes.find((type) => type.type_id === entry.type_id)?.group); /** 다음 카드 고름이 열 구조물 — 같은 측점에 관이 있어도 누른 것이 먼저다(52-15). */ let preferredId: string | null = null; /** 그 구조물로 갈 카드 측점 — 구간형은 범위 안 카드 중 기준점에 가까운 것(경계 기준점이 범위 밖 카드로 안 감 · 165-2). */ diff --git a/B06_Section/B06_Section_UI_Style_Cross_Detail.css b/B06_Section/B06_Section_UI_Style_Cross_Detail.css index ab0354901..2f14f0637 100644 --- a/B06_Section/B06_Section_UI_Style_Cross_Detail.css +++ b/B06_Section/B06_Section_UI_Style_Cross_Detail.css @@ -164,11 +164,42 @@ /* 그래프에서 고르기 — 고를 대상만 손가락 · 왼쪽 아래(눈금 자리) 안내 글 */ .b06-detail__cad[data-pick="area"] .b06-chart__area > polygon, -.b06-detail__cad[data-pick="area"] .b06-chart__spoil-fill, -.b06-detail__cad[data-pick="length"] .b06-chart__design-hit { +.b06-detail__cad[data-pick="area"] .b06-chart__spoil-fill { cursor: pointer; } +/* 선 조각 판정 선(209-1) — 투명 굵은 선 · 배율 무관 굵기 · 고른 조각 = 붉은 띠 */ +.b06-detail__piece { + fill: none; + stroke: transparent; + stroke-width: 10; + stroke-linecap: round; + vector-effect: non-scaling-stroke; + pointer-events: stroke; + cursor: pointer; +} + +.b06-detail__piece:hover { + stroke: color-mix(in srgb, var(--color-accent) 25%, transparent); +} + +.b06-detail__piece.is-selected { + stroke: color-mix(in srgb, var(--color-danger) 55%, transparent); + stroke-width: 6; +} + +/* 고른 것 값(카드 179-1 꼴) · [칸에 넣기] — [+ − ⤢] 왼쪽 */ +.b06-detail__commit { + width: auto; + padding: 0 var(--spacing-4); + color: var(--color-accent); + white-space: nowrap; +} + +.b06-detail__commit[hidden] { + display: none; +} + .b06-detail__cad[data-pick]::after { content: attr(data-pick-hint); position: absolute; diff --git a/B07_DesignDetail/B07_DesignDetail_Engine_Cross_Table_Edit.py b/B07_DesignDetail/B07_DesignDetail_Engine_Cross_Table_Edit.py index bcdb964c2..d522ab3f9 100644 --- a/B07_DesignDetail/B07_DesignDetail_Engine_Cross_Table_Edit.py +++ b/B07_DesignDetail/B07_DesignDetail_Engine_Cross_Table_Edit.py @@ -6,11 +6,17 @@ area = 설계 면적 칸 그대로(`AREA_KEYS` · 띠 키 = 표 키) length = 두 끝(m · offset · 표고)이 설계선 위면 hypot · 아니면 비움 → 「다시 고름」 text = 글 그대로 — 더한 칸(`r:` 행 · `c:` 열)만 + 고른 조각(209-1 · `pieces` = [{line, start, end}]) — 교차점에서 나눈 선 조각 목록: + length = 조각 길이 합 · area = 조각이 닫힌 고리를 이루면 그 넓이(안 닫힘 → 「다시 고름」) + 조각 길 = 그 선(설계선 · 원지반선 · 사토장선) 위 두 끝 사이 꺾은선 + (두 끝이 선 밖 → 「다시 고름」) + · 구조물 선(`structure` · 브라우저 기하)은 위치 검산 없이 두 끝 직선. 행(`rows`) = 묶음 안(이 행 아래 · 묶음이면 하위 줄) 또는 끝에 항목 줄(좌 · 중 · 우 이름 + 값). 열(`columns`) = 오른쪽 끝 · 모든 행(비고 등). 짝(① 파이썬 · TS) = `B06_Section/B06_Section_UI_Cross_Detail_Table.ts` `localCellValue` -(조작 중 즉시 표시) · 거울 시험 `resources/tester/test_179_4_detail_table.py`. +(조작 중 즉시 표시) · 조각 길 · 넓이 = `B06_Section/B06_Section_UI_Cross_Detail_Geom.ts` · +거울 시험 `resources/tester/test_179_4_detail_table.py` · `test_209_1_detail_select.py`. """ from __future__ import annotations @@ -46,9 +52,9 @@ def _point(value: Any) -> tuple[float, float] | None: return (x, y) if x is not None and y is not None else None -def _design_line(design: dict[str, Any]) -> list[tuple[float, float]]: +def _polyline(raw: Any) -> list[tuple[float, float]]: points = [] - for point in design.get("design_line") or []: + for point in raw if isinstance(raw, list) else []: if isinstance(point, dict): x, y = _num(point.get("offset_m")), _num(point.get("elevation_m")) if x is not None and y is not None: @@ -56,6 +62,24 @@ def _design_line(design: dict[str, Any]) -> list[tuple[float, float]]: return points +def _design_line(design: dict[str, Any]) -> list[tuple[float, float]]: + return _polyline(design.get("design_line")) + + +def ground_runs(samples: Any) -> list[list[tuple[float, float]]]: + """원지반선 — 무효 표고 샘플마다 끊은 꺾은선들(카드 `appendGroundProfile` 과 같은 규칙).""" + runs: list[list[tuple[float, float]]] = [[]] + for sample in samples if isinstance(samples, list) else []: + sample = sample if isinstance(sample, dict) else {} + x = _num(sample.get("offset_m")) + y = _num(sample.get("elevation_m", sample.get("z"))) + if sample.get("valid") is False or x is None or y is None: + runs.append([]) + else: + runs[-1].append((x, y)) + return [run for run in runs if len(run) > 1] + + def _on_line(point: tuple[float, float], line: list[tuple[float, float]]) -> bool: """점이 설계선(꺾은선) 조각 하나에서 `LINE_TOLERANCE_M` 안인가.""" px, py = point @@ -68,12 +92,119 @@ def _on_line(point: tuple[float, float], line: list[tuple[float, float]]) -> boo return False +Point = tuple[float, float] + + +def _locate(point: Point, run: list[Point]) -> float | None: + """선 위 자리(앞 끝에서 잰 길이 m) — 허용 안 가장 가까운 곳 · 없으면 None.""" + best: tuple[float, float] | None = None + along = 0.0 + for (ax, ay), (bx, by) in zip(run, run[1:]): + dx, dy = bx - ax, by - ay + size = hypot(dx, dy) + t = 0.0 if size == 0 else ((point[0] - ax) * dx + (point[1] - ay) * dy) / size**2 + t = max(0.0, min(1.0, t)) + gap = hypot(point[0] - (ax + t * dx), point[1] - (ay + t * dy)) + if gap <= LINE_TOLERANCE_M and (best is None or gap < best[0]): + best = (gap, along + t * size) + along += size + return best[1] if best else None + + +def _at(run: list[Point], s: float) -> Point: + """선 위 자리 s(m) 의 점.""" + for (ax, ay), (bx, by) in zip(run, run[1:]): + size = hypot(bx - ax, by - ay) + if s <= size: + t = 0.0 if size == 0 else s / size + return (ax + t * (bx - ax), ay + t * (by - ay)) + s -= size + return run[-1] + + +def sub_path(run: list[Point], s0: float, s1: float) -> list[Point]: + """선 위 두 자리 사이 꺾은선(s0 → s1 차례) — 사이 꼭짓점 포함.""" + lo, hi = min(s0, s1), max(s0, s1) + inner: list[Point] = [] + along = 0.0 + for a, b in zip(run, run[1:]): + along += hypot(b[0] - a[0], b[1] - a[1]) + if lo < along < hi: + inner.append(b) + path = [_at(run, lo), *inner, _at(run, hi)] + return path if s0 <= s1 else path[::-1] + + +def piece_path(piece: Any, lines: dict[str, list[list[Point]]]) -> list[Point] | None: + """고른 조각 하나 → 그 선 위 꺾은선 · 두 끝이 선 밖이면 None(구조물 선 = 두 끝 직선).""" + if not isinstance(piece, dict): + return None + start, end = _point(piece.get("start")), _point(piece.get("end")) + if not start or not end: + return None + if piece.get("line") == "structure": + return [start, end] + for run in lines.get(str(piece.get("line")), []): + s0, s1 = _locate(start, run), _locate(end, run) + if s0 is not None and s1 is not None: + return sub_path(run, s0, s1) + return None + + +def path_length(path: list[Point]) -> float: + return sum(hypot(b[0] - a[0], b[1] - a[1]) for a, b in zip(path, path[1:])) + + +def _near(a: Point, b: Point) -> bool: + return hypot(a[0] - b[0], a[1] - b[1]) <= LINE_TOLERANCE_M + + +def ring_area(paths: list[list[Point]]) -> float | None: + """조각 길들을 끝끼리 이어 한 고리가 되면 그 넓이(㎡) · 안 닫힘 · 남는 조각 = None.""" + if not paths: + return None + ring = list(paths[0]) + rest = [list(path) for path in paths[1:]] + while rest: + index = next( + (i for i, p in enumerate(rest) if _near(p[0], ring[-1]) or _near(p[-1], ring[-1])), + None, + ) + if index is None: + return None + path = rest.pop(index) + ring += (path if _near(path[0], ring[-1]) else path[::-1])[1:] + if len(ring) < 4 or not _near(ring[0], ring[-1]): + return None + ring.append(ring[0]) # 끝이 허용 안에서만 맞음 — 닫는 변을 꼭 넣음 + area = abs(sum(a[0] * b[1] - b[0] * a[1] for a, b in zip(ring, ring[1:]))) / 2 + return area if area > 1e-9 else None + + +def pick_lines(design: dict[str, Any], samples: Any = None) -> dict[str, list[list[Point]]]: + """서버가 아는 선 — 고른 조각 위치 검산 대상(설계선 · 원지반선 · 사토장선).""" + return { + "design": [_design_line(design)], + "ground": ground_runs(samples), + "spoil": [_polyline(design.get("spoil_fill_line"))], + } + + def cell_value( - source: dict[str, Any], design: dict[str, Any] | None + source: dict[str, Any], design: dict[str, Any] | None, samples: Any = None ) -> tuple[float | None, str | None, bool]: - """출처 하나 → (숫자, 글, 다시 고름).""" + """출처 하나 → (숫자, 글, 다시 고름). `samples` = 측점 원지반 샘플(조각 검산).""" design = design if isinstance(design, dict) else {} kind = source.get("src") + pieces = source.get("pieces") + if kind in ("length", "area") and isinstance(pieces, list): + lines = pick_lines(design, samples) + paths = [piece_path(piece, lines) for piece in pieces] + valid = [path for path in paths if path is not None] + if not valid or len(valid) != len(paths): + return None, None, True + number = sum(map(path_length, valid)) if kind == "length" else ring_area(valid) + return number, None, number is None if kind == "area": return _num(design.get(_AREA_DESIGN.get(str(source.get("key")), ""))), None, False if kind == "length": @@ -89,9 +220,9 @@ def cell_value( def edited_cells( - design: dict[str, Any] | None, + design: dict[str, Any] | None, samples: Any = None ) -> tuple[dict[str, float | None], dict[str, str], list[str]]: - """patch 칸 출처 → (숫자 칸, 글 칸, 다시 고를 칸). 글은 더한 칸만.""" + """patch 칸 출처 → (숫자 칸, 글 칸, 다시 고를 칸). 글은 더한 칸만 · `samples` = 원지반.""" values: dict[str, float | None] = {} texts: dict[str, str] = {} repick: list[str] = [] @@ -99,7 +230,7 @@ def edited_cells( for key, source in (cells if isinstance(cells, dict) else {}).items(): if not isinstance(source, dict): continue - number, text, again = cell_value(source, design) + number, text, again = cell_value(source, design, samples) if text is not None: if key[:2] in ("r:", "c:"): texts[key] = text diff --git a/B07_DesignDetail/B07_DesignDetail_Router_Support.py b/B07_DesignDetail/B07_DesignDetail_Router_Support.py index c70185032..a351e69c7 100644 --- a/B07_DesignDetail/B07_DesignDetail_Router_Support.py +++ b/B07_DesignDetail/B07_DesignDetail_Router_Support.py @@ -315,7 +315,7 @@ def _quantity_table( for key in QUANTITY_VALUE_KEYS: table.setdefault(key, num(quantities.get(key))) # [상세] 표 손질(179-4) — 고른 칸 · 더한 칸을 서버가 다시 셈(모달 · B07 도면 한 벌) - table.update(edited_cells(design)[0]) + table.update(edited_cells(design, source.get("samples"))[0]) return table diff --git a/B07_DesignDetail/openwebcad/src/components/ViewControls.tsx b/B07_DesignDetail/openwebcad/src/components/ViewControls.tsx index 6b0b707ae..c5c16e0c2 100644 --- a/B07_DesignDetail/openwebcad/src/components/ViewControls.tsx +++ b/B07_DesignDetail/openwebcad/src/components/ViewControls.tsx @@ -1,13 +1,30 @@ -/** 화면 우하단 탐색 막대 (줌 표시·전체 보기) */ +/** 화면 우하단 탐색 막대 (줌 표시·전체 보기) — 제목줄이 없는 화면(M02)은 되돌리기 · 다시 하기도 */ import type { FC } from 'react'; import { runCommandInput } from '../commands/run-command'; -import { getScreenCanvasDrawController } from '../state'; +import { + getScreenCanvasDrawController, + isDrawingReadOnly, + isHostSave, + isViewOnly, +} from '../state'; export const ViewControls: FC = () => { const zoom = getScreenCanvasDrawController()?.getScreenScale() ?? 1; + // 제목줄(빠른 막대)이 없는 M02 양식 · 구조물 카드 — 고칠 수 있을 때만 + const showUndo = isHostSave() && !isViewOnly() && !isDrawingReadOnly(); return (
+ {showUndo && ( + <> + + + + )}