diff --git a/B05_Profile/B05_Profile_Api_Replan.ts b/B05_Profile/B05_Profile_Api_Replan.ts index fe5ca67a0..95a8a85ec 100644 --- a/B05_Profile/B05_Profile_Api_Replan.ts +++ b/B05_Profile/B05_Profile_Api_Replan.ts @@ -19,6 +19,7 @@ import { readState, writeState } from "../A00_Common/b_page_state"; import { heightAt } from "../common_util/common_util_surface_sampler"; import { loadDesignTerrainGrid } from "./B05_Profile_Api_TerrainGrid"; import type { RouteDraft } from "../A00_Common/design/logic/design_pipeline_types"; +import type { RouteNodeEdit } from "./logic/B05_Profile_UI_RouteEdit_Edits"; /** 편집 창 분석 지형 — las = 확정 지표면(라이다) · sheet = 수치지형도 서피스. */ export type AnalysisTerrain = "las" | "sheet"; @@ -121,6 +122,8 @@ export interface RoutePlanResponse { station_snap_step?: number | null; /** 현재 초기값 — 서버가 [확인] 때 프로젝트에 적어 둔 초기노선 갈래(계획서 20). */ current_initial?: { logic: string; weights: Record | null }; + /** 노드마다 넣은 편집값(430) — 넣은 R · 고정 · 고정 길이 · 켬끔 · 노드 수와 다르거나 옛 노선이면 null. */ + node_edits?: RouteNodeEdit[] | null; } export interface RouteReplanResponse { diff --git a/B05_Profile/B05_Profile_Route_NodeEdits.py b/B05_Profile/B05_Profile_Route_NodeEdits.py new file mode 100644 index 000000000..56f658e2a --- /dev/null +++ b/B05_Profile/B05_Profile_Route_NodeEdits.py @@ -0,0 +1,48 @@ +"""노드마다 넣은 편집값(430) — 곡선 켬끔 · 넣은 R · 고정(R | 길이) · 고정 길이 → 곡선표 `edits`. + +⚠ 짝: `logic/B05_Profile_UI_RouteEdit_Edits.ts` `flattenServerPlan`(`RouteNodeEdit`)이 읽음 · +거울 시험 `resources/tester/test_430_route_edit_rules.py`. + +곡선표 `curves` 는 **그린** R(접선 자리에 눌린 값)만 있어, 그것으로 다시 열면 눌린 R 이 +넣은 값으로 굳고 R · 길이 고정이 [저장] 뒤 사라짐 — 넣은 값을 따로 둠. 자리 = 저장 노드 +(앞 노드에서 0.5 m 안인 점은 `build_planned_polyline` 과 같이 거름). +""" + +from __future__ import annotations + +import math +from typing import Any + +from common_util.common_util_route_polyline import DUPLICATE_TOLERANCE_M + +_LOCKS = ("radius", "arc") + + +def node_edits( + points: list[tuple[float, float]], + flags: list[bool] | None, + radii: list[float | None] | None, + locks: list[str | None] | None = None, + arcs: list[float | None] | None = None, +) -> list[dict[str, Any]]: + """점마다의 편집값 — 겹친 점은 빼고 저장 노드와 같은 자리로. 칸이 짧으면 기본값(켬 · 자동).""" + + def at(values: list | None, index: int, default: Any = None) -> Any: + return values[index] if values is not None and index < len(values) else default + + kept: list[tuple[float, float]] = [] + edits: list[dict[str, Any]] = [] + for index, point in enumerate(points): + if kept and math.dist(kept[-1], point) <= DUPLICATE_TOLERANCE_M: + continue + kept.append(point) + lock = at(locks, index) + edits.append( + { + "curve": bool(at(flags, index, True)), + "radius_m": at(radii, index), + "lock": lock if lock in _LOCKS else None, + "arc_m": at(arcs, index), + } + ) + return edits diff --git a/B05_Profile/B05_Profile_Router_Replan.py b/B05_Profile/B05_Profile_Router_Replan.py index 45e184e66..5383aee86 100644 --- a/B05_Profile/B05_Profile_Router_Replan.py +++ b/B05_Profile/B05_Profile_Router_Replan.py @@ -42,6 +42,7 @@ from B03_FileInput.B03_FileInput_Repository import get_project_storage_relative_ from B05_Profile.B05_Profile_Engine_RouteInitial import read_initial_choice, write_initial_choice from B05_Profile.B05_Profile_Engine_RouteInitial_Station import snapped_initial from B05_Profile.B05_Profile_Engine_Sections import load_station_snap, load_station_snap_step +from B05_Profile.B05_Profile_Route_NodeEdits import node_edits from B05_Profile.B05_Profile_Route_Save import RouteSaveRequest from B05_Profile.B05_Profile_Schema import ( # noqa: F401 — 부르는 곳이 `replan.` 으로 씀 RouteInitialCriteria, @@ -211,8 +212,8 @@ def _curves_path(path: Path) -> Path: return path.with_name(f"{path.stem}_curves.json") -def _read_curves(path: Path) -> list[dict]: - """저장해 둔 곡선 성분. 없거나 못 읽으면 빈 목록(옛 프로젝트).""" +def _read_curves(path: Path, key: str = "curves") -> list[dict]: + """저장해 둔 곡선 성분(`key` = "edits" 면 넣은 편집값 · 430). 없거나 못 읽으면 빈 목록.""" target = _curves_path(path) if not target.is_file(): return [] @@ -221,7 +222,7 @@ def _read_curves(path: Path) -> list[dict]: except (OSError, json.JSONDecodeError): logger.warning("계획노선 곡선 성분을 읽지 못했습니다: %s", target) return [] - curves = data.get("curves") if isinstance(data, dict) else None + curves = data.get(key) if isinstance(data, dict) else None return curves if isinstance(curves, list) else [] @@ -235,11 +236,14 @@ def _write_planned_polyline( radii: list[float | None] | None = None, station_snap: bool | None = None, station_snap_step: float | None = None, + locks: list[str | None] | None = None, + arcs: list[float | None] | None = None, ) -> dict: """점 묶음을 폴리라인으로 바꿔 CSV 로 쓴다. 노드 요약을 돌려준다. `station_snap` — [확인] 때만 곡선표에 적음(요구 224-2). None 이면 칸을 안 둠(끔) · `station_snap_step` — 켬 + 간격이 있을 때만 곡선표에 적음(390-5 · 없으면 측점 No.). + `locks` · `arcs` — 편집값이 오면 넣은 값을 곡선표 `edits` 에(430 · `_Route_NodeEdits`). **노드도 함께 남긴다** — 노드는 폴리라인에서 되뽑을 수 없다. 폴리라인에는 원호 위 점이 섞여 있어 다시 단순화하면 꺾임점이 조금씩 지워지고, 그것을 반복하면 [확인]을 누를 @@ -262,6 +266,8 @@ def _write_planned_polyline( table["station_snap"] = bool(station_snap) if station_snap and station_snap_step is not None: table["station_snap_step"] = float(station_snap_step) + if curve_flags is not None or radii is not None: + table["edits"] = node_edits(points, curve_flags, radii, locks, arcs) _curves_path(path).write_text(json.dumps(table, ensure_ascii=False), encoding="utf-8") return { "nodes": len(result.nodes), @@ -507,6 +513,13 @@ async def read_route_plan(project_id: UUID) -> dict[str, Any] | JSONResponse: # 저장해 둔 노드면 이미 꺾임점이라 다시 뽑지 않는다. 없을 때(옛 프로젝트)만 뽑는다. simplify=not saved_nodes, ) + saved_edits = await asyncio.to_thread( + _read_curves, + planned_route_working_path(project_root) + if working + else planned_route_initial_path(project_root), + "edits", + ) return { "status": "success", "project_id": str(project_id), @@ -527,6 +540,10 @@ async def read_route_plan(project_id: UUID) -> dict[str, Any] | JSONResponse: "station_snap": await asyncio.to_thread(load_station_snap, project_root), "station_snap_step": await asyncio.to_thread(load_station_snap_step, project_root), "current_initial": await asyncio.to_thread(read_initial_choice, project_root), + # 넣은 R · 고정 · 고정 길이(430) — 저장 노드와 자리가 같을 때만(옛 곡선표 = null) + "node_edits": saved_edits + if saved_nodes and len(saved_edits) == len(outline.nodes) + else None, } @@ -561,6 +578,7 @@ async def replan_route(project_id: UUID, body: RouteSaveRequest) -> dict[str, An nodes = [(vertex.x, vertex.y) for vertex in request.vertices] curve_flags = [bool(vertex.curve) for vertex in request.vertices] radii = [vertex.radius_m for vertex in request.vertices] + draft = getattr(body, "draft", None) # R · 길이 고정(430) — 초안에만 있음 # 체인이 끊기면 되돌릴 수 있게 이전 수정본을 손에 쥔다 — 실패했는데 노선만 바뀌면 # 종횡단과 어긋난 채 굳고, 다시 누를수록 어긋남이 쌓인다(2026-09-06 실측). # 곡선표 · 노드도 함께 — 남기면 되돌린 노선에 새 곡선표(스냅 켬끔)가 붙음. @@ -576,6 +594,8 @@ async def replan_route(project_id: UUID, body: RouteSaveRequest) -> dict[str, An radii=radii, station_snap=request.station_snap, station_snap_step=request.station_snap_step, + locks=list(draft.curveLock) if draft else None, + arcs=list(draft.curveArc) if draft else None, ), working_path, nodes, diff --git a/B05_Profile/B05_Profile_UI_RouteEdit.ts b/B05_Profile/B05_Profile_UI_RouteEdit.ts index ca0abbb99..d22241478 100644 --- a/B05_Profile/B05_Profile_UI_RouteEdit.ts +++ b/B05_Profile/B05_Profile_UI_RouteEdit.ts @@ -39,11 +39,7 @@ import { type AnalysisTerrain, } from "./B05_Profile_Api_Replan"; import { bindRouteApply } from "./B05_Profile_UI_RouteEdit_Apply"; -import { - buildEditedPolyline, - type EditedCurve, - type EditedNode, -} from "./logic/B05_Profile_UI_RouteEdit_Curve"; +import type { EditedCurve, EditedNode } from "./logic/B05_Profile_UI_RouteEdit_Curve"; import { drawRouteEditScene, polylineLengthM, watchTheme } from "./B05_Profile_UI_RouteEdit_Render"; import { bindNodeSplice, bindRouteEditNavigation } from "./B05_Profile_UI_RouteEdit_Input"; import { bindRouteEditPointer } from "./B05_Profile_UI_RouteEdit_Pointer"; @@ -69,14 +65,7 @@ import { writeRouteLocks, } from "./B05_Profile_UI_RouteEdit_Lock"; import { createInitialPanel, type InitialPanelParams } from "./B05_Profile_UI_RouteEdit_Initial"; -import { - applyArcLocks, - applyCurveLimits, - curveSummary, - flattenServerPlan, - spliceNode, - type CurveLock, -} from "./logic/B05_Profile_UI_RouteEdit_Edits"; +import * as edits from "./logic/B05_Profile_UI_RouteEdit_Edits"; import { bindHistoryControls, createRouteEditHistory, @@ -148,7 +137,7 @@ export async function mountRouteEditor( let curveRadius: Array = []; /** 붙들어 둔 값 — 무엇을 고정할지와, 길이를 고정했을 때의 그 길이(m). * 노드를 옮기면 교각이 바뀌어 R 과 길이 중 하나는 반드시 따라 움직인다(`_Edits.ts`). */ - let curveLock: CurveLock[] = []; + let curveLock: edits.CurveLock[] = []; let curveArc: Array = []; /** 자리를 못 박은 노드(2026-09-12 사용자 지시 ① · 계획서 22-5) — 0번 = 시점, 끝 칸 = 종점 * (기본 고정), 사이 = 교각점. 켜진 자리는 안 끌리고 반지름·곡선 길이 칸으로만 바뀐다. @@ -162,6 +151,7 @@ export async function mountRouteEditor( const snap = bindStationSnap(chrome, projectId, stationIntervalM, (toggle) => { if (toggle) setStationSnap(!stationSnap); if (stationSnap && history) applyEdit(snap.text()); // 전체 · 한 걸음 + tellDraft(); // 끔 · 간격 바꿈도 계산 줄에 바로(430) draw(); }); const stations = () => snap.stations(plannedLine.length ? plannedLine : planned, curveInfo); @@ -362,12 +352,11 @@ export async function mountRouteEditor( * 지금은 서버와 **같은 규칙**(`buildEditedPolyline` 짝)으로 즉시 다시 만든다. [확인] 때 * 서버가 정본으로 다시 내는 것은 그대로다. */ function markEdited(): void { - // 길이를 붙든 자리는 교각이 바뀌었을 수 있다 — 그리기 전에 R 부터 다시 잡는다. - applyArcLocks(planned, curveLock, curveArc, curveRadius); - // 지정해 둔 값이 하한을 밑돌면 하한까지 끌어올린다(계획서 0-9 ④). - // 하한은 **R 과 L 을 함께 본 값**이다 — 내각 155° 이상은 R 만 본다(2026-09-12 확정). - applyCurveLimits(planned, curveOn, curveRadius, limitRadiusM, limitArcM); - const built = buildEditedPolyline(planned, curveOn, curveRadius, minRadiusM); + // 길이 고정 R → 지정값 하한(R·L · 내각 155° 이상은 R 만) 끌어올림 → 선(셈은 `_Edits` · 0-9 ④). + const built = edits.rebuildLine( + { planned, curveOn, curveRadius, curveLock, curveArc }, + fitLimits(), + ); plannedLine = built.vertices; curveInfo = built.curves; nodeInfo = built.nodes; @@ -389,7 +378,7 @@ export async function mountRouteEditor( /** 상태줄 꼬리 — 셈은 `_Edits` 몫. */ const curveHint = (): string => - curveSummary({ + edits.curveSummary({ nodeCount: planned.length, curveOn, curveRadius, @@ -400,6 +389,7 @@ export async function mountRouteEditor( minRadiusM, fresh: nodeInfo.length === 0, offStation: stationSnap ? fit.offStationCount(plannedLine, curveInfo, snap()) : 0, + flags: edits.routeFlags(planned, curveOn, curveInfo), // 겹친 노드 · 못 그린 곡선(430) }); // ── 곡선 라벨 — 고른 꺾임점 옆에 뜨는 조작 패널. 배선은 `_CurveBar` 몫 ── @@ -433,9 +423,14 @@ export async function mountRouteEditor( const syncCurveBar = curveBar.sync; /** 한 번의 편집을 마무리한다 — 다시 그리고, 라벨·상태줄을 맞추고, 되돌리기에 쌓는다. - * 측점 스냅 켬이면 고친 자리 앞 곡선부터 MC 를 일반측점에(366-3 · 되살림 `fitting=false` 은 안 맞춤). */ + * 측점 스냅 켬이면 고친 자리 앞 곡선부터 MC 를 일반측점에(366-3 · 되살림 `fitting=false` 은 안 맞춤). + * 하한 검사 한 곳(430) — 지난 걸음이 지키던 하한을 새로 깨면 그 걸음으로 되돌리고 까닭을 상태줄에. */ function applyEdit(message: string, record = true, fitting = true): void { - const from = fit.fitStart(history?.current?.(), snapshotNow()); + const before = history?.current?.(); + markEdited(); + const stop = fitting && before ? edits.floorStop(before, planned, nodeInfo, fitLimits()) : ""; + if (stop && before) return restoreSnapshot(before, stop, false); + const from = fit.fitStart(before, snapshotNow()); if (stationSnap && fitting) planned = fit.fitCurveStations(snapshotNow(), fitLimits(), from); markEdited(); writeRouteLocks(projectId, planned, apexLock); // 고정은 [취소] · 다시 열기에도 남는다(22-5). @@ -446,6 +441,13 @@ export async function mountRouteEditor( historyControls.sync(); } + /** 계산 묶음에 알림 — 노선 · 분석 지형 · 스냅이 저장분과 다르면 초안 · 같으면 null(352-3 · 430). */ + function tellDraft(): void { + if (!history) return; + const dirty = history.isDirty() || pickedTerrain() !== designTerrain || snap.changed(); + options.draft?.edited(dirty ? draftLink.draftOfSnapshot(snapshotNow(), snap.draft()) : null); + } + /** 측점 스냅 맞춤 값 — 하한 · 스냅 간격(390-2). */ function fitLimits(): fit.FitLimits { return { minRadiusM, limitRadiusM, limitArcM, intervalM: snap() }; @@ -526,10 +528,10 @@ export async function mountRouteEditor( routeHead, curveHint, contourHint, - commit: () => { - if (stationSnap) return applyEdit(snap.text()); // 놓을 때(366-3) - history?.commit(snapshotNow()); - historyControls.sync(); + commit: (index) => { + const before = history?.current?.()?.planned ?? []; // 놓을 때 맞춤(366-3) · 하한 · 보고(430) + applyEdit(stationSnap ? snap.text() : "옮겼습니다."); + if (stationSnap && index !== undefined) curveBar.noteFit(snap.text(), before, index); }, snapStepM: snap, fitDrag: (index) => { @@ -546,7 +548,7 @@ export async function mountRouteEditor( segmentAt: pointer.segmentAt, nodeAt: pointer.nodeAt, insert: (segment, px, py) => { - spliceNode(snapshotNow(), segment + 1, toMetric(px, py)); // 편집값도 같은 자리에 끼운다. + edits.spliceNode(snapshotNow(), segment + 1, toMetric(px, py)); // 편집값도 같은 자리에 끼운다. picked = segment + 1; applyEdit("새 노드를 넣었습니다(직선 추가)."); }, @@ -554,7 +556,7 @@ export async function mountRouteEditor( if (planned.length <= 2) return showToast("노선은 노드가 2개 이상이어야 합니다.", "error"); if (apexLock[index]) return showToast("고정한 점은 못 지웁니다 — 고정을 먼저 푸세요.", "error"); - spliceNode(snapshotNow(), index); + edits.spliceNode(snapshotNow(), index); picked = -1; applyEdit("노드를 지웠습니다(직선 삭제)."); }, @@ -578,7 +580,7 @@ export async function mountRouteEditor( overlay, busy, projectId, - nodes: () => ({ planned, curveOn, curveRadius }), + nodes: () => ({ planned, curveOn, curveRadius, curveLock, curveArc }), // 분석 지형만 바꿔도 [확인]이 설계 지형을 바꿔 다시 셈한다(PLAN 133-2). changed: () => (history?.isDirty() ?? false) || pickedTerrain() !== designTerrain || snap.changed(), @@ -612,7 +614,7 @@ export async function mountRouteEditor( limitArcM = plan.limit_curve_length_m ?? 0; setStationSnap(snap.load(plan)); // 곡선 성분을 편집할 수 있는 꼴로 편다 — 셈은 `_Edits` 몫(까닭도 그쪽에 적었다). - const flat = flattenServerPlan(nodes, plan.curves ?? []); + const flat = edits.flattenServerPlan(nodes, plan.curves ?? [], plan.node_edits); ({ planned, curveOn, curveRadius, curveLock, curveArc } = flat); apexLock = lockColumn(planned, readRouteLocks(projectId)); // 닫기 전 고정을 좌표로 되살린다. ({ nodes: nodeInfo, curves: curveInfo } = flat); @@ -668,9 +670,7 @@ export async function mountRouteEditor( let terrainTicket = 0; terrainSelect.addEventListener("change", () => { setAnalysisTerrain(projectId, terrainSelect.value === "sheet" ? "sheet" : "las"); - // 계산 묶음에 알림 — 노선이 그대로여도 지형이 설계와 다르면 초안으로 다시 셈(352-3). - const dirty = history?.isDirty() || pickedTerrain() !== designTerrain; - options.draft?.edited(dirty ? draftLink.draftOfSnapshot(snapshotNow(), snap.draft()) : null); + tellDraft(); // 노선이 그대로여도 지형이 설계와 다르면 초안으로 다시 셈(352-3). const mine = ++terrainTicket; void loadBackground().then((background) => { if (closed || mine !== terrainTicket) return; diff --git a/B05_Profile/B05_Profile_UI_RouteEdit_Apply.ts b/B05_Profile/B05_Profile_UI_RouteEdit_Apply.ts index c006134a3..0a78128db 100644 --- a/B05_Profile/B05_Profile_UI_RouteEdit_Apply.ts +++ b/B05_Profile/B05_Profile_UI_RouteEdit_Apply.ts @@ -39,7 +39,10 @@ import type { SnapSetting } from "./B05_Profile_UI_RouteEdit_SnapStep"; type Vertex = [number, number]; type RouteSettings = SnapSetting & { terrain: string | null }; -type RouteNodes = { planned: Vertex[]; curveOn: boolean[]; curveRadius: Array }; +type RouteNodes = { planned: Vertex[]; curveOn: boolean[]; curveRadius: Array } & { + curveLock?: RouteDraft["curveLock"]; + curveArc?: Array; +}; export interface RouteApplyParams { /** 옛 [노선 반영] 자리(단추 · 대기 막) — 346-3 부터 안 씀(대기는 페이지 잠금 막 하나). */ @@ -72,15 +75,15 @@ interface RouteSource { const sources = new Map(); -/** 노드 · 곡선 편집값 → 계약 `RouteDraft`(붙든 값은 서버가 안 씀 · 칸 길이만 맞춤). */ +/** 노드 · 곡선 편집값 → 계약 `RouteDraft`(R · 길이 고정도 실음 — 서버가 곡선표 `edits` 에 둠 · 430). */ export function routeDraftOf(nodes: RouteNodes, settings: RouteSettings): RouteDraft { return { rev: 0, nodes: nodes.planned.map(([x, y]): Vertex => [x, y]), curveOn: nodes.planned.map((_, index) => nodes.curveOn[index] !== false), curveRadius: nodes.planned.map((_, index) => nodes.curveRadius[index] ?? null), - curveLock: nodes.planned.map(() => null), - curveArc: nodes.planned.map(() => null), + curveLock: nodes.planned.map((_, index) => nodes.curveLock?.[index] ?? null), + curveArc: nodes.planned.map((_, index) => nodes.curveArc?.[index] ?? null), stationSnap: settings.stationSnap, stationSnapStep: settings.stationSnapStep ?? null, terrain: settings.terrain, diff --git a/B05_Profile/B05_Profile_UI_RouteEdit_CurveBar.ts b/B05_Profile/B05_Profile_UI_RouteEdit_CurveBar.ts index 6cace6057..42ab19b74 100644 --- a/B05_Profile/B05_Profile_UI_RouteEdit_CurveBar.ts +++ b/B05_Profile/B05_Profile_UI_RouteEdit_CurveBar.ts @@ -10,8 +10,10 @@ * 들고 간다. 두 벌로 두면 교각이 바뀔 때 서로 어긋난다(`_Edits.ts` 설명 참고). * ========================================================================== */ +import { showToast } from "@ui/ui_template_elements"; import type { EditedCurve, EditedNode, Vertex } from "./logic/B05_Profile_UI_RouteEdit_Curve"; import { + CURVE_OPTIONAL_INNER_ANGLE_DEG, curveOptionalAt, deflectionRad, radiusFloorM, @@ -63,6 +65,8 @@ export interface CurveBar { label: CurveLabel; /** 고른 자리에 맞춰 패널을 옮겨 그린다. */ sync: () => void; + /** 끌기 · 손잡이 놓을 때 맞춤 결과를 상태줄 `message` 뒤에(430 · 스냅 끔이면 그대로). */ + noteFit: (message: string, before: Vertex[], picked: number) => void; } export function createCurveBar(params: CurveBarParams): CurveBar { @@ -120,10 +124,17 @@ export function createCurveBar(params: CurveBarParams): CurveBar { params.applyEdit(locked ? `${name}을 고정했습니다.` : `${name} 고정을 풀었습니다.`); }, onCurveOn: (on) => { - const { picked, curveOn } = params.state(); + const { picked, curveOn, nodeInfo } = params.state(); if (picked < 0) return; curveOn[picked] = on; - params.applyEdit(on ? "곡선을 넣었습니다." : "곡선을 지웠습니다."); + // 내각 155° 미만 = 곡선을 둬야 하는 자리(별표2 Ⅰ.2.다.(1)) — 막지 않고 경고(430). + const inner = nodeInfo[picked]?.inner_angle_deg ?? null; + const warn = + !on && inner !== null && !curveOptionalAt(inner) + ? ` — 내각 ${inner.toFixed(1)}° < ${CURVE_OPTIONAL_INNER_ANGLE_DEG}° 곡선 자리(경고)` + : ""; + params.applyEdit(on ? "곡선을 넣었습니다." : `곡선을 지웠습니다${warn}.`); + if (warn) showToast(`곡선을 지웠습니다${warn}.`, "warning", 5000); }, }, params.container, @@ -133,7 +144,7 @@ export function createCurveBar(params: CurveBarParams): CurveBar { * 앞뒤 직선 짧은 쪽 절반까지(`buildEditedPolyline` · 서버 짝 같은 규칙)라 큰 R 은 조용히 눌렸다. * 스냅 켬이면 맞춤이 민 교점 · 못 맞춘 곡선을 덧붙임(408-1 · `before` = 입력 전 교점). */ function noteResult(message: string, name: "반지름" | "곡선 길이", before: Vertex[]): void { - const { picked, curveRadius, curveInfo, nodeInfo, planned, line, snap } = params.state(); + const { picked, curveRadius, curveInfo, nodeInfo } = params.state(); const status = params.container.querySelector(".b05-routeedit__status"); if (!status) return; const asked = curveRadius[picked]; @@ -144,17 +155,29 @@ export function createCurveBar(params: CurveBarParams): CurveBar { asked === null || asked === undefined || !drawn || drawn.radius_m >= asked - 0.05 ? message.replace(/\.$/, "") : `${name} ${m(asked * per)} → ${m(drawn.radius_m * per)}(앞뒤 직선이 짧아 접선 자리 모자람)`; - const tail = snap - ? fitNote( - before, - planned, - picked, - offStationMcs(line, curveInfo, snap.stepM), - snap.stationM, - snap.stepM, - ) - : ""; - status.textContent = (status.textContent ?? "").replace(message, `${head}${tail}.`); + status.textContent = (status.textContent ?? "").replace( + message, + `${head}${fitTail(before, picked, false)}.`, + ); + } + + /** 맞춤이 민 교점 · 못 맞춘 곡선 꼬리 — 스냅 끔이면 ""(`hand` = 고른 IP 를 손이 옮김). */ + function fitTail(before: Vertex[], picked: number, hand: boolean): string { + const { curveInfo, planned, line, snap } = params.state(); + if (!snap) return ""; + const off = offStationMcs(line, curveInfo, snap.stepM); + return fitNote(before, planned, picked, off, snap.stationM, snap.stepM, hand); + } + + /** 끌기 · 손잡이 놓을 때(430) — 상태줄 `message` 뒤에 맞춤 결과(`before` = 누르기 전 교점). */ + function noteFit(message: string, before: Vertex[], picked: number): void { + const status = params.container.querySelector(".b05-routeedit__status"); + const tail = fitTail(before, picked, true); + if (status && tail) + status.textContent = (status.textContent ?? "").replace( + message, + `${message.replace(/\.$/, "")}${tail}.`, + ); } /** 고른 자리에 맞춰 라벨을 옮겨 그린다. 끝점은 곡선이 없어 **고정 단추만** 낸다(계획서 22-5). */ @@ -238,5 +261,5 @@ export function createCurveBar(params: CurveBarParams): CurveBar { }); } - return { label, sync }; + return { label, sync, noteFit }; } diff --git a/B05_Profile/B05_Profile_UI_RouteEdit_Pointer.ts b/B05_Profile/B05_Profile_UI_RouteEdit_Pointer.ts index 358f29407..45f975742 100644 --- a/B05_Profile/B05_Profile_UI_RouteEdit_Pointer.ts +++ b/B05_Profile/B05_Profile_UI_RouteEdit_Pointer.ts @@ -34,6 +34,7 @@ import { import { markShown } from "./B05_Profile_UI_RouteEdit_Marks"; import { curveShortfalls, + floorNote, radiusFloorM, shortfallCrossed, type CurveLock, @@ -98,8 +99,8 @@ export interface RouteEditPointerParams { routeHead: () => string; curveHint: () => string; contourHint: () => string; - /** 끌기 한 번을 되돌리기에 쌓는다. */ - commit: () => void; + /** 끌기 한 번을 되돌리기에 쌓는다 — `index` = 끈 교각점(430 · 놓을 때 맞춤 보고 · 방향키는 안 줌). */ + commit: (index?: number) => void; /** 스냅 간격(m · 390-5) — 스냅 켬이면 방향키 한 걸음. */ snapStepM: () => number; /** 끄는 중 · 방향키 걸음 미리보기(390-5) — 스냅 켬이면 IP `index` 자리 그대로 MC 를 간격 배수에 · @@ -308,6 +309,9 @@ export function bindRouteEditPointer(params: RouteEditPointerParams): RouteEditP const node = dragHandle.node; const moved = dragHandleTo(node, dragHandle.end, toMetric(px, py)); if (moved) { + // 교각점이 움직여 이웃 곡선 접선 자리도 바뀜 — 지키던 하한을 새로 깨면 그 걸음만 되돌림(430). + const before = curveShortfalls(state.nodeInfo, state.limitRadiusM, state.limitArcM); + const kept = [state.planned[node], state.curveRadius[node], state.curveOn[node]] as const; state.planned[node] = moved.apex; // 손으로 끌어도 하한 아래로는 안 내려간다 — 거기서 멈춘다(계획서 0-9 ④). // 하한은 그 자리의 교각까지 본 값이라 L 하한도 함께 지켜진다. @@ -319,8 +323,21 @@ export function bindRouteEditPointer(params: RouteEditPointerParams): RouteEditP params.setPicked(node); // 손잡이 자리는 다시 셈한 곡선에서 나온다 — 접선 자리가 모자라 R 이 눌리면 손이 // 끄는 자리보다 덜 따라오고, 그 눌림이 그 자리에서 눈에 보인다. - dragMoved = true; params.markEdited(); + const after = params.state(); + if ( + shortfallCrossed( + before, + curveShortfalls(after.nodeInfo, after.limitRadiusM, after.limitArcM), + ) + ) { + [state.planned[node], state.curveRadius[node], state.curveOn[node]] = kept; + params.markEdited(); + status.textContent = `${params.routeHead()} — 하한에 걸려 더 못 옮깁니다${floorNote(state.limitRadiusM, state.limitArcM)}.`; + params.draw(); + return; + } + dragMoved = true; params.syncCurveBar(); status.textContent = `${params.routeHead()} — 곡선을 잡는 중. ${params.curveHint()}`; params.draw(); @@ -350,9 +367,7 @@ export function bindRouteEditPointer(params: RouteEditPointerParams): RouteEditP state.planned[dragNode] = previous; params.markEdited(); fitPreview(state.planned); - status.textContent = - `${params.routeHead()} — 하한에 걸려 더 못 옮깁니다` + - `(곡선반지름 ${state.limitRadiusM}m${state.limitArcM > 0 ? ` · 곡선 길이 ${state.limitArcM}m` : ""}).`; + status.textContent = `${params.routeHead()} — 하한에 걸려 더 못 옮깁니다${floorNote(state.limitRadiusM, state.limitArcM)}.`; params.draw(); return; } @@ -395,7 +410,7 @@ export function bindRouteEditPointer(params: RouteEditPointerParams): RouteEditP // 끌기 **한 번**이 되돌리기 한 걸음이다 — 프레임마다 쌓으면 한 번 물리는 데 수십 번 // 눌러야 한다. 놓는 순간에만 쌓는다. if (dragMoved) { - params.commit(); + params.commit(dragHandle?.node ?? dragNode); // 노선이 바뀌었다 — 보던 측점 횡단을 다시 셈해 **전후로** 늘어놓는다(계획서 0-9 ⑲). // 끄는 동안에는 한 번도 안 부른다(한 장에 0.7초). void params.crossPreview.refresh(); diff --git a/B05_Profile/logic/B05_Profile_RouteEdit_KeyNudge.ts b/B05_Profile/logic/B05_Profile_RouteEdit_KeyNudge.ts index 37756e05f..7454daeb4 100644 --- a/B05_Profile/logic/B05_Profile_RouteEdit_KeyNudge.ts +++ b/B05_Profile/logic/B05_Profile_RouteEdit_KeyNudge.ts @@ -98,7 +98,8 @@ export function nudgeMessage(report: NudgeReport, snapping: boolean): string { } /** 반지름 · 곡선 길이 입력 뒤 맞춤 결과 꼬리(408-1) — 손으로 옮긴 교점이 없으니 고른 IP 도 「밀림」에 셈 · - * 못 맞춘 곡선 = 측점 밖 MC(`offStationMcs`)를 측점 표기로(셋까지 · 나머지 「외 N」). */ + * 못 맞춘 곡선 = 측점 밖 MC(`offStationMcs`)를 측점 표기로(셋까지 · 나머지 「외 N」). + * `handMoved` = 끌기 · 손잡이로 고른 IP 를 손이 옮김(430 · 놓을 때) — 고른 IP 는 「밀림」에 안 셈. */ export function fitNote( before: ReadonlyArray, after: ReadonlyArray, @@ -106,10 +107,11 @@ export function fitNote( offMcs: ReadonlyArray, stationM: number, stepM: number, + handMoved = false, ): string { const start = before[picked] ?? [0, 0]; const report = nudgeReport(before, after, picked, start, start); - const pushed = report.pushed + (report.movedM > SAME_M ? 1 : 0); + const pushed = report.pushed + (!handMoved && report.movedM > SAME_M ? 1 : 0); const names = offMcs.map((mc) => `No.${stationLabel(mc, stationM, stepM < 1 ? 1 : 0)}`); const more = names.length > 3 ? ` 외 ${names.length - 3}` : ""; const off = names.length ? ` · 못 맞춘 곡선 ${names.slice(0, 3).join(", ")}${more}` : ""; diff --git a/B05_Profile/logic/B05_Profile_RouteEdit_StationFit.ts b/B05_Profile/logic/B05_Profile_RouteEdit_StationFit.ts index aee19d122..8a9fbd34c 100644 --- a/B05_Profile/logic/B05_Profile_RouteEdit_StationFit.ts +++ b/B05_Profile/logic/B05_Profile_RouteEdit_StationFit.ts @@ -14,16 +14,10 @@ * 순수 계산 — 화면 · fetch · sessionStorage 없음. 부르는 쪽은 `B05_Profile_UI_RouteEdit`. * ========================================================================== */ +import type { EditedCurve, EditedPolyline, Vertex } from "./B05_Profile_UI_RouteEdit_Curve"; import { - buildEditedPolyline, - type EditedCurve, - type EditedPolyline, - type Vertex, -} from "./B05_Profile_UI_RouteEdit_Curve"; -import { - applyArcLocks, - applyCurveLimits, curveShortfalls, + rebuildLine, shortfallCrossed, type NodeColumns, } from "./B05_Profile_UI_RouteEdit_Edits"; @@ -47,10 +41,7 @@ type Columns = Pick value > 1e-6 && before[index] <= 1e-6); } +/** 선을 짜는 값 — 기본 반지름 · 못 넘는 하한(R · L). */ +export interface CurveLimits { + minRadiusM: number; + limitRadiusM: number; + limitArcM: number; +} + +/** 편집 창 `markEdited` 의 셈 — 길이를 붙든 자리 R 다시 잡기 → 지정값 하한까지 끌어올림(`curveRadius` + * 를 고침) → 선. 교각이 바뀌었을 수 있어 R 부터 잡고 그린다. */ +export function rebuildLine( + cols: Omit, + limits: CurveLimits, +): EditedPolyline { + applyArcLocks(cols.planned, cols.curveLock, cols.curveArc, cols.curveRadius); + applyCurveLimits( + cols.planned, + cols.curveOn, + cols.curveRadius, + limits.limitRadiusM, + limits.limitArcM, + ); + return buildEditedPolyline(cols.planned, cols.curveOn, cols.curveRadius, limits.minRadiusM); +} + +/** 하한 글 꼬리 — 「(곡선반지름 12m · 곡선 길이 20m)」. */ +export function floorNote(limitRadiusM: number, limitArcM: number): string { + return `(곡선반지름 ${limitRadiusM}m${limitArcM > 0 ? ` · 곡선 길이 ${limitArcM}m` : ""})`; +} + +/** 자리 번호 셋까지 「IP3 · IP5 외 2」. */ +const ipList = (seats: ReadonlyArray): string => + seats + .slice(0, 3) + .map((seat) => `IP${seat}`) + .join(" · ") + (seats.length > 3 ? ` 외 ${seats.length - 3}` : ""); + +/** + * 이번 편집이 하한을 **새로** 깼으면 까닭 한 줄 · 아니면 ""(430 · 모든 평면 조작이 `applyEdit` 한 곳에서). + * `before` = 지난 걸음 사진 · `nodes` = 지금 노드 요약(스냅 맞춤 전 — 맞춤은 스스로 하한을 지킴). + * 노드를 하나 끼우거나 뺐으면 처음 달라진 자리에서 줄을 맞춰 견줌(새 노드 = 지키던 자리) · 둘 넘게 다르면 안 견줌. + */ +export function floorStop( + before: NodeColumns, + planned: ReadonlyArray, + nodes: ReadonlyArray, + limits: CurveLimits, +): string { + const gap = planned.length - before.planned.length; + if (Math.abs(gap) > 1) return ""; + const built = rebuildLine({ ...before, curveRadius: [...before.curveRadius] }, limits); + const was = curveShortfalls(built.nodes, limits.limitRadiusM, limits.limitArcM); + const now = curveShortfalls(nodes, limits.limitRadiusM, limits.limitArcM); + const differ = planned.findIndex( + (vertex, i) => vertex[0] !== before.planned[i]?.[0] || vertex[1] !== before.planned[i]?.[1], + ); + const at = differ < 0 ? planned.length : differ; + const old = (i: number): number => + (gap === 0 || i < at ? was[i] : gap > 0 ? (i === at ? 0 : was[i - 1]) : was[i + 1]) ?? 0; + const seats = now.flatMap((value, i) => (value > 1e-6 && old(i) <= 1e-6 ? [i] : [])); + if (!seats.length) return ""; + return `하한에 걸려 되돌렸습니다 — ${ipList(seats)}${floorNote(limits.limitRadiusM, limits.limitArcM)}.`; +} + +/** 상태줄 표시(430) — 겹친 노드(앞 노드에서 0.5 m 안 · 선을 짤 때 버림 · 짝 `DUPLICATE_TOLERANCE_M`) · + * 못 그린 곡선(켬인데 곡선이 없음 · 곧은 자리 · 겹친 노드는 뺌). */ +export function routeFlags( + planned: ReadonlyArray, + curveOn: ReadonlyArray, + curves: ReadonlyArray, +): { overlap: number[]; undrawn: number[] } { + const overlap: number[] = []; + let last: Vertex | null = null; + planned.forEach((vertex, i) => { + if (last && Math.hypot(vertex[0] - last[0], vertex[1] - last[1]) <= DUPLICATE_TOLERANCE_M) + overlap.push(i); + else last = vertex; + }); + const drawn = new Set(curves.map((curve) => curve.node_first)); + const undrawn = planned.flatMap((vertex, i) => + i === 0 || + i === planned.length - 1 || + curveOn[i] === false || + drawn.has(i) || + overlap.includes(i) || + !(innerAngleDeg(planned[i - 1], vertex, planned[i + 1]) < 179.9) + ? [] + : [i], + ); + return { overlap, undrawn }; +} + export interface CurveSummaryInput { nodeCount: number; curveOn: boolean[]; @@ -170,6 +267,8 @@ export interface CurveSummaryInput { fresh: boolean; /** 측점 스냅 켬 때 MC 가 일반측점 밖인 곡선 수(366-3) — 끔이면 0. */ offStation?: number; + /** 겹친 노드 · 못 그린 곡선 자리(430 · `routeFlags`). */ + flags?: { overlap: number[]; undrawn: number[] }; } /** 상태줄 꼬리 — 곡선 수·기준 미달·사용자가 손댄 자리를 한 줄로. */ @@ -187,6 +286,7 @@ export function curveSummary(input: CurveSummaryInput): string { ] .filter(Boolean) .join(" · "); + const { overlap, undrawn } = input.flags ?? { overlap: [], undrawn: [] }; if (input.fresh) { const base = input.minRadiusM ? `곡선 기준 R ${input.minRadiusM}m — [저장] 때 반영` : ""; return edits ? `${base}${base ? " · " : ""}${edits}` : base; @@ -195,6 +295,8 @@ export function curveSummary(input: CurveSummaryInput): string { `곡선 ${input.curveCount}곳(하한 R ${input.minRadiusM}m)` + `${input.violationCount ? ` · 기준 미달 ${input.violationCount}곳` : ""}` + `${input.offStation ? ` · 측점 밖 곡선 ${input.offStation}개` : ""}` + + `${overlap.length ? ` · 겹친 노드 ${ipList(overlap)}(0.5 m 안 · 선에서 빠짐)` : ""}` + + `${undrawn.length ? ` · 못 그린 곡선 ${ipList(undrawn)}` : ""}` + `${edits ? ` · ${edits}` : ""}` ); } @@ -219,6 +321,15 @@ interface ServerNode { violations?: string[]; } +/** 노드마다 넣은 편집값(430) — 곡선표 `edits` 칸 · 서버 `node_edits`(⚠ 짝 `B05_Profile_Route_NodeEdits.py`). */ +export interface RouteNodeEdit { + curve: boolean; + /** 넣은 R(그린 R 아님 · 접선 자리에 눌렸어도 넣은 값) · null = 자동. */ + radius_m: number | null; + lock: CurveLock; + arc_m: number | null; +} + /** * 서버가 준 노드·곡선을 **꺾임점 하나 = 곡선 하나**로 편다(2026-09-07). * @@ -231,8 +342,15 @@ interface ServerNode { * ⚠ 서버가 **곡선을 안 둔 자리는 「곡선 없음」으로 연다**. 전부 켬으로 열면 아무것도 안 * 만지고 [확인]만 눌러도 그 자리에 곡선이 새로 생겨 노선이 조용히 바뀐다(서버의 편집 * 갈래는 켜진 자리마다 원호를 끼운다). 내각 179° 이상인 자리가 그렇다. + * + * `edits`(430 · 노드 수와 같을 때만 서버가 줌)가 있으면 곡선 켬끔 · R · 고정 · 고정 길이는 **넣은 값**으로 — + * 그린 R 로 열면 접선 자리에 눌린 R 이 넣은 값으로 굳고 R · 길이 고정이 [저장] 뒤 사라짐. */ -export function flattenServerPlan(nodes: ServerNode[], curves: EditedCurve[]): FlattenedPlan { +export function flattenServerPlan( + nodes: ServerNode[], + curves: EditedCurve[], + edits?: ReadonlyArray | null, +): FlattenedPlan { const replaced = new Map(); const dropped = new Set(); curves.forEach((curve) => { @@ -263,11 +381,14 @@ export function flattenServerPlan(nodes: ServerNode[], curves: EditedCurve[]): F tangent_m: null, violations: curve ? (curve.violations ?? []) : (node.violations ?? []), }); - out.curveOn.push(curve !== undefined); + const edit = edits?.[index]; + out.curveOn.push(edit ? edit.curve : curve !== undefined); // 서버가 고른 반지름을 **그대로 들고 간다** — 안 그러면 편집 한 번에 하한으로 눌린다. - out.curveRadius.push(curve ? Math.round(curve.radius_m * 100) / 100 : null); - out.curveLock.push(null); - out.curveArc.push(null); + out.curveRadius.push( + edit ? edit.radius_m : curve ? Math.round(curve.radius_m * 100) / 100 : null, + ); + out.curveLock.push(edit?.lock ?? null); + out.curveArc.push(edit?.arc_m ?? null); out.apexLock.push(false); if (curve) out.curves.push({ ...curve, node_first: seat, node_last: seat }); }); diff --git a/resources/tester/helper_398_2_curve_input.cjs b/resources/tester/helper_398_2_curve_input.cjs index 1d6beeccd..659ac5430 100644 --- a/resources/tester/helper_398_2_curve_input.cjs +++ b/resources/tester/helper_398_2_curve_input.cjs @@ -20,6 +20,7 @@ const STUBS = { }, centerDirectionOf: () => null, }, + "@ui/ui_template_elements": { showToast: () => {} }, // 곡선 삭제 경고(430) }; function loadTs(file) { diff --git a/resources/tester/helper_430_route_edit_rules.cjs b/resources/tester/helper_430_route_edit_rules.cjs new file mode 100644 index 000000000..7632c8f85 --- /dev/null +++ b/resources/tester/helper_430_route_edit_rules.cjs @@ -0,0 +1,137 @@ +/* 430 평면 형상 제어 규칙 한 곳 — `logic/B05_Profile_UI_RouteEdit_Edits.ts`(하한 검사 · 겹친 노드 · + * 못 그린 곡선 · 넣은 값 되살림) · `_KeyNudge.fitNote` 를 Node 로 돌려 JSON 한 줄 + * (`test_430_route_edit_rules.py` 가 판정). + * node helper_430_route_edit_rules.cjs <서버 곡선표 JSON 파일> + */ +const fs = require("fs"); +const path = require("path"); +const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript")); + +const ROOT = path.join(__dirname, "..", ".."); +const LOGIC = path.join(ROOT, "B05_Profile", "logic"); +const cache = new Map(); + +function loadTs(file) { + const full = path.resolve(file); + if (cache.has(full)) return cache.get(full); + const js = ts.transpileModule(fs.readFileSync(full, "utf8"), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText; + const box = { exports: {} }; + cache.set(full, box.exports); + const localRequire = (request) => + request.startsWith(".") + ? loadTs(path.join(path.dirname(full), `${request}.ts`)) + : require(request); + new Function("exports", "module", "require", js)(box.exports, box, localRequire); + cache.set(full, box.exports); + return box.exports; +} + +const edits = loadTs(path.join(LOGIC, "B05_Profile_UI_RouteEdit_Edits.ts")); +const nudge = loadTs(path.join(LOGIC, "B05_Profile_RouteEdit_KeyNudge.ts")); + +const LIMITS = { minRadiusM: 30, limitRadiusM: 20, limitArcM: 0 }; +// IP1 · IP2 · IP3 — 직선 넉넉(곡선 R 30 다 들어감) +const ROUTE = [ + [0, 0], + [100, 0], + [200, 60], + [300, 0], + [400, 0], +]; + +function cols(planned) { + const n = planned.length; + return { + planned: planned.map((v) => [v[0], v[1]]), + curveOn: Array(n).fill(true), + curveRadius: Array(n).fill(null), + curveLock: Array(n).fill(null), + curveArc: Array(n).fill(null), + apexLock: Array(n).fill(false), + }; +} + +/** 지난 걸음 `before` 에서 `change` 로 고친 뒤 하한 검사 글. */ +function stop(before, change) { + const now = cols(before.planned); + change(now); + const built = edits.rebuildLine(now, LIMITS); + return edits.floorStop(before, now.planned, built.nodes, LIMITS); +} + +const base = cols(ROUTE); +const out = { + // 같은 노드 수 — IP2 를 IP1 쪽 8 m 앞으로(IP1 · IP2 접선 자리 모자람 → R 하한 아래) + moveBreak: stop(base, (c) => (c.planned[2] = [108, 4])), + moveOk: stop(base, (c) => (c.planned[2] = [200, 70])), + // 끼우기 — IP1 바로 뒤 4 m 에 새 노드(IP1 접선 자리 2 m) + insertBreak: stop(base, (c) => { + c.planned.splice(2, 0, [104, 1]); + for (const k of ["curveOn", "curveRadius", "curveLock", "curveArc", "apexLock"]) + c[k].splice(2, 0, k === "curveOn" ? true : k === "apexLock" ? false : null); + }), + // 지우기 — IP2 를 빼도 IP1 · IP3 넉넉 + deleteOk: stop(base, (c) => { + for (const k of ["planned", "curveOn", "curveRadius", "curveLock", "curveArc", "apexLock"]) + c[k].splice(2, 1); + }), + // 둘 넘게 다르면 안 견줌 + manyGap: stop(base, (c) => { + c.planned.splice(1, 0, [50, 0], [52, 0]); + for (const k of ["curveOn", "curveRadius", "curveLock", "curveArc", "apexLock"]) + c[k].splice( + 1, + 0, + ...(k === "curveOn" ? [true, true] : k === "apexLock" ? [false, false] : [null, null]), + ); + }), +}; + +// 이미 하한을 밑돌던 자리는 「새로」가 아님 — 밑돈 노선에서 다시 조금 옮겨도 통과 +const broken = cols(ROUTE); +broken.planned[2] = [108, 4]; +out.alreadyBroken = stop(broken, (c) => (c.planned[2] = [108.5, 4.2])); + +// 겹친 노드 · 못 그린 곡선 +const overlap = [ + [0, 0], + [100, 0], + [100.3, 0.2], + [200, 60], + [300, 0], +]; +out.flags = edits.routeFlags(overlap, Array(5).fill(true), []); +out.flagsOff = edits.routeFlags(ROUTE, [true, false, false, false, true], []); +out.summary = edits.curveSummary({ + nodeCount: 5, + curveOn: Array(5).fill(true), + curveRadius: Array(5).fill(null), + curveLock: Array(5).fill(null), + apexLock: [], + curveCount: 2, + violationCount: 0, + minRadiusM: 30, + fresh: false, + flags: out.flags, +}); + +// fitNote — 손으로 옮긴 고른 IP 는 「밀림」에 안 셈(놓을 때 · 430) · 입력 뒤는 셈(408-1) +const after = ROUTE.map((v, i) => (i === 2 ? [v[0] + 3, v[1]] : i === 3 ? [v[0] + 1, v[1]] : v)); +out.noteHand = nudge.fitNote(ROUTE, after, 2, [], 20, 20, true); +out.noteInput = nudge.fitNote(ROUTE, after, 2, [], 20, 20); + +// 짝 — 서버 곡선표(파이썬이 씀)를 그대로 펴서 넣은 값이 돌아오는가 +const server = JSON.parse(fs.readFileSync(process.argv[2], "utf8")); +const flat = edits.flattenServerPlan(server.nodes, server.curves, server.edits); +out.flat = { + planned: flat.planned, + curveOn: flat.curveOn, + curveRadius: flat.curveRadius, + curveLock: flat.curveLock, + curveArc: flat.curveArc, +}; +const old = edits.flattenServerPlan(server.nodes, server.curves, null); +out.flatOld = { curveRadius: old.curveRadius, curveLock: old.curveLock }; +process.stdout.write(JSON.stringify(out)); diff --git a/resources/tester/test_352_3_analysis_terrain_default.py b/resources/tester/test_352_3_analysis_terrain_default.py index 00aa1b676..eb722d92c 100644 --- a/resources/tester/test_352_3_analysis_terrain_default.py +++ b/resources/tester/test_352_3_analysis_terrain_default.py @@ -49,6 +49,7 @@ def test_편집기_배선() -> None: assert main.count("setAnalysisTerrain(") == 1 # 바꿀 때 한 곳뿐 — 열 때 쓰기 없음 handler = main.split('terrainSelect.addEventListener("change"', 1)[1][:900] assert "setAnalysisTerrain(projectId" in handler - assert "options.draft?.edited(" in handler # 바꾸면 계산 묶음에 알림 + assert "tellDraft()" in handler # 바꾸면 계산 묶음에 알림(430 — 스냅과 한 곳) + assert "options.draft?.edited(" in main.split("function tellDraft()", 1)[1][:400] # 설계 지형이 수치지형도면 확정 모델(수치지형도 서피스) 등고선을 「LAS」로 쓰지 않음 assert 'analysisTerrain(projectId) === "las" && designTerrain === "las"' in main diff --git a/resources/tester/test_390_4_snap_step_text.py b/resources/tester/test_390_4_snap_step_text.py index 3f4766817..70d53fa64 100644 --- a/resources/tester/test_390_4_snap_step_text.py +++ b/resources/tester/test_390_4_snap_step_text.py @@ -58,6 +58,7 @@ def test_간격별_상태줄_글(texts, step, want) -> None: def test_편집기는_고른_간격_글을_씀() -> None: edit = (B05 / "B05_Profile_UI_RouteEdit.ts").read_text(encoding="utf-8") assert "일반측점에 맞췄" not in edit - assert edit.count("applyEdit(snap.text())") == 2 + assert edit.count("applyEdit(snap.text())") == 1 # 켬 · 간격 바꿈 + assert 'applyEdit(stationSnap ? snap.text() : "옮겼습니다.")' in edit # 놓을 때(430) snap = SNAP.read_text(encoding="utf-8") assert "text: () => snapFitText(select.value)" in snap diff --git a/resources/tester/test_430_route_edit_rules.py b/resources/tester/test_430_route_edit_rules.py new file mode 100644 index 000000000..bf24e9aea --- /dev/null +++ b/resources/tester/test_430_route_edit_rules.py @@ -0,0 +1,185 @@ +"""430 평면 형상 제어 규칙 한 곳 — 하한 검사(`applyEdit` 한 곳 · 끼우기 · 지우기 · 손잡이) · +곡선 삭제 155° 경고 · 놓을 때 맞춤 보고 · 스냅 끔 · 간격 즉시 계산 줄 · R · 길이 고정 · +넣은 R 곡선표 저장(짝) · 겹친 노드 · 못 그린 곡선 표시. + +TS 셈은 Node(`helper_430_route_edit_rules.cjs`) · 짝 = 파이썬 `_write_planned_polyline` 이 쓴 +곡선표를 TS `flattenServerPlan` 이 펴서 넣은 값이 돌아오는가. + + ./venv/Scripts/python.exe -m pytest resources/tester/test_430_route_edit_rules.py -q +""" + +import csv +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) + +from B05_Profile import B05_Profile_Router_Replan as replan # noqa: E402 +from B05_Profile.B05_Profile_Route_NodeEdits import node_edits # noqa: E402 +from common_util.common_util_route_polyline import build_planned_polyline # noqa: E402 + +B05 = ROOT / "B05_Profile" +HELPER = Path(__file__).with_name("helper_430_route_edit_rules.cjs") + +# IP2 뒤 직선 16 m — 넣은 R 200 은 접선 자리에 눌려 그려짐 · IP3 바로 뒤 0.3 m 겹친 점 +NODES = [(0.0, 0.0), (120.0, 0.0), (220.0, 70.0), (236.0, 70.0), (236.2, 70.2), (340.0, 0.0)] +FLAGS = [True, True, True, False, True, True] +RADII = [None, 40.0, 200.0, None, None, None] +LOCKS = [None, "radius", "arc", None, "radius", "bogus"] +ARCS = [None, None, 33.5, None, None, None] + + +@pytest.fixture(scope="module") +def saved(tmp_path_factory) -> dict: + path = tmp_path_factory.mktemp("route") / "planned_route.csv" + replan._write_planned_polyline( + path, + NODES, + 30.0, + simplify=False, + curve_flags=FLAGS, + radii=RADII, + locks=LOCKS, + arcs=ARCS, + ) + with replan._nodes_path(path).open(encoding="utf-8") as handle: + nodes = [(float(row["x"]), float(row["y"])) for row in csv.DictReader(handle)] + outline = build_planned_polyline(nodes, min_radius_m=30.0, simplify=False) + return { + "path": path, + "nodes": [node.as_dict() for node in outline.nodes], + "curves": replan._read_curves(path), + "edits": replan._read_curves(path, "edits"), + } + + +@pytest.fixture(scope="module") +def got(saved, tmp_path_factory) -> dict: + server = tmp_path_factory.mktemp("server") / "plan.json" + payload = {key: saved[key] for key in ("nodes", "curves", "edits")} + server.write_text(json.dumps(payload), encoding="utf-8") + run = subprocess.run( # noqa: S603 — 고정 실행 파일 + ["node", str(HELPER), str(server)], + capture_output=True, + text=True, + encoding="utf-8", + timeout=60, + ) + assert run.returncode == 0, run.stderr + return json.loads(run.stdout) + + +# ── 하한 검사 한 곳 ────────────────────────────────────────────────────────── + + +def test_옮겨_새로_깨면_까닭(got) -> None: + assert got["moveBreak"].startswith("하한에 걸려 되돌렸습니다 — IP1") + assert "(곡선반지름 20m)" in got["moveBreak"] + assert got["moveOk"] == "" + + +def test_끼우기_새로_깨면_까닭_지우기_넉넉하면_통과(got) -> None: + assert "IP1" in got["insertBreak"] and "IP2" in got["insertBreak"] + assert got["deleteOk"] == "" + assert got["manyGap"] == "" # 둘 넘게 다르면 안 견줌 + + +def test_이미_밑돈_자리는_새로가_아님(got) -> None: + assert got["alreadyBroken"] == "" + + +# ── 겹친 노드 · 못 그린 곡선 ───────────────────────────────────────────────── + + +def test_겹친_노드_못_그린_곡선(got) -> None: + assert got["flags"] == {"overlap": [2], "undrawn": [1, 3]} + assert got["flagsOff"] == {"overlap": [], "undrawn": []} # 곡선 끈 자리는 「못 그림」 아님 + assert "겹친 노드 IP2(0.5 m 안 · 선에서 빠짐)" in got["summary"] + assert "못 그린 곡선 IP1 · IP3" in got["summary"] + + +def test_놓을_때_손으로_옮긴_IP_는_밀림에_안_셈(got) -> None: + assert got["noteHand"] == " · 함께 밀린 교점 1곳" + assert got["noteInput"] == " · 함께 밀린 교점 2곳" + + +# ── 넣은 R · 고정 곡선표 저장(짝) ──────────────────────────────────────────── + + +def test_곡선표_edits_는_저장_노드와_자리가_같음(saved) -> None: + assert len(saved["edits"]) == len(saved["nodes"]) == len(NODES) - 1 # 겹친 점 하나 빠짐 + assert saved["edits"][2] == {"curve": True, "radius_m": 200.0, "lock": "arc", "arc_m": 33.5} + assert saved["edits"][1]["lock"] == "radius" + assert saved["edits"][3]["curve"] is False + assert saved["edits"][4]["lock"] is None # 모르는 고정 값은 버림 + + +def test_다시_열면_넣은_R_고정이_돌아옴(got, saved) -> None: + flat = got["flat"] + drawn = next(c["radius_m"] for c in saved["curves"] if c["node_first"] == 2) + assert drawn < 200 - 1 # 그린 R 은 눌림 + assert flat["curveRadius"][1:3] == [40, 200] # 넣은 값 + assert flat["curveLock"][1:3] == ["radius", "arc"] + assert flat["curveArc"][2] == 33.5 + assert flat["curveOn"][3] is False + assert got["flatOld"]["curveRadius"][2] == pytest.approx(drawn, abs=0.01) # 옛 곡선표 = 그린 R + + +def test_node_edits_짧은_칸은_기본값() -> None: + edits = node_edits([(0, 0), (10, 0), (20, 5)], None, [None, 15.0]) + assert edits[1] == {"curve": True, "radius_m": 15.0, "lock": None, "arc_m": None} + assert edits[2] == {"curve": True, "radius_m": None, "lock": None, "arc_m": None} + + +def test_편집값_없이_쓴_곡선표는_edits_없음(tmp_path) -> None: + path = tmp_path / "planned_route.csv" + replan._write_planned_polyline(path, NODES, 30.0, simplify=False) + assert replan._read_curves(path, "edits") == [] + + +# ── 배선 ──────────────────────────────────────────────────────────────────── + + +def _read(name: str) -> str: + return (B05 / name).read_text(encoding="utf-8") + + +def test_편집기_배선() -> None: + main = _read("B05_Profile_UI_RouteEdit.ts") + apply_edit = main.split("function applyEdit(", 1)[1][:700] + assert "edits.floorStop(before, planned, nodeInfo, fitLimits())" in apply_edit + assert "restoreSnapshot(before, stop, false)" in apply_edit + assert "curveBar.noteFit(snap.text(), before, index)" in main # 놓을 때 맞춤 보고 + snap = main.split("bindStationSnap(chrome", 1)[1][:400] + assert "tellDraft();" in snap # 끔 · 간격 바꿈 즉시 계산 줄 + assert "snap.changed()" in main.split("function tellDraft()", 1)[1][:400] + assert "plan.node_edits" in main + assert "nodes: () => ({ planned, curveOn, curveRadius, curveLock, curveArc })" in main + assert len(main.splitlines()) <= 695 + + +def test_손잡이_끌기_하한_검사() -> None: + pointer = _read("B05_Profile_UI_RouteEdit_Pointer.ts") + handle = pointer.split("// 곡선 시작·끝점을 끈다", 1)[1][:2200] + assert "shortfallCrossed(" in handle + assert "params.commit(dragHandle?.node ?? dragNode)" in pointer + + +def test_곡선_삭제_155_경고() -> None: + bar = _read("B05_Profile_UI_RouteEdit_CurveBar.ts") + on = bar.split("onCurveOn:", 1)[1][:900] + assert "!curveOptionalAt(inner)" in on and '"warning"' in on + + +def test_저장에_고정_실음_읽기에_node_edits() -> None: + apply = _read("B05_Profile_UI_RouteEdit_Apply.ts") + assert "nodes.curveLock?.[index] ?? null" in apply + assert "nodes.curveArc?.[index] ?? null" in apply + router = _read("B05_Profile_Router_Replan.py") + assert '"node_edits":' in router + assert "locks=list(draft.curveLock) if draft else None" in router