Compare commits

..
16 Commits
Author SHA1 Message Date
DCCONSTRUCTIONS f4cdf3744a feat(ui): integrate fleet equipment and expanded workspace layouts
Compose expanded workspaces and fleet equipment through shared product controls. Integrate device surfaces and preserve the documented UI grammar.
2026-10-29 09:10:02 +03:00
DCCONSTRUCTIONS 755a124bd8 build(node): ship qualified installers with CAN maintenance and rollback
Publish qualified Node and device bundles through versioned installers. Coordinate CAN maintenance, dependency closure, retained rollback and packaging provenance.
2026-10-29 09:10:02 +03:00
DCCONSTRUCTIONS fa8bde584f feat(video): recover camera previews and reduce encoding and playout cost
Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS e06ff9a214 feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS bec20d63e2 feat(monitor): keep operator telemetry live and retire local replicas
Keep operator monitoring in bounded live snapshots and provide scoped replica retirement. Update the board dashboard and retirement regressions.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS 7878937691 feat(viewer): unify spatial clipping, planning and observation surfaces
Share spatial clipping and height slices across live planning and recorded observations. Refine scene navigation, report serialization and viewer presentation.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS f48411f8fe feat(simulation): integrate infrastructure jobs and semantic scene editing
Integrate infrastructure preparation and qualified map delivery with local scenes. Add semantic editing, object provenance, survey caching and operator scene tools.
2026-10-29 09:10:01 +03:00
DCCONSTRUCTIONS 25dc0a1b44 feat(semantics): add portable annotation, learning and review contracts
Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
2026-10-29 09:10:00 +03:00
DCCONSTRUCTIONS 69dc566665 feat(research): preserve urban geometry pipelines and qualification suites
Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
2026-10-29 09:10:00 +03:00
DCCONSTRUCTIONS 5d56237124 feat(routers): add observed router inventory and scoped controls
Separate router discovery, evidence and authorized control from device runtime. Add Node/Core contracts and reusable operator surfaces.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS 8b210258ca feat(usb-can): add isolated adapter runtime and confirmed CAN transactions
Package the adapter SDK boundary and runtime lifecycle. Confirm admitted CAN transactions, bound retained data and test failure paths with synthetic hardware.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS f32c7b400b feat(vesc): extend motor diagnostics, configuration and transport recovery
Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS 115476d2e6 feat(sdk): add bounded media admission, diagnostics and H264 recovery
Introduce deadline-bound admission and common diagnostics for constrained links. Add H264 packetization, recovery and the measured two-thread veryfast encoder path.
2026-10-29 09:09:59 +03:00
DCCONSTRUCTIONS 70ef3f9f1c chore(storage): bound build retention, caches and test resources
Track build ownership, qualified pins and bounded cache/log lifecycles. Move Vite fixtures to a job-owned server helper and preserve private outputs outside Git.
2026-10-29 09:09:58 +03:00
DCCONSTRUCTIONS 55f64f195b Add vector infrastructure maps and persistent location experience 2026-10-10 14:35:50 +03:00
DCCONSTRUCTIONS e095a43f00 Restore collision layers in local route planner 2026-10-10 11:33:47 +03:00
1631 changed files with 154151 additions and 2342 deletions
+3
View File
@@ -56,3 +56,6 @@ node_modules
# Private experiment evidence and generated build archives.
/outputs/
# Packaged WireGuard binaries are published artifacts, not source.
/apps/wireguard-client/build/
+72
View File
@@ -27,9 +27,36 @@ links to that record for monorepo, storage, resource and live-only telemetry rul
build-input packages per active build line; preserve separately designated
qualified releases and required rollback artifacts. Do not accumulate a new
full package after every iteration without retiring superseded intermediates.
- Build storage lifecycle is implemented by `scripts/packaging/build_retention.py`;
follow `docs/STORAGE_RETENTION.md`. New input generators return a persistent
active owner handle. After the remote job/transfer/qualification is confirmed
terminal, close only your own hold with `finish` (pin qualified/rollback
outcomes), review its plan and apply it as part of build completion. Never
expire active holds by age or declare unknown legacy inputs disposable.
- Run local Python validation through `scripts/check_python.py pytest|ruff|mypy`
(pass the usual file/selection arguments). It owns temporary caches, disables
persistent pytest/Ruff cache output, and cleans its own scratch after child
processes end. Never sweep another active job's cache or unknown crash residue.
- Runtime cache publication quotas and bounded service journals are defined in
`docs/STORAGE_RETENTION.md`. Existing replay/overlay data remains protected;
a full quota refuses a new copy rather than deleting recovery material.
- Check disk space before large builds or captures. Keep task scratch work
under `.runtime` and clean generated scratch at completion; do not scatter
temporary project folders through the parent repository directory.
- Owner amendment, 2026-10-19: completed simulation/urban-infrastructure
engineering experiments must not retain unlimited raw frames, render arrays
and step-by-step traces by default. At closeout preserve a compact textual
report, exact inputs/configuration/source identities, result/limitations and
regression evidence; archive text with verified hashes, then retire the
explicitly inventoried disposable derived files after all owners stop.
Use one content-addressed text copy for duplicates. Keep only the limited
visual evidence needed by the final report. Do not leave a complete new
media export after every iteration or require the owner to clean it manually.
This is a closeout obligation for engineering-owned scratch, not permission
to TTL-delete application runs, scans, accepted maps, working code, offline
dependencies, installers, qualified releases or pinned rollback. Unknown or
active ownership blocks removal; retain a deletion receipt and link the
archive from the report/Ops. See the amendment in docs/STORAGE_RETENTION.md.
- Other repositories, platform worktrees, infrastructure, DOC, workspace bridge,
Site/SEO, BIM Viewer, Device Core, Design Guideline, and Gaussian Pipeline are
separate ownership boundaries. Mission Core cleanup must not alter them.
@@ -39,6 +66,14 @@ links to that record for monorepo, storage, resource and live-only telemetry rul
monitoring requires an explicitly provisioned separate service; simulation
evidence and recordings have a separate lifecycle and must not be deleted as
part of telemetry cleanup.
- Owner amendment, 2026-10-20: new semantic-learning images, observations,
datasets, checkpoints and heavy experiments belong to a separate portable
persistent store on Worker 006, outside the source checkout and container
writable layer. Never accumulate them on the operator Mac or add a local
fallback. Core may keep viewer scenes, semantic results and bounded edit
metadata. Saving an edit is not dataset preparation or training acceptance;
retain the immutable algorithm result and human provenance separately.
See `docs/SEMANTIC_EDITOR.md` for the delivered scope and outstanding gates.
## Non-negotiable safety boundaries
@@ -254,3 +289,40 @@ decoders before BLE/Wi-Fi/data-session evidence exists.
- Spatial evidence uses 3D by default. Image-space reprojection may be offered
as a 2D diagnostic mode inside the same reusable viewer. Primary evidence
viewers must provide the canonical expand/restore action.
## Urban semantic agent contract — owner requirement, 2026-10-26
- Product foundation: read `docs/SCENE_SEMANTICS_PRODUCT_CONCEPT.md`. Each scan is
a standalone local scene, including unnamed/unmapped locations. Raw recorded
sensor points support localization; Gaussian observations support the current
semantic research. Never substitute Gaussian-derived geometry for raw points.
- No GPS/address/public-map prerequisite and no automatic cross-scan geographic
matching, overlap search, registration or merging. Those require a separate
explicit owner request. Named train/evaluation source lists do not authorize
geographic investigation. Preserve source lineage and evaluation honesty.
- Crosswalks are functionally important; the target includes all observed road
markings for scene context, interface/product value and difficult-task
validation. Do not reduce the scope to demo-only markings or crosswalks only.
- For automated infrastructure annotation, dataset preparation and learning,
begin with live Ops MISSIONCOR-93 (agent contract) and MISSIONCOR-88 (product),
then `docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md`. Reuse the current hypothesis
register and existing experiments; a new chat does not reset the investigation.
- The owner explicitly requests MISSIONCOR-93 to hold current architecture,
rules, bounded next steps and portable handoff. This is the scoped exception
to the earlier delivered-results-only Ops rule. Keep raw logs/media in local
engineering evidence; update the current card blocks after meaningful changes.
- Root owns the useful outcome, real dispatch, integration and final decision.
Use one reusable critic and an optional bounded research scout, at most two
active helpers and no nested delegation. Send compact briefs, not full history.
- New annotation cycles use the v2 objective/dispatch contract. Approved partial
annotations are distinct from completing the enclosing product work package.
Handle introduced critical regressions within the session or revert/isolate
the change. Do not declare success merely because a ledger or test completed.
- Choose reusable pipelines against actual inputs/outputs and accumulated
evidence before narrow tuning. Every closed hypothesis states tested scope,
supporting artifacts and a substantive condition for reopening. Do not repeat
unchanged searches or model variants under a new name.
- Worker access/power/runtime authority comes from the owner's current session
instructions, never from the card or an old experiment's training allowance.
+26
View File
@@ -19,6 +19,7 @@
"@rerun-io/web-viewer": "0.36.3",
"meshoptimizer": "1.1.1",
"playcanvas": "2.21.4",
"polygon-clipping": "0.15.7",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"three": "0.185.1",
@@ -1757,6 +1758,16 @@
"node": ">=18.3.0"
}
},
"node_modules/polygon-clipping": {
"version": "0.15.7",
"resolved": "https://registry.npmjs.org/polygon-clipping/-/polygon-clipping-0.15.7.tgz",
"integrity": "sha512-nhfdr83ECBg6xtqOAJab1tbksbBAOMUltN60bU+llHVOL0e5Onm1WpAXXWXVB39L8AJFssoIhEVuy/S90MmotA==",
"license": "MIT",
"dependencies": {
"robust-predicates": "^3.0.2",
"splaytree": "^3.1.0"
}
},
"node_modules/postcss": {
"version": "8.5.19",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.19.tgz",
@@ -1817,6 +1828,12 @@
"node": ">=0.10.0"
}
},
"node_modules/robust-predicates": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
"integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",
"license": "Unlicense"
},
"node_modules/rollup": {
"version": "4.62.2",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz",
@@ -1888,6 +1905,15 @@
"node": ">=0.10.0"
}
},
"node_modules/splaytree": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/splaytree/-/splaytree-3.2.3.tgz",
"integrity": "sha512-7OXrNWzy6CK+r7Ch9OLPBDTKfB6XlWHjX4P0RU5B3IgFuWPeYN0XtRtlexGRjgbQxpfaUve6jTAwBGWuGntz/w==",
"license": "MIT",
"engines": {
"node": ">=18.20 || >=20"
}
},
"node_modules/three": {
"version": "0.185.1",
"resolved": "https://registry.npmjs.org/three/-/three-0.185.1.tgz",
+2 -1
View File
@@ -9,7 +9,7 @@
"prebuild": "node scripts/install-rerun-navigation.mjs",
"build": "tsc -b && vite build",
"preview": "vite preview",
"test:unit": "node --test test/*.test.mjs",
"test:unit": "node --test --test-concurrency=1 test/*.test.mjs",
"typecheck": "tsc -b --pretty false"
},
"dependencies": {
@@ -23,6 +23,7 @@
"@rerun-io/web-viewer": "0.36.3",
"meshoptimizer": "1.1.1",
"playcanvas": "2.21.4",
"polygon-clipping": "0.15.7",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"three": "0.185.1",
+4 -5
View File
@@ -722,9 +722,9 @@ export default function App() {
workspace.navigationOpen && activeRoot !== null
}
contentOpen={workspace.contentOpen && activeDefinition !== null}
contentExpanded={workspace.contentExpanded}
contentExpanded
header={header}
stage={
stage={activeDefinition ? null :
<LandingStage
root={currentRoot}
backendStatus={runtime.backendStatus}
@@ -797,8 +797,7 @@ export default function App() {
: activeDefinition.title
}
description={activeDefinition.description}
expanded={workspace.contentExpanded}
onExpandedChange={workspace.setContentExpanded}
expanded
headerTools={
activeDefinition.kind === "device" ? (
<StatusBadge tone={phaseTone(runtime.state?.phase)}>
@@ -836,7 +835,7 @@ export default function App() {
/>
) : activeDefinition.kind === "missions" ? (
<div ref={setWorkspaceHeaderToolsHost} />
) : activeDefinition.kind === "vehicles" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? null : activeDefinition.kind === "datasets" ? (
) : activeDefinition.kind === "vehicles" ? <div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "simulations" ? <div className="ai-polygon__actions" ref={setWorkspaceHeaderToolsHost} /> : activeDefinition.kind === "datasets" ? (
<StatusBadge tone="neutral">Offline evaluation</StatusBadge>
) : activeDefinition.kind === "lab-archive" ? (
laboratoryAnnotation.control
@@ -171,7 +171,7 @@ export function CanonicalRecordedLabReplay<
>
{splitView || paneToolbarsAlwaysVisible ? (
<div
className="m4-replay-threat-visual__pane-toolbar"
className="m4-replay-threat-visual__pane-toolbar nodedc-viewport-controls"
data-pane-toolbar="media"
data-multi-semantic={mediaMultiLayer ? "true" : undefined}
>
@@ -190,7 +190,7 @@ export function CanonicalRecordedLabReplay<
>
{splitView || paneToolbarsAlwaysVisible ? (
<div
className="m4-replay-threat-visual__pane-toolbar"
className="m4-replay-threat-visual__pane-toolbar nodedc-viewport-controls"
data-pane-toolbar="spatial"
>
{spatialLeadingControl}
@@ -83,7 +83,7 @@ export function LaboratoryEvidenceViewer<
}, [expanded, onExpandedChange]);
const controls = (
<div className="laboratory-evidence-viewer__controls">
<div className="laboratory-evidence-viewer__controls nodedc-viewport-controls">
{actions}
{modeControlsVisible && secondaryMode ? (
<SegmentedControl
@@ -137,7 +137,7 @@ export function LaboratoryEvidenceViewer<
{children}
</div>
{transport ? (
<div className="laboratory-evidence-viewer__transport">
<div className="laboratory-evidence-viewer__transport nodedc-viewport-controls">
{transport}
</div>
) : null}
@@ -149,7 +149,7 @@ export function LaboratoryEvidenceViewer<
</div>
{overlay}
{transport ? (
<div className="laboratory-evidence-viewer__transport">
<div className="laboratory-evidence-viewer__transport nodedc-viewport-controls">
{transport}
</div>
) : null}
@@ -101,7 +101,7 @@ export function LaboratoryReviewWorkspaceFrame({
keepFocusInside(event, event.currentTarget);
}}
>
<header className="laboratory-review-workspace__toolbar">{toolbar}</header>
<header className="laboratory-review-workspace__toolbar nodedc-viewport-controls">{toolbar}</header>
<div className="laboratory-review-workspace__stage">{stage}</div>
{inspector ? <footer className="laboratory-review-workspace__inspector">{inspector}</footer> : null}
{overlays}
@@ -1,3 +1,4 @@
import {heightSlice} from "../../core/heightSlice";
import {useEffect,useRef,useState} from 'react';
import {Button,LoadingRegion,RangeControl} from '@nodedc/ui-react';
import {createIsolatedRerunHost} from '../rerun/isolatedRerunHost';
@@ -26,16 +27,20 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
const optionsRef=useRef(options);optionsRef.current=options;
const stateRef=useRef({active,revision});stateRef.current={active,revision};
const ceilingRef=useRef<number|null>(null);
const floorRef=useRef<number|null>(null);
const boundsRef=useRef<{min:number;max:number}|null>(null);
const host=useRef<HTMLDivElement>(null);
const [state,setState]=useState('loading'),[retry,setRetry]=useState(0);
const [bounds,setBounds]=useState<{min:number;max:number}|null>(null);
const [ceiling,setCeiling]=useState<number|null>(null);
const [floor,setFloor]=useState<number|null>(null);
useEffect(()=>{
ceilingRef.current=null;floorRef.current=null;setCeiling(null);setFloor(null);
},[runId]);
useEffect(()=>{
ceilingRef.current=null;
const next=heightBounds&&Number.isFinite(heightBounds.min)&&Number.isFinite(heightBounds.max)&&heightBounds.max>heightBounds.min?heightBounds:null;
boundsRef.current=next;
setBounds(next);setCeiling(null);
setBounds(next);
},[runId,heightBounds?.min,heightBounds?.max]);
useEffect(()=>{
if(!host.current)return;
@@ -54,6 +59,7 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
stopStream=startPlanningSceneStream({
url:`${plannerBase}/live-tests/${runId}/scene-delta.rrd`,
snapshot:()=>({...stateRef.current,options:{...optionsRef.current,
...(floorRef.current===null?{}:{floor_m:floorRef.current}),
...(ceilingRef.current===null?{}:{ceiling_m:ceilingRef.current})}}),
apply:async(bytes,delivery)=>{
if(disposed)return;
@@ -62,9 +68,6 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
const previous=boundsRef.current;
if(!previous||previous.min!==next.min||previous.max!==next.max){
boundsRef.current=next;setBounds(next);
if(ceilingRef.current!==null&&(ceilingRef.current<next.min||ceilingRef.current>next.max)){
ceilingRef.current=null;setCeiling(null);
}
}
}
sceneAvailable=true;
@@ -89,15 +92,15 @@ export function PlanningLiveScene({runId,options={},active=false,revision=0,heig
return()=>{disposed=true;stopStream?.();reporter.dispose();clearTimeout(timeout);runtime.dispose();};
},[runId,retry]);
const sourceBounds=bounds??heightBounds;
const rangeBounds=sourceBounds?{min:Math.min(sourceBounds.min,0),max:CLIP_CEILING_M}:null;
const rangeBounds=sourceBounds?{min:Math.min(sourceBounds.min,0,floor??Infinity),max:Math.max(CLIP_CEILING_M,sourceBounds.max,ceiling??-Infinity)}:null;
return <LoadingRegion loading={state==='loading'} label="Загрузка эталона и нового прохода" className="planning-live__scene">
<div ref={host} className="session-overview__runtime rerun-single-view-content" style={{visibility:state==='ready'?'visible':'hidden'}} />
{rangeBounds&&state==='ready'&&<div className="session-overview__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={ceiling??rangeBounds.max} min={rangeBounds.min} max={rangeBounds.max} step="any"
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={[floor??rangeBounds.min,ceiling??rangeBounds.max]} min={rangeBounds.min} max={rangeBounds.max} step="any"
formatValue={value=>`${value.toFixed(1).replace('.',',')} м`} formatLimit={value=>value.toFixed(1).replace('.',',')}
onChange={value=>{
const next=value>=rangeBounds.max-Math.max(1,rangeBounds.max-rangeBounds.min)*1e-9?null:value;
ceilingRef.current=next;setCeiling(next);
const next=heightSlice(value,[rangeBounds.min,rangeBounds.max]);
floorRef.current=next.floor;setFloor(next.floor);ceilingRef.current=next.ceiling;setCeiling(next.ceiling);
}}/>
</div>}
{state==='error'&&<div className="session-overview__empty"><span>Обновление сцены недоступно.</span><Button onClick={()=>setRetry(v=>v+1)}>Повторить подключение сцены</Button></div>}
@@ -7,11 +7,11 @@ export function ObservationMount({element,className='observation-mount'}:{elemen
useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]);
return <div ref={ref} className={className}/>;
}
export function ObservationDeck({ids,mounts,layout,onTreeChange,labels,focusedId,children}:{
export function ObservationDeck({ids,mounts,layout,onTreeChange,labels,focusedId,minimumSizes,children}:{
ids:string[];mounts:Map<string,HTMLElement>;layout:ObservationLayout;onTreeChange:(tree:DockTree)=>void;
labels:Record<string,string>;focusedId?:string|null;children:ReactNode;
minimumSizes?:Record<string,{width:number;height:number}>; labels:Record<string,string>;focusedId?:string|null;children:ReactNode;
}){
return <DockLayout tree={observationTree(layout,ids)} onTreeChange={onTreeChange}
focusedId={focusedId} panels={ids.map(id=>({id,label:labels[id]??id}))}
focusedId={focusedId} panels={ids.map(id=>({id,label:labels[id]??id,minimumSize:minimumSizes?.[id],preferredSize:!layout.tree&&!Object.keys(layout.splits).length?minimumSizes?.[id]:undefined}))}
renderPanel={id=><ObservationMount element={mounts.get(id)!}/>}>{children}</DockLayout>;
}
@@ -9,5 +9,5 @@ export function ObservationPanelHeader({children}:{children:ReactNode}) {
measure();const observer=new ResizeObserver(measure);observer.observe(header);
return()=>observer.disconnect();
},[]);
return <header ref={ref} className="observation-panel__header">{children}</header>;
return <header ref={ref} className="observation-panel__header nodedc-viewport-controls">{children}</header>;
}
@@ -1,3 +1,4 @@
import { heightSlice } from "../../core/heightSlice";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { Button, LoadingRegion, RangeControl, SegmentedControl } from "@nodedc/ui-react";
import { createIsolatedRerunHost } from "../rerun/isolatedRerunHost";
@@ -11,6 +12,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const [retry, setRetry] = useState(0);
const [metadata, setMetadata] = useState<OverviewSpatialMetadata | null>(null);
const [ceiling, setCeiling] = useState<number | null>(null);
const [floor, setFloor] = useState<number | null>(null);
const [mode, setMode] = useState<OverviewViewMode>("3d");
const [viewError, setViewError] = useState<string | null>(null);
const [visiblePoints, setVisiblePoints] = useState<number | null>(null);
@@ -26,7 +28,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const abort = new AbortController();
appliedMode.current = null;
setState("loading");
setMetadata(null); setCeiling(null); setMode("3d"); setVisiblePoints(null); setViewError(null);
setMetadata(null); setCeiling(null); setFloor(null); setMode("3d"); setVisiblePoints(null); setViewError(null);
setRepresentation("original"); setAppliedRepresentation("original"); setUpdating(false);
void fetchOverviewSpatial(sourceUrl, abort.signal).then(data => {
if (disposed) return;
@@ -56,7 +58,7 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
const timer = setTimeout(() => {
const aspect = Math.max(.1, Math.min(20, (host.current?.clientWidth ?? 1) / Math.max(1, (host.current?.clientHeight ?? 1) - 28)));
void updateOverviewSpatial(sourceUrl, ceiling, appliedMode.current === mode ? null : mode, aspect, abort.signal,
comparison?.generation ?? null, comparison ? representation : "original").then(result => {
comparison?.generation ?? null, comparison ? representation : "original", floor).then(result => {
if (abort.signal.aborted || !controller.current) return;
controller.current.channel.send_rrd(result.bytes);
appliedMode.current = mode;
@@ -65,12 +67,12 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
}).catch(() => { if (!abort.signal.aborted) { setUpdating(false); setViewError("Не удалось обновить вид облака. Показан предыдущий вид."); } });
}, 180);
return () => { abort.abort(); clearTimeout(timer); };
}, [state, metadata, sourceUrl, ceiling, mode, retry, comparison, representation]);
}, [state, metadata, sourceUrl, ceiling, floor, mode, retry, comparison, representation]);
const low = comparison?.height_min_m ?? metadata?.height_min_m;
const high = comparison?.height_max_m ?? metadata?.height_max_m;
return <>
<div className={`session-overview__scene-head ${hideTitle?"session-overview__scene-head--end":""}`}>{!hideTitle&&<h2>Облако и траектория</h2>}
<div className={`session-overview__scene-head nodedc-viewport-controls ${hideTitle?"session-overview__scene-head--end":""}`}>{!hideTitle&&<h2>Облако и траектория</h2>}
{compareVersions && comparison && <SegmentedControl label="Версия облака" value={representation} onChange={setRepresentation}
items={[{ value: "original", label: "Исходное", disabled: state !== "ready" }, { value: "corrected", label: "Исправленное", disabled: state !== "ready" }]} />}
<SegmentedControl label="Вид облака" value={mode} onChange={setMode}
@@ -80,15 +82,15 @@ export function SessionOverviewScene({ sourceUrl, toolbar, hideTitle=false, comp
<LoadingRegion loading={state === "loading" || (state === "ready" && !!metadata && visiblePoints === null && !viewError)} label="Загрузка облака" className="session-overview__scene">
<div ref={host} className={`session-overview__runtime ${hideTitle?"rerun-single-view-content":""}`} style={{ visibility: state === "ready" && metadata && visiblePoints !== null ? "visible" : "hidden" }} />
{low != null && high != null && high > low && state === "ready" && <div className="session-overview__height">
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={ceiling ?? high} min={low} max={high} step="any"
<RangeControl orientation="vertical" limitSide="left" label="Срез" value={[floor ?? low, ceiling ?? high]} min={low} max={high} step="any"
formatValue={value => `${value.toFixed(1).replace('.', ',')} м`} formatLimit={value => value.toFixed(1).replace('.', ',')}
onChange={value => setCeiling(value >= high - Math.max(1, high - low) * 1e-9 ? null : value)} />
onChange={value => { const next = heightSlice(value, [low, high]); setFloor(next.floor); setCeiling(next.ceiling); }} />
</div>}
{state === "error" && <div className="session-overview__empty"><span>Не удалось открыть облако.</span><Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>}
</LoadingRegion>
<span className="session-overview__note" role="status" aria-busy={updating}>
{updating ? "Обновление · " : comparison ? `${appliedRepresentation === "corrected" ? "Исправленное" : "Исходное"} · ` : ""}
{ceiling == null ? "Без среза" : `Высота ≤ ${ceiling.toFixed(1)} м`} · {visiblePoints?.toLocaleString("ru-RU") ?? "—"} точек
{floor == null && ceiling == null ? "Без среза" : `${floor == null ? "" : `${floor.toFixed(1)} м ≤ `}Высота${ceiling == null ? "" : ` ≤ ${ceiling.toFixed(1)} м`}`} · {visiblePoints?.toLocaleString("ru-RU") ?? "—"} точек
{comparison && <><br />Выборка для просмотра. Исходная запись сохранена отдельно.</>}
</span>
{viewError && <div className="session-overview__note" role="alert">{viewError}<Button onClick={() => setRetry(n => n + 1)}>Повторить</Button></div>}
@@ -22,6 +22,7 @@
.observation-panel__title { display:flex; align-items:center; gap:var(--nodedc-space-2); flex:1; min-width:0; }
.observation-header-slot, .observation-header-slot > div { display:flex; align-items:center; gap:var(--nodedc-space-2); flex-shrink:0; }
.observation-header-slot:has(> div:empty) { display:none; }
.observation-panel__title .observation-header-slot, .observation-panel__title .observation-header-slot > div { min-width:0; max-width:100%; flex-shrink:1; }
.observation-layer-select { min-width:0; max-width:120px; }
.observation-layer-select button { max-width:100%; }
.observation-layer-select button > span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
@@ -29,6 +30,7 @@
.observation-source__media video, .observation-source__media canvas { width:100%; height:100%; object-fit:contain; }
.observation-source__media[data-live="false"] > *, .observation-source__media [data-live="false"] { visibility:hidden; }
.observation-source__notice { position:absolute; inset:max(30%, calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3))) var(--nodedc-space-4) auto; text-align:center; color:var(--nodedc-text-secondary); font-size:calc(var(--nodedc-font-size-lg) * .7); }
.observation-source__notice--centered { inset:var(--observation-overlay-header-space, 0px) 0 0; margin:0; padding:var(--nodedc-space-4); display:grid; place-content:center; font-size:var(--nodedc-font-size-sm); pointer-events:none; }
.observation-rerun, .observation-rerun > div, .observation-map > div { width:100%; height:100%; }
.observation-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-4); }
.observation-layer { display:grid; grid-template-columns:minmax(0, 1fr) 50%; align-items:center; gap:var(--nodedc-space-3); }
@@ -45,10 +47,11 @@
.observation-panel-drag.is-dragging { z-index:var(--nodedc-layer-panel); }
.observation-split:has(.observation-panel-drag.is-dragging),
.observation-split > .nodedc-split-pane__panel:has(.observation-panel-drag.is-dragging) { position:relative; overflow:visible; z-index:var(--nodedc-layer-panel); }
@container (max-width:340px) {
@container (max-width:420px) {
.observation-panel__header { flex-wrap:wrap; }
.observation-panel__title { min-width:80px; }
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; }
.observation-panel__title:has(.rover-view__title) { min-width:min(160px, 100%); }
.observation-panel__header > .observation-actions { max-width:100%; flex-wrap:wrap; justify-content:flex-end; margin-left:auto; gap:var(--nodedc-space-1); }
}
.observation-panel__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); }
@@ -0,0 +1,32 @@
import {useState} from 'react';
import {Button,Description,Select,SettingsCard,Switch,Window,WindowFooterActions} from '@nodedc/ui-react';
import {localDevOptions,type DevOptions,type RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
import './roverLogs.css';
export function RoverDevWindow({capture,close,started}:{capture:RoverDiagnostics;close:()=>void;started:()=>void}){
const [options,setOptions]=useState<DevOptions>({...localDevOptions});
const [local,setLocal]=useState({enabled:true,preview:true});
const set=(key:keyof DevOptions,value:boolean|number)=>setOptions(current=>({...current,[key]:value}));
const rates=[8,16,32,64].map(value=>({value:String(value),label:`${value} кбит/с`}));
const begin=async()=>{if(await capture.toggle(options,local)){started();close();}};
return <Window open onClose={close} title="Настройки DEV-записи" size="md" footer={<WindowFooterActions><Button onClick={close}>Отмена</Button><Button variant="primary" loading={capture.pending} disabled={!capture.state.options_supported} onClick={()=>void begin()}>Начать запись</Button></WindowFooterActions>}>
<div className="rover-dev-options">
<Description>Запись сохраняется на борту. После завершения её можно скачать в окне логов. Закрытие окна не останавливает запись.</Description>
<SettingsCard title="Что записывать" description="Переходы управления, остановки и ошибки записываются всегда.">
<Switch label="Подробные замеры моторов" checked={options.motor_samples} onChange={value=>set('motor_samples',value)}/>
<Switch label="Сетевые события и распределение полосы" checked={options.network} onChange={value=>set('network',value)}/>
</SettingsCard>
<SettingsCard title="Замеры на компьютере" description="Задержки команд и события браузера сохраняются отдельно от записи борта. Эти замеры не передаются на борт.">
<Switch label="Записать замеры Core и браузера" checked={local.enabled} onChange={enabled=>setLocal(current=>({...current,enabled}))}/>
{local.enabled&&<><Switch label="Добавить статистику видео" checked={local.preview} onChange={preview=>setLocal(current=>({...current,preview}))}/><Description>Без записи изображения. Замер хранится в памяти до перезапуска Core: не более 15 минут и последних 6000 событий. После остановки сохраните его отдельной кнопкой в окне логов.</Description></>}
</SettingsCard>
<SettingsCard title="Передача во время записи" description={!options.live&&!options.core_trace?'Диагностические события остаются на борту. По сети передаётся только короткое состояние записи.':'Эти потоки используют сеть. На слабом канале их можно отключить и скачать файл позже.'}>
<Switch label="Показывать события онлайн" checked={options.live} onChange={value=>set('live',value)}/>
{options.live&&<Select label="Лимит live-событий" value={String(options.live_kbps)} options={rates} onChange={value=>set('live_kbps',Number(value))}/>}
<Switch label="Добавлять события Core и браузера" checked={options.core_trace} onChange={value=>set('core_trace',value)}/>
{options.core_trace&&<><Description>Эти события передаются с компьютера оператора на борт. При нехватке полосы пропуски отмечаются в записи.</Description><Select label="Лимит событий на борт" value={String(options.core_kbps)} options={rates} onChange={value=>set('core_kbps',Number(value))}/></>}
</SettingsCard>
{!capture.state.options_supported&&<Description>Борт ещё не подтвердил доступность настроек записи. Запуск станет доступен после подключения совместимого борта.</Description>}
</div>
</Window>;
}
@@ -0,0 +1,24 @@
import {createPortal} from 'react-dom';
import {Button,StatusBadge} from '@nodedc/ui-react';
import type {RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
import './roverLogs.css';
export function RoverLogs({capture,header}:{capture:RoverDiagnostics;header:ObservationHeaderTargets}){
const storage=capture.state.node?.storage,failed=storage?.error||capture.state.node?.transport_error;
const status=failed?'Ошибка записи':capture.state.closing?'Завершение записи':storage?.closed?'Запись завершена':capture.state.node?.active?'Запись на борт':'Ожидание борта';
return <>
{createPortal(<StatusBadge variant="indicator" tone={failed?'danger':capture.state.node?.active?'success':'warning'} aria-label={status} title={status}/>,header.statusTarget)}
<div className="rover-logs">
<div className="rover-logs__actions"><Button disabled={!storage?.file} loading={capture.saving} onClick={()=>void capture.save()}>Сохранить с борта</Button>{capture.state.local_capture?.id&&<Button loading={capture.saving} onClick={()=>void capture.saveLocal()}>Сохранить с компьютера</Button>}</div>
<p>{status} · {storage?.written??0} записей{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</p>
{storage?.file&&<p title={storage.file}>{storage.file}</p>}
{failed&&<p role="alert">Файл может быть неполным: {failed}</p>}
<p>{capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</p>
{capture.state.local_capture?.id&&<p>Замер компьютера: {capture.state.local_capture.active?'идёт запись':'завершён'} · {capture.state.local_capture.sequence??0} событий{capture.state.local_capture.dropped?` · Пропущено: ${capture.state.local_capture.dropped}`:''}. Сохраните до перезапуска Core.</p>}
<div className="rover-logs__entries" role="log" aria-live="off" aria-label="События DEV-сессии">
{[...capture.rows].reverse().map(item=>{const row=item.record??item;return <pre key={item.record_sequence}>{JSON.stringify(row,null,2)}</pre>;})}
</div>
</div>
</>;
}
@@ -1,7 +1,9 @@
import {ComparisonTable,Description,StatusBadge} from '@nodedc/ui-react';
import type {RoverState} from '../../core/fleet/useRoverControl';
import type {RoverObservationStatus} from '../../core/fleet/roverObservation';
import {drivePositions} from '../../../../../plugins/vesc/frontend/src/model';
const number=(v:number|undefined,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits}):'—';
export function RoverTelemetry({state}:{state:RoverState}){
export function roverTelemetryTable(state:RoverState){
const devices=state.snapshot.devices??[],profile=state.snapshot.profile;
const positions=drivePositions(profile?.layout??null);
const assigned=Object.entries(profile?.bindings??{}).map(([slot,binding])=>({
@@ -9,17 +11,19 @@ export function RoverTelemetry({state}:{state:RoverState}){
reading:devices.find(d=>d.id===binding.device_id&&d.uuid===binding.uuid),
}));
const readings=[...assigned,...devices.filter(d=>!assigned.some(a=>a.id===d.id&&a.uuid===d.uuid)).map(d=>({...d,reading:d}))];
return <div className="rover-telemetry">
{!state.fresh?<p>Нет свежих показаний VESC.</p>:!readings.length?<p>Получение показаний VESC…</p>:readings.map(d=>{
const fresh=!!d.reading&&d.reading.age_ms<1000,v=fresh?d.reading?.values:undefined;
return <section key={d.uuid}><strong>{d.label}</strong><span>VESC {d.uuid.slice(0,6).toUpperCase()}{!d.reading?' · Нет связи':!fresh?' · Нет свежих данных':''}</span>
<dl><div><dt>Ток мотора</dt><dd>{number(v?.motor_current_a)} А</dd></div>
<div><dt>Ток батареи</dt><dd>{number(v?.input_current_a)} А</dd></div>
<div><dt>Напряжение</dt><dd>{number(v?.input_voltage_v)} В</dd></div>
<div><dt>Обороты, ERPM</dt><dd>{number(v?.erpm,0)}</dd></div>
<div><dt>Контроллер</dt><dd>{number(v?.mos_temperature_c)} °C</dd></div>
<div><dt>Ошибка VESC</dt><dd>{v?v.fault_code===0?'Нет':String(v.fault_code):'—'}</dd></div></dl>
</section>;
})}
</div>;
const fresh=(d:typeof readings[number])=>state.fresh&&!!d.reading&&Number.isFinite(d.reading.age_ms)&&d.reading.age_ms>=0&&d.reading.age_ms<1000;
const metrics=[['motor_current_a','Ток мотора','А',1],['input_current_a','Ток батареи','А',1],['input_voltage_v','Напряжение','В',1],['erpm','Обороты, ERPM','',0],['mos_temperature_c','Контроллер','°C',1]] as const;
return {
columns:readings.map(d=>({id:d.id+':'+d.uuid,label:d.uuid.slice(0,6).toUpperCase()})),
rows:[{id:'position',label:'Расположение',cells:readings.map(d=>d.label||'Не назначено')},
{id:'status',label:'Связь',cells:readings.map(d=>!state.fresh?'Нет данных':!d.reading?'Нет связи':fresh(d)?'В сети':'Нет данных')},
...metrics.map(([key,label,unit,digits])=>({id:key,label,cells:readings.map(d=>{const value=fresh(d)?d.reading?.values?.[key]:undefined;return typeof value==='number'&&Number.isFinite(value)?`${number(value,digits)}${unit?' '+unit:''}`:'—';})})),
{id:'fault',label:'Ошибка VESC',cells:readings.map(d=>{const code=fresh(d)?d.reading?.values?.fault_code:undefined;return typeof code==='number'?code===0?'Нет':String(code):'—';})}],
};
}
export function RoverTelemetry({state,observation}:{state:RoverState;observation?:RoverObservationStatus}){
const table=roverTelemetryTable(state);
return <div className="rover-telemetry">{observation?.label&&<StatusBadge tone="warning" pulse={observation.pulse}>{observation.label}</StatusBadge>}{table.columns.length?<ComparisonTable density="compact" label="Телеметрия VESC" heading="VESC" {...table}/>:!observation?.label&&<Description>{state.fresh?'Получение показаний VESC…':'Нет свежих показаний VESC.'}</Description>}</div>;
}
export function roverTelemetryMinimum(state:RoverState){return {width:Math.max(288,144+88*roverTelemetryTable(state).columns.length),height:280};}
@@ -1,45 +1,63 @@
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
import {createPortal} from 'react-dom';
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,Switch,TextField,ToastStack,Window} from '@nodedc/ui-react';
import {keysFor,roverSettings,type RoverMode} from '../../core/fleet/roverInput';
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react';
import {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput';
import {roverDevEvent} from '../../core/fleet/roverDevEvents';
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
import type {RoverController} from '../../core/fleet/useRoverControl';
import {roverObservationStatus,type RoverObservationStatus} from '../../core/fleet/roverObservation';
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
import './rover.css';
const Scene=lazy(()=>import('./editor/RoverScene'));
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'};
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление вкл',driving:'Управление вкл',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выкл',fault:'Управление остановлено'};
export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){
export function RoverView({vehicleID,controller:c,header,active,observation}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
const storage=`missioncore.rover-view.v1:${vehicleID}`;
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
const [open,setOpen]=useState(false),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
const [editing,setEditing]=useState(false);
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null);
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();setConfirmed(false);},[c.stop,c.setInputGuard]);
useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
const focusAfterArm=useRef(false);
useEffect(()=>{
if(open||!focusAfterArm.current)return;
focusAfterArm.current=false;
// Window restores its opener on close. Transfer input after that cleanup,
// once only, without taking focus back from another window or dialog.
const frame=requestAnimationFrame(()=>{if(active&&!document.hidden&&document.hasFocus()&&!document.querySelector('[role=dialog],[role=listbox]'))stage.current?.focus({preventScroll:true});});
return()=>cancelAnimationFrame(frame);
},[open,active]);
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();},[c.stop,c.setInputGuard]);
useEffect(()=>{if(persistableRoverSettings(settings))try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
useEffect(()=>{if(!active)stop();},[active,stop]);
useEffect(()=>{
if(!c.ready||!active||open||editing||!stage.current)return;
const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop});
const scope=stage.current.closest<HTMLElement>('.observation-center')??stage.current;
const binding=bindRoverHoldInput(scope,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop,trace:(event,data)=>roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,event,data)});
input.current=binding;c.setInputGuard(binding.valid);
return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;};
},[c.ready,active,open,editing,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
const showSettings=()=>{setEditing(false);stop();setOpen(true);};
const preparing=c.pending||(c.armed&&!c.ready);
const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null;
const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral';
const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение');
const preparing=c.recovering||c.pending||(c.armed&&!c.ready);
const duty=c.controlMode!=='rpm';
const limits=(c.state.snapshot.devices??[]).filter(d=>d.slot&&d.current_limits);
const currentDescription=limits.length?limits.map(d=>`${d.label}: до ${d.current_limits!.motor_a.toLocaleString('ru-RU',{maximumFractionDigits:2})} А`).join('; ')+'. Выбранный предел ограничивает тягу; настройки VESC сохраняются.':'Предел тяги. Каждый мотор также ограничен своей конфигурацией VESC.';
const speedValid=duty?settings.throttlePercent>=1&&settings.throttlePercent<=100:settings.maxErpm>=300&&settings.maxErpm<=3000;
const observing=observation??roverObservationStatus(c.state,c.connection);
const availability=observing.label??(c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null);
const tone=preparing||availability?'warning':c.ready?'success':c.error||c.state.snapshot.state==='fault'?'warning':'neutral';
const status=c.recovering?'Восстанавливаем связь':preparing?'Подготовка управления':availability??c.error??(labels[c.state.snapshot.state??'']??'Наблюдение');
const running=c.armed||c.pending||c.recovering;
return <>
{createPortal(<><IconButton label={editing?"Завершить редактирование сцены":"Редактировать сцену"} aria-pressed={editing} onClick={()=>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}><Icon name="edit"/></IconButton><IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton></>,header.actionsTarget)}
{createPortal(<StatusBadge variant="indicator" tone={tone} aria-label={status} title={status}/>,header.statusTarget)}
{createPortal(<><IconButton label={running?"Остановить управление":"Включить управление"} aria-pressed={running||open} onClick={running?stop:showSettings}><Icon name={running?'stop':'play'}/></IconButton><IconButton label={editing?"Завершить редактирование сцены":"Редактировать сцену"} aria-pressed={editing} onClick={()=>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}><Icon name="edit"/></IconButton><IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton></>,header.actionsTarget)}
{createPortal(<><StatusBadge variant="indicator" tone={editing?'neutral':tone} pulse={!editing&&(preparing||observing.pulse)} aria-label={editing?'Редактирование сцены':status}/><h3 className="rover-view__title" title={status}>{editing?'Редактирование сцены':status}</h3></>,header.statusTarget)}
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером"
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'} label="Загрузка модели ровера">
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
<div className="rover-view__status"><StatusBadge tone={editing?'neutral':tone}>{editing?'Редактирование сцены':status}</StatusBadge></div>
{c.ready&&!editing&&<div className="rover-view__controls">
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
@@ -51,20 +69,17 @@ export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:stri
</div>
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
</div>}
{!editing&&<div className="rover-view__authority">
{c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>}
</div>}
</div>
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:'dcd006-v020',label:'DCD-006 · полный ровер v020'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
<TextField label="Предел тока каждого мотора, А" type="number" min={.5} max={30} step={.5} value={settings.currentA} onChange={e=>setSettings(v=>({...v,currentA:Number(e.target.value)}))}/>
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={settings.maxErpm} onChange={e=>setSettings(v=>({...v,maxErpm:Number(e.target.value)}))}/>
<Switch label="Моторы остановлены, движение можно начинать" checked={confirmed} onChange={setConfirmed}/>
{availability&&<StatusBadge tone="warning">{availability}</StatusBadge>}
<p>Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. Команда с пульта прекращает удалённое управление.</p>
<Button variant="primary" tone="neutral" disabled={!confirmed||!c.canArm||!(settings.currentA>=.5&&settings.currentA<=30&&settings.maxErpm>=300&&settings.maxErpm<=3000)} loading={c.pending}
onClick={async()=>{const acquired=await c.arm(settings.currentA,settings.maxErpm);if(acquired){setOpen(false);if(document.hasFocus())stage.current?.focus();}}}>Включить управление</Button>
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
{(availability||c.error)&&<StatusBadge tone="warning">{availability||c.error}</StatusBadge>}
<p>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</p>
<Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending}
onClick={async()=>{roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,'settings',{mode:settings.mode,current_a:settings.currentA,speed:duty?settings.throttlePercent:settings.maxErpm,control_mode:duty?'duty':'rpm'});const acquired=await c.arm(settings.currentA,duty?settings.throttlePercent:settings.maxErpm,duty?'duty':'rpm');if(acquired){focusAfterArm.current=true;setOpen(false);}}}>Включить управление</Button>
</div></Window>
<ToastStack onDismiss={c.clearError} items={c.error?[{id:'rover-control-error',tone:'error',title:'Управление остановлено',description:c.error}]:[]}/>
</>;
@@ -20,7 +20,7 @@ export default function RoverScene({vehicleID,editing,onModelState}:{vehicleID:s
{scene.ready&&<PlayCanvasViewer modelUrl="/rover-scene/dcd006-v020.glb?materials-v2" postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} materials={scene.document.materials} assignments={scene.document.assignments} editing={editing} onMaterialPick={pick} onModelState={onModelState} onTextureState={setTextureState}/>}
</LoadingRegion>
{editing&&<>
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface"><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>setPalette(v=>!v)}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton></GlassSurface></div>
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>setPalette(v=>!v)}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton></GlassSurface></div>
<div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></div>
{palette&&<GlassSurface className="rover-material-palette"><div className="rover-material-palette__header"><span>Материалы · выберите в палитре или на модели</span><IconButton label="Скрыть палитру материалов" onClick={()=>setPalette(false)}><Icon name="close"/></IconButton></div><div className="rover-material-palette__items">{Object.entries(scene.document.materials).map(([id,m])=><Button key={id} variant={selected===id?'primary':'secondary'} tone="neutral" aria-pressed={selected===id} title={m.name} onClick={()=>pick(id)}><span className="rover-material-tile"><span aria-hidden="true" className="rover-material-swatch" style={{'--material-color':m.color,'--material-gloss':1-m.roughness} as CSSProperties}/><span>{m.name}</span></span></Button>)}<Button aria-label="Добавить материал" title="Добавить материал" onClick={addMaterial}><span className="rover-material-tile"><Icon name="plus"/><span>Новый материал</span></span></Button></div></GlassSurface>}
</>}
@@ -2,19 +2,11 @@
.rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; }
.rover-view .rover-view__scene { position:absolute; inset:0; }
.rover-view__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); }
.rover-view__status { position:absolute; top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)); left:var(--nodedc-space-3); }
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; }
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; transform:scale(.8); transform-origin:bottom right; }
.rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); }
.rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); }
.rover-key-KeyW { grid-column:2; }.rover-key-KeyA { grid-column:1; grid-row:2; }.rover-key-KeyS { grid-column:2; grid-row:2; }.rover-key-KeyD { grid-column:3; grid-row:2; }
.rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; }
.rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); }
@container (max-width: 380px) {
.rover-view:has(.rover-view__controls) .rover-view__authority { top:calc(var(--observation-overlay-header-space, 0px) + 48px); bottom:auto; }
}
.rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); }
.rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); }
.rover-telemetry { height:100%; overflow:auto; padding:var(--nodedc-space-3); display:flex; flex-wrap:wrap; align-content:start; gap:var(--nodedc-space-4); font-size:var(--nodedc-font-size-sm); }
.rover-telemetry section { flex:1; min-width:170px; }.rover-telemetry section > span { display:block; color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-xs); margin-top:var(--nodedc-space-1); }
.rover-telemetry dl { display:grid; gap:var(--nodedc-space-1); margin-bottom:0; }.rover-telemetry dl > div { display:flex; justify-content:space-between; gap:var(--nodedc-space-3); }
.rover-telemetry dt { color:var(--nodedc-text-secondary); }.rover-telemetry dd { margin:0; font-variant-numeric:tabular-nums; }
.rover-telemetry {height:100%; min-height:0; min-width:0; overflow:hidden; padding:var(--nodedc-space-3);}.rover-telemetry > .nodedc-comparison-table {max-height:100%;}
@@ -0,0 +1,10 @@
.nodedc-icon-button > .rover-dev-label {color:inherit;font-size:var(--nodedc-font-size-xs);font-weight:var(--nodedc-font-weight-medium);}
.rover-logs {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)) var(--nodedc-space-3) var(--nodedc-space-3);}
.rover-logs > p {margin:0;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);overflow-wrap:anywhere;}
.rover-logs__entries {flex:1;min-height:0;overflow:auto;}
.rover-logs__entries pre {white-space:pre-wrap;overflow-wrap:anywhere;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-primary);}
.rover-dev-options {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
.rover-dev-options .nodedc-settings-card__body {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
.rover-logs__actions {display:flex;flex-wrap:wrap;gap:var(--nodedc-space-2);}
@@ -1,13 +1,20 @@
import type {SceneView} from "../../core/simulation/simulationLayout";
import {isOrthographic,screenSpan,type EditorProjection} from "../../core/simulation/editorProjection";
import { sceneClipBounds } from "../../core/simulation/sceneClip";
import { EditorUrbanMapLayer } from "./EditorUrbanMapLayer";
import { urbanExtent, type UrbanMap, type UrbanClassId } from "../../core/simulation/urbanMap";
import { EditorCollisionLayer } from "./EditorCollisionLayer";
import { waypointHit } from "../../core/simulation/waypointHit";
import { PlannerMarkers } from "./PlannerMarkers";
import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality";
import { DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
import { Application, Asset, Color, Entity, FILLMODE_NONE, Mat4, Quat, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
import { Application, Asset, BoundingBox, Color, Entity, FILLMODE_NONE, Mat4, Quat, PROJECTION_ORTHOGRAPHIC, PROJECTION_PERSPECTIVE, RESOLUTION_AUTO, Vec3, WORKBUFFER_UPDATE_ONCE } from "playcanvas";
import { toEditor, toMission, type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, ScreenPoint } from "../../core/simulation/aiPolygon";
import { localScene } from "./localScene";
import { EditorTerrain } from "./EditorTerrain";
import { EditorCamera } from "./EditorCamera";
import { EditorSurfacePicker } from "./EditorSurfacePicker";
import { dragWaypoint, type WaypointAxis } from "../../core/simulation/waypointDrag";
export interface EditorMarker { id: string; base: ScreenPoint; top: ScreenPoint; x: ScreenPoint; y: ScreenPoint; z: ScreenPoint }
@@ -18,10 +25,22 @@ export class AiEditorRuntime {
private scan: Entity;
private asset: Asset | null = null;
private controls: EditorCamera;
private surfacePicker: EditorSurfacePicker;
private collisionVisible = false;
private annotations: PlannerMarkers;
private preferences = DEFAULT_PLANNER_PREFERENCES;
private selected: string|null = null;
private terrain = new EditorTerrain();
private urbanLayer: EditorUrbanMapLayer | null = null;
private urbanBounds:number[][]=[];
private cameraProject: ((q:[number,number,number,number])=>void)|null=null;
private semanticProject: (()=>void)|null = null;
private visualBounds:number[][]=[];
private urbanVisible=false;
private experienceLayer: EditorUrbanMapLayer | null = null;
private experiencePoints: number[][] = [];
private onExperienceProject: (p: ScreenPoint[])=>void = ()=>undefined;
private collisionLayer: EditorCollisionLayer | null = null;
private resize: ResizeObserver;
private abort = new AbortController();
private disposed = false;
@@ -30,6 +49,7 @@ export class AiEditorRuntime {
private points: AiWaypoint[] = [];
private route: number[][] = [];
clip = Infinity;
clipFloor = -Infinity;
height: [number, number] = [0, 1];
constructor(private canvas: HTMLCanvasElement, private cache: EditorCache,
private onProject: (markers: EditorMarker[]) => void,
@@ -44,10 +64,19 @@ export class AiEditorRuntime {
app.setCanvasFillMode(FILLMODE_NONE, 1, 1); app.setCanvasResolution(RESOLUTION_AUTO);
this.camera.addComponent("camera", { nearClip: .05, farClip: 3000, fov: 60, clearColor: new Color(.025,.03,.04) });
this.controls = new EditorCamera(canvas.parentElement!, canvas);
this.surfacePicker = new EditorSurfacePicker(app, this.camera, canvas);
app.root.addChild(this.camera);
app.root.addChild(this.scan);
this.annotations = new PlannerMarkers(app,this.camera,canvas);
this.controls.pick = (x,y) => { const p=this.pick(x,y);return p?toEditor(p):null; };
this.controls.pickSurface = async (x,y) => {
this.syncCamera();
if(this.scan.enabled && this.scan.gsplat) return this.surfacePicker.pick(x,y);
if(!this.collisionVisible)return null;
const from=this.camera.camera!.screenToWorld(x*canvas.clientWidth,y*canvas.clientHeight,.05);
const to=this.camera.camera!.screenToWorld(x*canvas.clientWidth,y*canvas.clientHeight,2000);
return this.terrain.pickSurface([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip,false,this.clipFloor)?.toArray()??null;
};
const transform = new Mat4().set(localScene(cache).transforms.worldFromVisual);
this.scan.setPosition(transform.getTranslation());
this.scan.setRotation(new Quat().setFromMat4(transform));
@@ -64,9 +93,11 @@ export class AiEditorRuntime {
this.controls.update(dt); this.syncCamera();
if (this.annotations.setRotationCenter(this.controls.rotationCenter)) app.renderNextFrame = true;
if (this.annotations.update(dt)) app.renderNextFrame = true;
const matrix = this.camera.getWorldTransform().data.join(",");
const matrix = this.camera.getWorldTransform().data.join(",")+this.controls.camera.projectionMatrix.elements.join(",");
if (matrix !== this.previous || this.dirty) {
this.previous = matrix; this.dirty = false; app.renderNextFrame = true;
this.semanticProject?.();this.cameraProject?.(this.controls.camera.quaternion.toArray());
this.onExperienceProject(this.experiencePoints.map(p=>this.project(...toEditor(p) as [number,number,number])));
this.onRouteProject(this.route.map(p=>this.project(...toEditor(p) as [number,number,number])));
this.onProject(this.points.map((p) => {
const [x,y,z] = toEditor(p.position);
@@ -79,10 +110,9 @@ export class AiEditorRuntime {
}
async load() {
const scene = localScene(this.cache);
await this.terrain.load(scene.collision.meshUrl!, this.abort.signal, scene.transforms.worldFromCollision);
if (scene.collision.available && scene.collision.meshUrl)
await this.terrain.load(scene.collision.meshUrl, this.abort.signal, scene.transforms.worldFromCollision);
if (this.disposed) return;
this.height = [this.terrain.bounds.min.y, this.terrain.bounds.max.y];
if (this.height[1] <= this.height[0]) this.height = [this.height[0]-.5,this.height[1]+.5];
const asset = new Asset("Route editor", "gsplat", { url: scene.visual.streamedSogUrl! });
this.asset = asset;
await new Promise<void>((resolve,reject) => {
@@ -91,20 +121,100 @@ export class AiEditorRuntime {
});
if (this.disposed) { asset.unload(); return; }
this.scan.addComponent("gsplat", { asset, unified: true });
const bounds = new BoundingBox();
bounds.setFromTransformedAabb(this.scan.gsplat!.customAabb!, this.scan.getWorldTransform());
const low=bounds.getMin(),high=bounds.getMax();
this.visualBounds=[...Array(8)].map((_,i)=>[i&1?high.x:low.x,i&2?high.y:low.y,i&4?high.z:low.z]);
const terrain=this.terrain.bounds;
this.height = sceneClipBounds([low.y, high.y], terrain.isEmpty() ? null : [terrain.min.y, terrain.max.y]);
this.scan.gsplat!.setWorkBufferModifier({ glsl: `
uniform float editorClip;
uniform float editorFloor;
void modifySplatCenter(inout vec3 center) {}
void modifySplatRotationScale(vec3 a, vec3 b, inout vec4 rotation, inout vec3 scale) {}
void modifySplatColor(vec3 center, inout vec4 color) {
// Unified work-buffer modifiers receive the calibrated world center.
if (center.y > editorClip) color.a = 0.0;
if (center.y > editorClip || center.y < editorFloor) color.a = 0.0;
}` });
this.setPreferences(this.preferences);
this.controls.sceneCenter = this.terrain.bounds.getCenter(this.controls.sceneCenter);
if (terrain.isEmpty()) this.controls.sceneCenter.set(bounds.center.x,bounds.center.y,bounds.center.z);
else this.controls.sceneCenter = terrain.getCenter(this.controls.sceneCenter);
if (!scene.collision.available) { this.controls.top(this.visualBounds); this.syncCamera(); }
this.setClip(Infinity); this.dirty = true;
}
setExperience(document: UrbanMap, points: number[][], callback: (p: ScreenPoint[])=>void) {
this.experienceLayer?.dispose();this.experienceLayer=new EditorUrbanMapLayer(this.app,this.camera,document);
this.experiencePoints=points;this.onExperienceProject=callback;this.experienceLayer.setClip(this.clip,this.clipFloor);this.dirty=true;
}
showExperience(visible: boolean) {this.experienceLayer?.setVisible(visible);this.dirty=true;}
clearExperience() {this.experienceLayer?.dispose();this.experienceLayer=null;this.experiencePoints=[];this.onExperienceProject=()=>undefined;this.dirty=true;}
setUrbanMap(document: UrbanMap) {
this.urbanBounds=urbanExtent(document);
this.urbanLayer?.dispose();
this.urbanLayer=new EditorUrbanMapLayer(this.app,this.camera,document);this.urbanLayer.setClip(this.clip,this.clipFloor);this.urbanLayer.setVisible(this.urbanVisible);this.dirty=true;
}
snapshotView():SceneView{return {...this.controls.snapshot(),clip:[Number.isFinite(this.clipFloor)?this.clipFloor:null,Number.isFinite(this.clip)?this.clip:null]};}
restoreView(view:SceneView){this.setClip(view.clip[1]??Infinity,view.clip[0]??-Infinity);this.controls.restore(view);this.syncCamera();this.dirty=true;}
watchCamera(callback:((q:[number,number,number,number])=>void)|null) {this.cameraProject=callback;this.dirty=true;}
setProjection(mode:EditorProjection){this.surfacePicker.invalidate();this.controls.setProjection(mode);this.syncCamera();this.dirty=true;}
view(direction:number[]){this.surfacePicker.invalidate();this.controls.view(direction);this.syncCamera();this.dirty=true;}
watchSemantic(callback:(()=>void)|null) { this.semanticProject=callback;this.dirty=true; }
projectSemantic(point:number[]): ScreenPoint {
if(point[2]<this.clipFloor||point[2]>this.clip)return null;
return this.project(...toEditor(point) as [number,number,number]);
}
semanticSegmentParameter(a:number[],b:number[],u:number) {
if(isOrthographic(this.controls.camera))return u;
const depth=(p:number[])=>new Vec3(...toEditor(p)).sub(this.camera.getPosition()).dot(this.camera.forward);
const za=depth(a),zb=depth(b);
return u*za/((1-u)*zb+u*za);
}
/** Explicit planar edit: preserve source elevation, never pretend a ray hit ground. */
moveSemantic(point:number[],x:number,y:number,axis:import("../../core/simulation/semanticVector").SemanticAxis="xy") {
const from=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,.05);
const to=this.camera.camera!.screenToWorld(x*this.canvas.clientWidth,y*this.canvas.clientHeight,2000);
const origin=toMission([from.x,from.y,from.z]),direction=toMission([to.x-from.x,to.y-from.y,to.z-from.z]);
let result:number[]|null;
if(axis.length===1)result=dragWaypoint(origin,direction,point,axis as "x"|"y"|"z");
else {
const normal=[0,1,2].find(k=>!axis.includes("xyz"[k]))!;
if(Math.abs(direction[normal])<1e-8)return null;
const t=(point[normal]-origin[normal])/direction[normal];if(t<0)return null;
result=point.map((v,k)=>k===normal?v:origin[k]+t*direction[k]);
}
if(!result)return null;
return result[2]>=this.clipFloor&&result[2]<=this.clip?result:null;
}
semanticGizmo(point:number[]) {
const depth=new Vec3(...toEditor(point)).sub(this.camera.getPosition()).dot(this.camera.forward);
const length=screenSpan(this.controls.camera,depth)*this.preferences.pivot.pixels*.7/Math.max(1,this.canvas.clientHeight);
return {length,colors:this.preferences.pivot,base:this.projectSemantic(point),
x:this.projectSemantic([point[0]+length,point[1],point[2]]),
y:this.projectSemantic([point[0],point[1]+length,point[2]]),
z:this.projectSemantic([point[0],point[1],point[2]+length])};
}
async pickSemanticSurface(x:number,y:number) {
if(!this.scan.enabled||!this.scan.gsplat)return null;
this.syncCamera();
const hit=await this.surfacePicker.pick(x,y);
if(!hit)return null;
const q=toMission(hit);
return q[2]>=this.clipFloor&&q[2]<=this.clip?q:null;
}
setUrbanClasses(selected:readonly UrbanClassId[]) {this.urbanLayer?.setClasses(selected);this.dirty=true;}
showUrbanMap(visible: boolean) { this.urbanVisible=visible;this.urbanLayer?.setVisible(visible);this.dirty=true; }
setSceneLayers({gaussian,collision}:{gaussian:boolean;collision:boolean}) {
this.surfacePicker.invalidate();this.controls.invalidateSurface();this.collisionVisible=collision;
if (collision && !this.collisionLayer && !this.terrain.bounds.isEmpty()) {
this.collisionLayer = new EditorCollisionLayer(this.app, this.camera, this.terrain.renderData());
this.collisionLayer.setClip(this.clip,this.clipFloor);
}
this.scan.enabled = gaussian;
this.collisionLayer?.setMode(collision ? (gaussian ? "combined" : "collision") : "visual");
this.dirty = true;
}
setRoute(points:number[][]) {this.route=points;this.dirty=true;}
top() {this.controls.top((this.route.length?this.route:this.points.map(p=>p.position)).map(toEditor));this.syncCamera();this.dirty=true;}
top() {const points=(this.urbanVisible&&this.urbanBounds.length?this.urbanBounds:this.route.length?this.route:this.points.map(p=>p.position)).map(toEditor);this.controls.top(points.length?points:this.visualBounds);this.syncCamera();this.dirty=true;}
setPoints(points: AiWaypoint[]) { this.points = points; this.annotations.set(points,this.selected,this.preferences);this.dirty = true; }
setSelected(id: string|null) {this.selected=id;this.annotations.set(this.points,id,this.preferences);this.dirty=true;}
setPreferences(preferences: PlannerPreferences) {
@@ -118,10 +228,14 @@ export class AiEditorRuntime {
}
this.app.resizeCanvas(this.canvas.clientWidth,this.canvas.clientHeight);this.dirty=true;
}
setClip(height: number) {
this.clip = height;
setClip(height: number, floor = -Infinity) {
this.surfacePicker.invalidate();this.controls.invalidateSurface();
this.clip = height; this.clipFloor = floor;
this.collisionLayer?.setClip(height,floor);
this.urbanLayer?.setClip(height,floor);this.experienceLayer?.setClip(height,floor);
if (this.scan.gsplat) {
this.scan.gsplat.setParameter("editorClip", Number.isFinite(height) ? height : 1e9);
this.scan.gsplat.setParameter("editorFloor", Number.isFinite(floor) ? floor : -1e9);
this.scan.gsplat.workBufferUpdate = WORKBUFFER_UPDATE_ONCE;
}
this.dirty = true;
@@ -129,9 +243,13 @@ export class AiEditorRuntime {
setNavigation(enabled: boolean) {
this.controls.setNavigation(enabled);
}
setSemanticSelection(active:boolean) {this.controls.semanticSelection=active;}
setAddMode(add: boolean) { this.controls.setAddMode(add); }
private syncCamera() {
const { position:p, quaternion:q } = this.controls.camera;
const c=this.controls.camera;
this.camera.camera!.projection=isOrthographic(c)?PROJECTION_ORTHOGRAPHIC:PROJECTION_PERSPECTIVE;
if(isOrthographic(c))this.camera.camera!.orthoHeight=c.top;
const { position:p, quaternion:q } = c;
this.camera.setPosition(p.x,p.y,p.z); this.camera.setRotation(q.x,q.y,q.z,q.w);
}
home() {
@@ -142,7 +260,7 @@ export class AiEditorRuntime {
const width = this.canvas.clientWidth, height = this.canvas.clientHeight;
const from = this.camera.camera!.screenToWorld(x*width,y*height,.05);
const to = this.camera.camera!.screenToWorld(x*width,y*height,2000);
const hit = this.terrain.pick([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip);
const hit = this.terrain.pick([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],this.clip,this.clipFloor);
return hit ? toMission(hit.toArray()) : null;
}
pickWaypoint(x:number,y:number) {
@@ -163,18 +281,21 @@ export class AiEditorRuntime {
const hit = dragWaypoint([from.x,from.y,from.z],[to.x-from.x,to.y-from.y,to.z-from.z],p,axis);
if (!hit) return null;
if (axis !== "xz") return toMission(hit);
const ground = this.terrain.ground(hit[0],hit[2],p[1],this.clip);
const ground = this.terrain.ground(hit[0],hit[2],p[1],this.clip,this.clipFloor);
return ground ? toMission(ground.toArray()) : null;
}
private project(x:number,y:number,z:number): ScreenPoint {
const point = this.camera.camera!.worldToScreen(new Vec3(x,y,z));
return point.z > 0 ? [point.x/this.canvas.clientWidth,point.y/this.canvas.clientHeight] : null;
return new Vec3(x,y,z).sub(this.camera.getPosition()).dot(this.camera.forward) > 0 ? [point.x/this.canvas.clientWidth,point.y/this.canvas.clientHeight] : null;
}
dispose() {
this.disposed = true;
this.controls.dispose();
this.surfacePicker.dispose();
this.abort.abort(); this.resize.disconnect(); this.terrain.dispose();
this.annotations.dispose();
this.collisionLayer?.dispose();
this.urbanLayer?.dispose();this.clearExperience();
this.asset?.unload(); this.app.destroy(); this.canvas.width=1; this.canvas.height=1;
}
}
@@ -1,3 +1,11 @@
import {getSimulationLayout,readSceneView,writeSceneView,useSimulationLayout} from "./useSimulationLayout";
import {PlannerCameraTools} from "./PlannerCameraTools";
import { heightSlice } from "../../core/heightSlice";
import { InfrastructureAnalysis } from "./InfrastructureAnalysis";
import { PlannerLegend } from "./PlannerLegend";
import { SemanticEditor } from "./SemanticEditor";
import { PlannerExperience } from "./PlannerExperience";
import { loadUrbanMap, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
import type { PreparedRoute } from "../../core/simulation/routePreparation";
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
import { editWaypoints, waypointEditing, waypointShortcut } from "../../core/simulation/waypointEditing";
@@ -5,7 +13,7 @@ import { SimulationViewTools } from "./SimulationViewTools";
import { usePlannerPreferences } from "./usePlannerPreferences";
import { useEffect, useReducer, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Button, Icon, IconButton, LoadingRegion, RangeControl, SegmentedControl, StatusBadge } from "@nodedc/ui-react";
import { Button, FieldFrame, Icon, IconButton, LoadingRegion, RangeControl, Select, SegmentedControl, SegmentedGroup, SegmentedButton, StatusBadge } from "@nodedc/ui-react";
import { type EditorCache } from "../../core/simulation/aiEditor";
import type { AiWaypoint, AiWorld } from "../../core/simulation/aiPolygon";
import { AiEditorRuntime, type EditorMarker } from "./AiEditorRuntime";
@@ -14,10 +22,14 @@ import { useLocalScene } from "./useLocalScene";
import { useSimulationFullscreen } from "./useSimulationFullscreen";
export interface LocalDraft { cache: EditorCache; points: AiWaypoint[]; id: string; sequence: number }
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, busy=false, preparedRoute=null }: {
export type LocationMode = "view" | "semantic" | "planning";
export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, headerActions, routeActions, sceneMode, onSceneMode, busy=false, preparedRoute=null }: {
world: AiWorld; initialPoints: AiWaypoint[]; onDraft: (draft: LocalDraft | null) => void;
actionsHost: HTMLElement | null; headerActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
actionsHost: HTMLElement | null; headerActions: React.ReactNode;
routeActionsHost: HTMLElement | null; routeActions: React.ReactNode; busy?: boolean; preparedRoute?:PreparedRoute|null;
sceneMode:LocationMode; onSceneMode:(mode:LocationMode)=>void;
}) {
const [semanticHeader,setSemanticHeader]=useState<HTMLSpanElement|null>(null);
const markerSvg=useRef<SVGSVGElement>(null);
const host = useRef<HTMLDivElement>(null), canvas = useRef<HTMLCanvasElement>(null);
const viewport = useRef<HTMLDivElement>(null), loadedPoints = useRef(initialPoints);
@@ -30,33 +42,62 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
const {points,selected,sequence} = editing;
const press=useRef<{id:number;x:number;y:number}|null>(null);
const [routeProjection,setRouteProjection]=useState<ScreenPoint[]>([]);
const [viewMode,setViewMode]=useState<"3d"|"top">("3d");
const [layout,updateLayout]=useSimulationLayout();
const sceneLayers=layout.sceneLayers,setSceneLayers=(sceneLayers:typeof layout.sceneLayers)=>updateLayout({sceneLayers});
const [urbanMap,setUrbanMap]=useState<UrbanMap|null>(null);
const semantic=sceneMode==="semantic", planning=sceneMode==="planning";
const urbanVisible=layout.infrastructure,setUrbanVisible=(infrastructure:boolean)=>updateLayout({infrastructure});
const urbanClasses=layout.urbanLayers,setUrbanClasses=(urbanLayers:UrbanClassId[])=>updateLayout({urbanLayers});
const [memoryVisible,setMemoryVisible]=useState(false);
const [urbanError,setUrbanError]=useState<string|null>(null);
const [markers, setMarkers] = useState<EditorMarker[]>([]);
const [mode,setMode] = useState<"view" | "add">("view");
const [clip,setClip] = useState(Infinity);
const [clip,setClip] = useState<[number,number]|null>(null);
const draftId = useRef(crypto.randomUUID().replaceAll("-",""));
const drag = useRef<{ point: AiWaypoint; axis: WaypointAxis; offset: number[] } | null>(null);
const callback = useRef(onDraft); callback.current = onDraft;
useEffect(() => {
if (cache?.status !== "ready" || !canvas.current) return;
let active = true;
setReady(false); setError(null); setClip(Infinity);
let active = true, loaded=false;
const sceneKey=cache.world.sha256!,remember=()=>{if(loaded&&runtime.current)writeSceneView(sceneKey,runtime.current.snapshotView());};
const timer=window.setInterval(remember,1500);window.addEventListener("pagehide",remember);
const abort=new AbortController();
setUrbanMap(null);setUrbanError(null);
setReady(false); setError(null); setClip(null);
let view: AiEditorRuntime;
try { view = new AiEditorRuntime(canvas.current,cache,setMarkers,setRouteProjection); }
catch (e) { setError((e as Error).message); return; }
catch (e) { clearInterval(timer);window.removeEventListener("pagehide",remember);setError((e as Error).message); return; }
runtime.current = view;
view.setPreferences(preferences);view.setPoints(initialPoints); view.home();
void view.load().then(() => { if (active) setReady(true); }).catch((e: Error) => { if (active) setError(e.message); });
return () => { active=false; runtime.current=null; view.dispose(); callback.current(null); };
void view.load().then(() => { if (active) {
const remembered=readSceneView(sceneKey),settings=getSimulationLayout();
if(remembered){view.restoreView(remembered);setClip([remembered.clip[0]??view.height[0],remembered.clip[1]??view.height[1]]);}
view.setProjection(settings.projection);view.setSceneLayers(settings.sceneLayers);
loaded=true;setReady(true);
void loadUrbanMap(cache.world.world_id,cache.world.sha256!,abort.signal).then(map=>{
if(active && map){view.setUrbanMap(map);setUrbanMap(map);}
}).catch((e:Error)=>{if(active)setUrbanError(e.message);});
} }).catch((e: Error) => { if (active) setError(e.message); });
return () => { remember();clearInterval(timer);window.removeEventListener("pagehide",remember);active=false; abort.abort(); runtime.current=null; view.dispose(); callback.current(null); };
}, [cache?.key,cache?.status,retry]);
useEffect(() => {
runtime.current?.setPoints(points);
runtime.current?.setPoints(planning?points:[]);
if (cache?.status === "ready" && ready) callback.current({ cache,points,id:draftId.current,sequence });
}, [points,cache,ready,sequence]);
}, [points,cache,ready,sequence,planning]);
useEffect(()=>{
runtime.current?.setRoute(preparedRoute?.preview_xyz??[]);
if(preparedRoute && ready){runtime.current?.top();setViewMode("top");}
},[preparedRoute?.sha256,ready]);
if(!semantic&&urbanMap){runtime.current?.setUrbanMap(urbanMap);runtime.current?.setUrbanClasses(urbanClasses);runtime.current?.showUrbanMap(urbanVisible);}
},[semantic,urbanMap,urbanVisible,urbanClasses]);
useEffect(()=>{
runtime.current?.setRoute(planning?preparedRoute?.preview_xyz??[]:[]);
},[preparedRoute?.sha256,ready,planning]);
useEffect(()=>{
setMode("view");press.current=null;runtime.current?.setAddMode(false);
if(drag.current){edit({type:"cancel"});drag.current=null;runtime.current?.setNavigation(!busy);}
},[sceneMode,ready]);
// SemanticEditor owns both the edited map and its layer mask in semantic mode.
useEffect(()=>{if(!semantic)runtime.current?.setUrbanClasses(urbanClasses);},[semantic,urbanClasses,urbanMap,ready]);
useEffect(()=>{if(ready)try{runtime.current?.setSceneLayers(sceneLayers);}catch(e){setError((e as Error).message);}},[sceneLayers,ready]);
useEffect(()=>{runtime.current?.setPreferences(preferences);},[preferences,ready]);
useEffect(()=>{runtime.current?.setSelected(selected);},[selected,ready]);
useEffect(()=>{runtime.current?.setNavigation(!busy);},[busy,ready]);
@@ -80,33 +121,60 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
const bytes = progress.reduce((n,f)=>n+f.uploaded_bytes,0), total = progress.reduce((n,f)=>n+f.byte_length,0);
const message = cache?.status === "uploading" ? `Копируем сцену на диск · ${Math.round(bytes/Math.max(1,total)*100)}%`
: cache?.status === "ready" ? "Открываем локальную сцену" : "Готовим локальную копию сцены";
const modeLabels={view:"Просмотр",semantic:"Семантика",planning:"Планирование миссии"};
const infrastructure=semantic?<InfrastructureAnalysis worldId={world.world_id} worldSha={world.sha256!} busy={busy} hasMap={!!urbanMap}
onMap={map=>{setUrbanMap(map);runtime.current?.setUrbanMap(map);runtime.current?.showUrbanMap(true);setUrbanError(null);}}/>:null;
const header=<>{planning?<FieldFrame label="Выбор задания" labelPlacement="below" className="ai-polygon__task-field">{headerActions}</FieldFrame>:null}
<FieldFrame label="Режим" labelPlacement="below" className="ai-polygon__mode-field">
<Select label="Режим" value={sceneMode} onChange={onSceneMode} disabled={busy}
options={([{value:"view",label:modeLabels.view},{value:"semantic",label:modeLabels.semantic},{value:"planning",label:modeLabels.planning}] as const).map(o=>({...o}))}/>
</FieldFrame>{infrastructure}{semantic?<span className="ai-polygon__semantic-actions" ref={setSemanticHeader}/>:null}{planning?routeActions:null}</>;
return <div className="ai-polygon__stage" ref={host}>
{expanded ? <div className="ai-polygon__actions">{headerActions}</div> : actionsHost ? createPortal(headerActions,actionsHost) : null}
{expanded ? <>
<div className="ai-polygon__actions ai-polygon__planner-actions">{header}</div>
</> : <>
{actionsHost ? createPortal(header,actionsHost) : null}
</>}
<div className="ai-polygon__telemetry-row ai-polygon__telemetry-row--local">
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? "Планирование на этом компьютере" : message}</StatusBadge>
<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p></div>
<StatusBadge tone={ready ? "success" : "neutral"}>{ready ? modeLabels[sceneMode] : message}</StatusBadge>
{planning?<p>{preparedRoute?`${preparedRoute.length_m.toFixed(1)} м · маршрут — ориентир, препятствия оцениваются при движении`:`${points.length} точек · первая — старт, последняя — финиш`}</p>:null}
{!semantic && urbanVisible && urbanMap ? <p>Инфраструктура · {urbanMap.coverage.kind === "objects-only" ? `${urbanMap.schema_version === "missioncore.urban-map/v3" ? "по скану" : urbanMap.analysis?.scope === "whole-scene" ? `обследовано ${urbanMap.analysis.tiles_total} участков · данные в ${urbanMap.analysis.tiles_mapped}` : "участок"} · ${urbanMap.features.length} объектов · распознано автоматически` : `${(urbanMap.coverage.accepted_cells * urbanMap.coverage.cell_m ** 2).toFixed(0)} м² · неполное покрытие`}</p> : null}
</div>
<div className="ai-polygon__viewer">
<div ref={viewport} className="ai-polygon__viewport ai-local-editor" onContextMenu={(e)=>e.preventDefault()}
onKeyDown={(e)=>{
if(!planning)return;
const editable=!!(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"],.nodedc-workspace-window');
const action=waypointShortcut(e,editable);
if(!busy && ready && !drag.current && action){e.preventDefault();edit({type:action});setError(null);}
}}>
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport} planning>
<SimulationViewTools expanded={expanded} toggle={toggle} boundsRef={viewport} planning routeEditing={planning} semantic={semantic}>
{ready?<div className="ai-local-editor__tools nodedc-scene-controls" inert={busy}>
{points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
<div className="ai-local-editor__tool-row">
{runtime.current&&viewport.current?<PlannerCameraTools runtime={runtime.current} viewport={viewport.current} semantic={semantic} disabled={busy}/>:null} {planning?<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>:null}
{planning&&points.some(p=>p.id===selected)?<IconButton label="Удалить точку" onClick={()=>{
edit({type:"delete"});canvas.current?.focus({preventScroll:true});
}}><Icon name="trash"/></IconButton>:null}
{preparedRoute?<SegmentedControl label="Ракурс маршрута" value={viewMode}
items={[{value:"3d",label:"3D"},{value:"top",label:"Вид сверху"}]}
onChange={v=>{setViewMode(v);if(v==="top")runtime.current?.top();else runtime.current?.home();}}/>:null}
<SegmentedControl label="Инструмент маршрута" value={mode} onChange={(v)=>{setMode(v);runtime.current?.setAddMode(v==="add");}}
items={[{value:"view",label:"Обзор"},{value:"add",label:"Waypoint по клику"}]}/>
</div>
<SegmentedGroup label="Слои сцены" className="ai-local-editor__layers">
{!semantic&&urbanMap?<SegmentedButton title={urbanError??"Карта дорожной инфраструктуры"}
active={urbanVisible} aria-pressed={urbanVisible}
onClick={()=>{const visible=!urbanVisible;setUrbanVisible(visible);runtime.current?.showUrbanMap(visible);}}>Инфраструктура</SegmentedButton>:null}
{(["gaussian","collision"] as const).map(key=><SegmentedButton key={key} active={sceneLayers[key]} aria-pressed={sceneLayers[key]}
onClick={()=>{try {const next={...sceneLayers,[key]:!sceneLayers[key]};runtime.current?.setSceneLayers(next);setSceneLayers(next);setError(null);}
catch(e){setError(e instanceof Error?e.message:"Не удалось показать слой коллизий.");}}}>{key==="gaussian"?"Gaussian":"Коллизии"}</SegmentedButton>)}
{runtime.current && viewport.current ? <PlannerExperience worldId={world.world_id} worldSha={world.sha256!}
runtime={runtime.current} viewport={viewport.current} onVisibilityChange={setMemoryVisible}/> : null}
</SegmentedGroup>
{urbanMap&&urbanMap.schema_version!=="missioncore.urban-map/v1"&&runtime.current&&viewport.current?<SemanticEditor key={world.sha256} worldId={world.world_id} worldSha={world.sha256!}
runtime={runtime.current} viewport={viewport.current} active={semantic} busy={busy} source={urbanMap} headerHost={semanticHeader}/>:null}
{semantic&&!urbanMap?<StatusBadge tone="neutral">Рассчитайте инфраструктуру для редактирования</StatusBadge>:null}
</div>:null}
</SimulationViewTools>
<div className="ai-local-editor__surface"
onPointerDownCapture={(e)=>{
if(e.target!==canvas.current || e.button!==0 || busy || !ready)return;
if(!planning || e.target!==canvas.current || e.button!==0 || busy || !ready)return;
const id=runtime.current?.pickWaypoint(...position(e) as [number,number]);
if(!id)return;
e.preventDefault();e.stopPropagation();press.current=null;
@@ -117,14 +185,14 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
drag.current={point:points.find(p=>p.id===id)!,axis:"xz",offset:base.map((v,i)=>v-position(e)[i])};
runtime.current?.setNavigation(false);markerSvg.current!.setPointerCapture(e.pointerId);
}}
onPointerDown={(e)=>{if(e.target===canvas.current&&e.button===0)press.current={id:e.pointerId,x:e.clientX,y:e.clientY};}}
onPointerDown={(e)=>{if(planning&&e.target===canvas.current&&e.button===0)press.current={id:e.pointerId,x:e.clientX,y:e.clientY};}}
onPointerCancel={()=>{press.current=null;}}
onPointerUp={(e)=>{
const start=press.current;press.current=null;
if(!start||start.id!==e.pointerId||busy||!ready||Math.hypot(e.clientX-start.x,e.clientY-start.y)>4)return;
if(!planning||!start||start.id!==e.pointerId||busy||!ready||Math.hypot(e.clientX-start.x,e.clientY-start.y)>4)return;
if(mode==="add")add(...position(e) as [number,number]);else edit({type:"select",id:null});
}}><canvas ref={canvas} aria-label="Локальная Gaussian-сцена для маршрута" />
<svg ref={markerSvg} className={`ai-local-editor__markers ${mode === "add" ? "is-adding" : ""}`} viewBox="0 0 1280 720" preserveAspectRatio="none"
<svg ref={markerSvg} style={!planning?{display:"none"}:undefined} className={`ai-local-editor__markers ${mode === "add" ? "is-adding" : ""}`} viewBox="0 0 1280 720" preserveAspectRatio="none"
onPointerMove={(e)=>{
if (!drag.current) return;
const d=drag.current, [x,y]=position(e);
@@ -155,11 +223,13 @@ export function AiLocalPlanner({ world, initialPoints, onDraft, actionsHost, hea
<text x={m[axis]![0]*1280+16} y={m[axis]![1]*720-12}>{axis.toUpperCase()}</text></g>:null):null}
</g>:null)}
</svg></div>
{!ready && !error ? <div className="ai-polygon__preview-error"><LoadingRegion loading label={message} /></div>:null}
{!semantic?<PlannerLegend map={urbanVisible?urbanMap:null} memory={memoryVisible}
selected={urbanClasses} onChange={setUrbanClasses} disabled={busy}/>:null}
{!ready && !error ? <LoadingRegion className="ai-local-editor__loading" loading label={message} />:null}
{ready ? <><div className="ai-route__height"><RangeControl orientation="vertical" limitSide="right" label="Срез"
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={Number.isFinite(clip)?clip:runtime.current!.height[1]}
min={runtime.current!.height[0]} max={runtime.current!.height[1]} step="any" value={clip??runtime.current!.height}
formatValue={(v)=>`${v.toFixed(1)} м`} formatLimit={(v)=>v.toFixed(1)}
onChange={(v)=>{const next=v>=runtime.current!.height[1]?Infinity:v;setClip(next);runtime.current!.setClip(next);}}/></div>
onChange={(v)=>{const next=heightSlice(v,runtime.current!.height);setClip(v);runtime.current!.setClip(next.ceiling??Infinity,next.floor??-Infinity);}}/></div>
{error?<div className="ai-route__tools"><p role="alert">{error}</p></div>:null}</>:null}
{error && !ready ? <div className="ai-polygon__preview-error"><p role="alert">{error}</p><Button onClick={()=>setRetry(retry+1)}>Повторить загрузку</Button></div>:null}
</div>
@@ -0,0 +1,74 @@
import { useState } from "react";
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
import { Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon";
export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused, onOpen, onPlan, canPlan, onChanged}: {
worlds: AiWorld[]; removedWorlds: AiWorld[]; activeWorldId?: string; paused: boolean;
onOpen: (world: AiWorld) => void; onPlan: (world: AiWorld) => void; canPlan: boolean; onChanged: () => Promise<void>;
}) {
const queue=useInfrastructureQueue();
const [editing, setEditing] = useState<AiWorld | null>(null);
const [name, setName] = useState("");
const [confirming, setConfirming] = useState(false);
const [showRemoved, setShowRemoved] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const update = async (world: AiWorld, changes: {display_name?:string;removed?:boolean}) => {
if (busy) return;
setBusy(world.world_id); setError(null);
try {
await updateAiWorld(world.world_id, changes);
await onChanged();
setConfirming(false); setEditing(null);
} catch (caught) {
setError(caught instanceof Error ? caught.message : "Не удалось сохранить изменения.");
} finally { setBusy(null); }
};
return <>
<ResourceList>{worlds.map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);return <li key={world.world_id}>
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
status={activeWorldId === world.world_id ? <StatusBadge tone="neutral">
{paused ? "На паузе" : "Сцена открыта"}</StatusBadge> : queued ? <StatusBadge tone={queue.unavailable?"neutral":"warning"}>
{queue.unavailable?"Нет обновлений очереди":queued.cancel_requested?"Отмена расчёта":queued.status==="queued"?`В очереди · №${queued.queue?.position??"—"}`:queued.status==="running"?"Расчёт инфраструктуры":"Освобождение Worker"}</StatusBadge> : undefined}
actions={<>
<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
onClick={() => onOpen(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>
{canPlan&&world.status!=="uploading"&&world.settings.prepared?<IconButton label={`Подготовить маршрут · ${world.name}`}
onClick={() => onPlan(world)}><Icon name="plan"/></IconButton>:null}
<IconButton label={`Настройки ${world.name}`} onClick={() => {
setEditing(world); setName(world.name); setConfirming(false); setError(null);
}}><Icon name="settings"/></IconButton>
</>}/>
</li>;})}</ResourceList>
{removedWorlds.length ? <>
<Button aria-expanded={showRemoved} onClick={() => setShowRemoved(!showRemoved)}>
Удалённые локации · {removedWorlds.length}</Button>
{showRemoved ? <ResourceList>{removedWorlds.map(world => <li key={world.world_id}>
<ResourceRow title={world.name} icon={<Icon name="globe"/>} actions={
<Button disabled={busy !== null} loading={busy === world.world_id}
onClick={() => void update(world, {removed:false})}>Восстановить</Button>}/>
</li>)}</ResourceList> : null}
</> : null}
<Window open={!!editing && !confirming} title="Настройки локации" size="sm"
onClose={() => {if (!busy) setEditing(null);}}
footer={<WindowFooterActions>
<Button icon={<Icon name="trash"/>} disabled={!!busy || editing?.world_id === activeWorldId}
onClick={() => setConfirming(true)}>Удалить локацию</Button>
<Button variant="primary" loading={!!busy} disabled={!name.trim() || name.trim() === editing?.name}
onClick={() => {if (editing) void update(editing, {display_name:name.trim()});}}>Сохранить</Button>
</WindowFooterActions>}>
<TextField label="Название локации" value={name} maxLength={120} disabled={!!busy}
onChange={event => setName(event.target.value)}/>
{editing?.world_id === activeWorldId ? <p>Удаление станет доступно после завершения симуляции.</p> : null}
</Window>
<ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger
description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся.
Восстановить её можно в списке удалённых локаций.</>}
confirmLabel="Удалить" pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
onConfirm={async () => {if (editing) await update(editing, {removed:true});}}/>
{error ? <ToastStack items={[{id:"location-settings",tone:"error",title:"Не удалось изменить локацию",description:error}]}
onDismiss={() => setError(null)}/> : null}
</>;
}
@@ -126,7 +126,7 @@ export function AiRouteOverlay({ run, onChange, videoReady, visible = true }: {
setClip(height); send({ action: "clip", amount: value, enabled: height != null });
}} />
</div> : null}
{editing ? <div className="ai-route__tools">
{editing ? <div className="ai-route__tools nodedc-viewport-controls">
<SegmentedControl label="Инструмент маршрута" size="dense" value={mode} onChange={setMode}
items={[{ value: "view", label: "Обзор" }, { value: "add", label: "Точка по клику" }]} />
<Button disabled={!ready} onClick={() => send({ action: "add", x: .5, y: .5 })}>Добавить waypoint</Button>
@@ -1,24 +1,31 @@
import type {SceneView} from "../../core/simulation/simulationLayout";
import { DEFAULT_PLANNER_PREFERENCES, panSensitivity } from "../../core/simulation/plannerPreferences";
import { zoomDisplacement } from "../../core/simulation/editorZoom";
import { navigationDepth, orbitCamera, panCamera } from "../../core/simulation/editorNavigation";
import { PerspectiveCamera, Vector3 } from "three";
import {cameraRay,isOrthographic,switchProjection,type EditorProjection,type ProjectionCamera} from "../../core/simulation/editorProjection";
const KEYS = new Set(["KeyW","KeyA","KeyS","KeyD","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","KeyQ","KeyE","ShiftLeft","ShiftRight"]);
/** Input/math only: PlayCanvas remains the sole renderer. */
export class EditorCamera {
readonly camera = new PerspectiveCamera(60, 1, .05, 3000);
camera:ProjectionCamera = new PerspectiveCamera(60, 1, .05, 3000);
private aspect=1;
get projection():EditorProjection {return isOrthographic(this.camera)?"orthographic":"perspective";}
navigation=DEFAULT_PLANNER_PREFERENCES.navigation;
get rotationCenter(){return this.gesture&&!this.gesture.pan?this.gesture.anchor:null;}
get rotationCenter(){return this.gesture&&!this.gesture.pan&&!this.gesture.pending?this.gesture.anchor:null;}
private keys = new Set<string>();
private enabled=true;
private topPoints:number[][]|null=null;
private addMode=false;
private gesture: {id:number;x:number;y:number;anchor:Vector3;depth:number;distance:number;pan:boolean}|null=null;
semanticSelection=false;
private gesture: {id:number;x:number;y:number;nextX:number;nextY:number;anchor:Vector3;depth:number;distance:number;pan:boolean;pending:boolean}|null=null;
private lastAnchor: Vector3|null = null;
private forward = new Vector3();
private right = new Vector3();
private delta = new Vector3();
sceneCenter = new Vector3();
pick: ((x:number,y:number)=>number[]|null)|null = null;
pickSurface: ((x:number,y:number)=>Promise<number[]|null>)|null = null;
constructor(private surface: HTMLElement, private canvas: HTMLCanvasElement) {
surface.addEventListener("wheel",this.zoom,{passive:false});
surface.addEventListener("pointerdown",this.pointerDown);
@@ -34,68 +41,122 @@ export class EditorCamera {
private anchor(x:number,y:number) {
const hit=this.pick?.(x,y);
if(hit)return new Vector3(...hit);
// Empty sky has no surface; retain useful scale relative to the scene.
return this.camera.getWorldDirection(new Vector3())
.multiplyScalar(Math.max(2,this.camera.position.distanceTo(this.sceneCenter))).add(this.camera.position);
// Empty sky: retain useful depth, but keep the pivot on the clicked ray.
const depth=this.lastAnchor?navigationDepth(this.camera,this.lastAnchor):Math.max(2,this.camera.position.distanceTo(this.sceneCenter));
const forward=this.camera.getWorldDirection(new Vector3());
const ray=cameraRay(this.camera,x,y);
return ray.at((depth-ray.origin.clone().sub(this.camera.position).dot(forward))/Math.max(.01,ray.direction.dot(forward)),new Vector3());
}
private pointerDown=(e:PointerEvent)=>{
const editOrbit=this.semanticSelection&&e.ctrlKey&&[0,2].includes(e.button);
// Ctrl-drag may start on a semantic gizmo as well as the underlying canvas.
if(e.target!==this.canvas&&!(editOrbit&&(e.target as Element).closest("[data-semantic-axis],[data-semantic-handle]")))return;
this.canvas.focus({preventScroll:true});
if(!this.enabled || (e.target as Element).closest("[data-waypoint]") || ![0,1,2].includes(e.button))return;
if(e.button===0 && this.addMode)return;
const rect=this.canvas.getBoundingClientRect();
const anchor=this.anchor((e.clientX-rect.left)/rect.width,(e.clientY-rect.top)/rect.height);
this.gesture={id:e.pointerId,x:e.clientX,y:e.clientY,anchor,depth:navigationDepth(this.camera,anchor),distance:this.camera.position.distanceTo(anchor),pan:e.button!==0};
if(e.button===0&&(this.semanticSelection&&!editOrbit||this.addMode&&!editOrbit))return;
if(editOrbit)e.preventDefault();
this.cancelGesture();
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
const anchor=this.anchor(x,y);this.lastAnchor=anchor.clone();
const g=this.gesture={id:e.pointerId,x:e.clientX,y:e.clientY,nextX:e.clientX,nextY:e.clientY,anchor,depth:navigationDepth(this.camera,anchor),distance:this.camera.position.distanceTo(anchor),pan:e.button!==0&&!editOrbit,pending:!!this.pickSurface};
this.surface.setPointerCapture(e.pointerId);
if(this.pickSurface)void this.pickSurface(x,y).catch(()=>null).then(hit=>{
if(this.gesture!==g)return; // Released pointer, new gesture, resize or view change.
if(hit?.length===3&&hit.every(Number.isFinite)){g.anchor.set(...hit as [number,number,number]);this.lastAnchor=g.anchor.clone();}
g.depth=navigationDepth(this.camera,g.anchor);g.distance=this.camera.position.distanceTo(g.anchor);g.pending=false;
this.moveGesture(g.nextX,g.nextY);
});
};
private pointerMove=(e:PointerEvent)=>{
const g=this.gesture;if(!g||g.id!==e.pointerId||!this.enabled)return;
this.topPoints=null;
const dx=e.clientX-g.x,dy=e.clientY-g.y;g.x=e.clientX;g.y=e.clientY;
if(g.pan)panCamera(this.camera,g.depth,dx*panSensitivity(g.distance,this.navigation),dy*panSensitivity(g.distance,this.navigation),this.canvas.clientHeight);
else orbitCamera(this.camera,g.anchor,dx,dy,this.canvas.clientHeight);
g.nextX=e.clientX;g.nextY=e.clientY;
if(!g.pending)this.moveGesture(e.clientX,e.clientY);
};
private moveGesture(x:number,y:number){
const g=this.gesture;if(!g)return;
const dx=x-g.x,dy=y-g.y;g.x=x;g.y=y;
if(!dx&&!dy)return;
this.topPoints=null;
if(g.pan){const before=this.camera.position.clone();panCamera(this.camera,g.depth,dx*panSensitivity(g.distance,this.navigation),dy*panSensitivity(g.distance,this.navigation),this.canvas.clientHeight);this.lastAnchor?.add(this.camera.position.clone().sub(before));}
else orbitCamera(this.camera,g.anchor,dx,dy,this.canvas.clientHeight);
}
private pointerEnd=(e:PointerEvent)=>{
if(this.gesture?.id!==e.pointerId)return;
this.gesture=null;
if(this.surface.hasPointerCapture(e.pointerId))this.surface.releasePointerCapture(e.pointerId);
this.cancelGesture();
};
private zoom=(e:WheelEvent)=>{
if(!this.enabled)return;
if(!this.enabled||e.target!==this.canvas)return;
this.cancelGesture();
this.topPoints=null;
e.preventDefault();this.canvas.focus({preventScroll:true});
const rect=this.canvas.getBoundingClientRect(),x=(e.clientX-rect.left)/rect.width,y=(e.clientY-rect.top)/rect.height;
const ray=new Vector3(x*2-1,1-y*2,.5).unproject(this.camera).sub(this.camera.position).normalize();
const depth=this.camera.position.distanceTo(this.anchor(x,y));
const anchor=this.anchor(x,y),ray=cameraRay(this.camera,x,y).direction;
const depth=this.camera.position.distanceTo(anchor);
if(this.semanticSelection&&!e.ctrlKey&&!e.metaKey) {
const before=this.camera.position.clone();panCamera(this.camera,navigationDepth(this.camera,anchor),e.deltaX,e.deltaY,this.canvas.clientHeight);
this.lastAnchor=anchor.add(this.camera.position.clone().sub(before));
this.camera.updateMatrixWorld();return;
}
const delta=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?rect.height:1);
this.camera.position.addScaledVector(ray,zoomDisplacement(depth,delta*this.navigation.zoom));this.camera.updateMatrixWorld();
if(isOrthographic(this.camera)) {
const factor=Math.exp(Math.max(-.8,Math.min(.8,delta*this.navigation.zoom*.002)));
const next=Math.max(.05,Math.min(5000,this.camera.top*factor)),ratio=next/this.camera.top;
const offset=anchor.clone().sub(this.camera.position);offset.addScaledVector(this.camera.getWorldDirection(new Vector3()),-navigationDepth(this.camera,anchor));
this.camera.position.addScaledVector(offset,1-ratio);
this.camera.top=next;this.camera.bottom=-next;this.camera.left=-next*this.aspect;this.camera.right=next*this.aspect;this.camera.updateProjectionMatrix();
} else this.camera.position.addScaledVector(ray,zoomDisplacement(depth,delta*this.navigation.zoom));
this.lastAnchor=anchor;this.camera.updateMatrixWorld();
};
private keyDown=(e:KeyboardEvent)=>{
if(document.activeElement!==this.canvas || e.ctrlKey || e.metaKey || e.altKey || !KEYS.has(e.code))return;
e.preventDefault();this.keys.add(e.code);
};
private keyUp=(e:KeyboardEvent)=>{this.keys.delete(e.code);};
private clear=()=>{this.keys.clear();this.gesture=null;};
resize(width:number,height:number){this.camera.aspect=width/height;this.camera.updateProjectionMatrix();if(this.topPoints)this.top(this.topPoints);}
private cancelGesture(){const id=this.gesture?.id;this.gesture=null;if(id!==undefined&&this.surface.hasPointerCapture(id))this.surface.releasePointerCapture(id);}
private clear=()=>{this.keys.clear();this.cancelGesture();};
resize(width:number,height:number){this.cancelGesture();this.aspect=width/height;if(isOrthographic(this.camera)){this.camera.left=-this.camera.top*this.aspect;this.camera.right=this.camera.top*this.aspect;}else this.camera.aspect=this.aspect;this.camera.updateProjectionMatrix();if(this.topPoints)this.top(this.topPoints);}
setProjection(mode:EditorProjection){this.clear();this.camera=switchProjection(this.camera,mode,this.aspect,navigationDepth(this.camera,this.lastAnchor??this.sceneCenter));}
view(direction:number[]){
this.clear();this.topPoints=null;
const depth=navigationDepth(this.camera,this.lastAnchor??this.sceneCenter),target=this.camera.position.clone().addScaledVector(this.camera.getWorldDirection(new Vector3()),depth);
const d=new Vector3(...direction).normalize();this.camera.position.copy(target).addScaledVector(d,depth);
this.camera.up.set(0,1,0);if(Math.abs(d.y)>.999)this.camera.up.set(0,0,-Math.sign(d.y));
this.camera.lookAt(target);this.camera.up.set(0,1,0);this.camera.updateMatrixWorld();this.lastAnchor=target;
}
home(point:number[]){
this.clear();this.lastAnchor=null;
this.topPoints=null;
const target=new Vector3(...point);
if(isOrthographic(this.camera)){this.camera.top=6.5;this.camera.bottom=-6.5;this.camera.left=-6.5*this.aspect;this.camera.right=6.5*this.aspect;this.camera.updateProjectionMatrix();}
this.camera.position.copy(target).add(new Vector3(5,6,8));this.camera.lookAt(target);this.camera.updateMatrixWorld();
}
top(points:number[][]){
if(!points.length)return;
this.clear();this.lastAnchor=null;
this.topPoints=points;
const low=[0,1,2].map(i=>Math.min(...points.map(p=>p[i])));
const high=[0,1,2].map(i=>Math.max(...points.map(p=>p[i])));
const target=new Vector3(...low.map((v,i)=>(v+high[i])/2));
const span=Math.max((high[0]-low[0])/this.camera.aspect,high[2]-low[2],10);
const span=Math.max((high[0]-low[0])/this.aspect,high[2]-low[2],10);
const distance=span/(2*Math.tan(Math.PI/6))*1.15+high[1]-low[1];
this.camera.position.copy(target).add(new Vector3(0,distance,0));
if(isOrthographic(this.camera)){this.camera.top=span*.575;this.camera.bottom=-this.camera.top;this.camera.left=-this.camera.top*this.aspect;this.camera.right=this.camera.top*this.aspect;this.camera.updateProjectionMatrix();}
this.lastAnchor=target;this.camera.position.copy(target).add(new Vector3(0,distance,0));
this.camera.up.set(0,0,-1);this.camera.lookAt(target);this.camera.up.set(0,1,0);this.camera.updateMatrixWorld();
}
setAddMode(add:boolean){this.addMode=add;}
snapshot(){return {position:this.camera.position.toArray(),quaternion:this.camera.quaternion.toArray(),anchor:this.lastAnchor?.toArray()??null,projection:this.projection,span:isOrthographic(this.camera)?this.camera.top:null};}
restore(view:SceneView){
this.clear();this.topPoints=null;this.setProjection(view.projection);
this.camera.position.fromArray(view.position);this.camera.quaternion.fromArray(view.quaternion);
this.lastAnchor=view.anchor?new Vector3(...view.anchor):null;
if(isOrthographic(this.camera)&&view.span!==null){this.camera.top=view.span;this.camera.bottom=-view.span;this.camera.left=-view.span*this.aspect;this.camera.right=view.span*this.aspect;}
this.camera.updateProjectionMatrix();this.camera.updateMatrixWorld();
}
setAddMode(add:boolean){this.cancelGesture();this.addMode=add;}
invalidateSurface(){this.cancelGesture();this.lastAnchor=null;}
setNavigation(enabled:boolean){this.enabled=enabled;if(!enabled)this.clear();}
update(dt:number){
if(!this.enabled||!this.keys.size)return;
this.cancelGesture();
this.topPoints=null;
const pressed=(...keys:string[])=>Number(keys.some(k=>this.keys.has(k)));
this.camera.getWorldDirection(this.forward);this.right.crossVectors(this.forward,this.camera.up).normalize();
@@ -0,0 +1,78 @@
import {
Application, BLEND_NONE, BLEND_NORMAL, CULLFACE_NONE, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance,
SEMANTIC_POSITION, ShaderMaterial,
} from "playcanvas";
import type { SimulationViewMode } from "./PlayCanvasRuntime";
export interface CollisionRenderData {
positions: Float32Array;
indices: Uint16Array | Uint32Array;
}
/** Displays the exact calibrated picking mesh; visibility never changes its geometry or BVH. */
export class EditorCollisionLayer {
private entity: Entity;
private material: ShaderMaterial;
private layer = new Layer({ name: "Planning collision surface", clearDepthBuffer: true });
constructor(private app: Application, private camera: Entity, geometry: CollisionRenderData[]) {
// Unified splats occupy the world pass; the mesh overlay must follow that pass.
app.scene.layers.insert(this.layer, app.scene.layers.getTransparentIndex(app.scene.layers.getLayerById(LAYERID_WORLD)!) + 1);
camera.camera!.layers = [...camera.camera!.layers, this.layer.id];
this.entity = new Entity("Planning collision layer", app);
this.material = new ShaderMaterial({
uniqueName: "planning-collision-surface",
attributes: { vertex_position: SEMANTIC_POSITION },
vertexGLSL: `
attribute vec3 vertex_position;
uniform mat4 matrix_model;
uniform mat4 matrix_viewProjection;
varying vec3 surfacePosition;
void main(void) {
vec4 world = matrix_model * vec4(vertex_position, 1.0);
surfacePosition = world.xyz;
gl_Position = matrix_viewProjection * world;
}`,
fragmentGLSL: `
varying vec3 surfacePosition;
uniform float surfaceClip;
uniform float surfaceFloor;
uniform float surfaceOpacity;
void main(void) {
if (surfacePosition.y > surfaceClip || surfacePosition.y < surfaceFloor) discard;
vec3 normal = normalize(cross(dFdx(surfacePosition), dFdy(surfacePosition)));
float shade = 0.42 + 0.58 * abs(dot(normal, normalize(vec3(0.3, 1.0, 0.4))));
gl_FragColor = vec4(vec3(0.2, 0.95, 0.42) * shade, surfaceOpacity);
}`,
});
this.material.cull = CULLFACE_NONE;
const instances = geometry.map(({ positions, indices }) => {
const mesh = new Mesh(app.graphicsDevice);
mesh.setPositions(positions);
mesh.setIndices(indices);
mesh.update();
return new MeshInstance(mesh, this.material, this.entity);
});
this.entity.addComponent("render", { meshInstances: instances, layers: [this.layer.id], castShadows: false, receiveShadows: false });
app.root.addChild(this.entity);
this.setClip(Infinity);
this.setMode("visual");
}
setMode(mode: SimulationViewMode) {
this.entity.enabled = mode !== "visual";
const combined = mode === "combined";
this.material.setParameter("surfaceOpacity", combined ? 0.34 : 1);
this.material.blendType = combined ? BLEND_NORMAL : BLEND_NONE;
this.material.depthWrite = true;
this.material.update();
}
setClip(height: number, floor = -Infinity) {
this.material.setParameter("surfaceFloor", Number.isFinite(floor) ? floor : -1e9);
this.material.setParameter("surfaceClip", Number.isFinite(height) ? height : 1e9);
}
dispose() {
this.camera.camera!.layers = this.camera.camera!.layers.filter(id => id !== this.layer.id);
this.app.scene.layers.remove(this.layer);
this.entity.destroy();
this.material.destroy();
}
}
@@ -0,0 +1,38 @@
import { Application, Entity, LAYERID_WORLD, Picker } from "playcanvas";
/** Visual navigation only. Gaussian depth never becomes a route/collision surface. */
export class EditorSurfacePicker {
private picker: Picker | null = null;
private tail: Promise<void> = Promise.resolve();
private request = 0;
private disposed = false;
constructor(private app: Application, private camera: Entity, private canvas: HTMLCanvasElement) {}
pick(x: number, y: number): Promise<number[] | null> {
const request = ++this.request;
// Keep one GPU readback in flight; superseded clicks never resize its buffer.
const result = this.tail.then(async () => {
if (this.disposed || request !== this.request || x < 0 || x >= 1 || y < 0 || y >= 1) return null;
const world = this.app.scene.layers.getLayerById(LAYERID_WORLD);
if (!world) return null;
const width = Math.max(1, Math.round(this.canvas.clientWidth));
const height = Math.max(1, Math.round(this.canvas.clientHeight));
this.picker ??= new Picker(this.app, width, height, true);
this.picker.resize(width, height);
// Exclude infrastructure, route markers and gizmos from the depth measurement.
this.picker.prepare(this.camera.camera!, this.app.scene, [world]);
const point = await this.picker.getWorldPointAsync(x * width, y * height);
if (this.disposed || request !== this.request || !point) return null;
const xyz = [point.x, point.y, point.z];
return xyz.every(Number.isFinite) ? xyz : null;
});
this.tail = result.then(() => undefined, () => undefined);
return result;
}
invalidate() { this.request++; }
dispose() {
this.disposed = true; this.invalidate();
this.picker?.destroy(); this.picker = null;
}
}
@@ -1,3 +1,4 @@
import type { CollisionRenderData } from "./EditorCollisionLayer";
import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Mesh, Matrix4, Ray, Vector3 } from "three";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
@@ -47,16 +48,26 @@ export class EditorTerrain {
}
this.builder?.dispose(); this.builder = null;
}
pick(origin: number[], direction: number[], clip = Infinity) {
renderData(): CollisionRenderData[] {
return this.geometries.map((geometry) => ({
positions: geometry.getAttribute("position").array as Float32Array,
indices: geometry.index!.array as Uint16Array | Uint32Array,
}));
}
pick(origin: number[], direction: number[], clip = Infinity, floor = -Infinity) {
return this.pickSurface(origin,direction,clip,true,floor);
}
/** Camera navigation may select walls; waypoint admission remains ground-only. */
pickSurface(origin: number[], direction: number[], clip = Infinity, groundOnly = false, floor = -Infinity) {
const ray = new Ray(new Vector3(...origin), new Vector3(...direction).normalize());
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
.filter((hit) => hit.point.y <= clip && hit.point.y >= floor && (!groundOnly || Math.abs(hit.face?.normal.y ?? 0) > .35))
.sort((a, b) => a.distance - b.distance)[0]?.point ?? null;
}
ground(x: number, z: number, near: number, clip = Infinity) {
ground(x: number, z: number, near: number, clip = Infinity, floor = -Infinity) {
const ray = new Ray(new Vector3(x, this.bounds.max.y + 1, z), new Vector3(0, -1, 0));
return this.trees.flatMap((tree) => tree.raycast(ray, DoubleSide))
.filter((hit) => hit.point.y <= clip && Math.abs(hit.face?.normal.y ?? 0) > .35)
.filter((hit) => hit.point.y <= clip && hit.point.y >= floor && Math.abs(hit.face?.normal.y ?? 0) > .35)
.sort((a, b) => Math.abs(a.point.y - near) - Math.abs(b.point.y - near))[0]?.point ?? null;
}
dispose() { this.disposed = true; this.draco.dispose(); this.builder?.dispose(); this.builder = null; this.geometries.forEach((g) => g.dispose()); this.trees = []; }
@@ -0,0 +1,58 @@
import { Application, BLEND_NORMAL, CULLFACE_NONE, Entity, Layer, LAYERID_WORLD, Mesh, MeshInstance, PRIMITIVE_LINES, PRIMITIVE_TRIANGLES, SEMANTIC_COLOR, SEMANTIC_POSITION, ShaderMaterial } from "playcanvas";
import { toEditor } from "../../core/simulation/aiEditor";
import { URBAN_COLORS, urbanPaths, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
import { urbanSurface } from "../../core/simulation/urbanSurface";
/** Read-only observed surfaces and physical contours; never routing or collision input. */
export class EditorUrbanMapLayer {
private entity: Entity;
private meshes: Mesh[] = [];
private groups = new Map<string,Entity>();
private materials: ShaderMaterial[];
private surfaceLayer = new Layer({ name: "Urban pedestrian coverage" });
private layer = new Layer({ name: "Urban infrastructure observations" });
constructor(private app: Application, private camera: Entity, document: UrbanMap) {
const at=app.scene.layers.getTransparentIndex(app.scene.layers.getLayerById(LAYERID_WORLD)!) + 1;
app.scene.layers.insert(this.surfaceLayer,at);app.scene.layers.insert(this.layer,at+2);
camera.camera!.layers = [...camera.camera!.layers, this.surfaceLayer.id, this.layer.id];
this.materials=[false,true].map(surface=>{
const material=new ShaderMaterial({ uniqueName: surface?"urban-ground-coverage":"urban-map-contours", attributes: { vertex_position: SEMANTIC_POSITION, vertex_color: SEMANTIC_COLOR },
vertexGLSL: `attribute vec3 vertex_position; attribute vec4 vertex_color;
uniform mat4 matrix_model; uniform mat4 matrix_viewProjection;
varying vec4 mapColor; varying float mapHeight;
void main(void) { vec4 p=matrix_model*vec4(vertex_position,1.0); mapColor=vertex_color; mapHeight=p.y; gl_Position=matrix_viewProjection*p; }`,
fragmentGLSL: `precision highp float; varying vec4 mapColor; varying float mapHeight; uniform float mapClip; uniform float mapFloor;
void main(void) { if(mapHeight>mapClip || mapHeight<mapFloor) discard; gl_FragColor=mapColor; }` });
material.depthTest=false;material.depthWrite=false;
if(surface){material.blendType=BLEND_NORMAL;material.cull=CULLFACE_NONE;}
return material;
});
this.entity = new Entity("Urban infrastructure",app);
const groups = new Map<string, {positions:number[];colors:number[];surface:boolean}>();
for (const feature of document.features) {
const color = URBAN_COLORS[feature.properties.class]; if (!color) continue;
const surface=urbanSurface(feature),key=feature.properties.class+(surface?":surface":":line");
if (!groups.has(key)) groups.set(key,{positions:[],colors:[],surface:!!surface});
const group=groups.get(key)!;
if(surface){
for(const i of surface.indices){group.positions.push(...toEditor(surface.positions.slice(i*3,i*3+3)));group.colors.push(...color,48);}
}else for (const ring of urbanPaths(feature)) for (let i=1;i<ring.length;i++) {
group.positions.push(...toEditor(ring[i-1]), ...toEditor(ring[i]));
group.colors.push(...color,255,...color,255);
}
}
for (const [key,{positions,colors,surface}] of groups) {
if (!positions.length) continue;
const mesh=new Mesh(app.graphicsDevice);mesh.setPositions(positions);mesh.setColors32(colors);mesh.update(surface?PRIMITIVE_TRIANGLES:PRIMITIVE_LINES);this.meshes.push(mesh);
const entity=new Entity(key,app);entity.addComponent("render",{meshInstances:[new MeshInstance(mesh,this.materials[surface?1:0])],layers:[surface?this.surfaceLayer.id:this.layer.id],castShadows:false,receiveShadows:false});
this.entity.addChild(entity);this.groups.set(key,entity);
}
this.entity.enabled=false; app.root.addChild(this.entity); this.setClip(Infinity);
}
setClasses(selected:readonly UrbanClassId[]) {
for (const [key,entity] of this.groups) entity.enabled=selected.includes(key.split(":")[0] as UrbanClassId);
}
setVisible(visible: boolean) { this.entity.enabled=visible; }
setClip(height: number, floor = -Infinity) { for(const material of this.materials) { material.setParameter("mapClip",Number.isFinite(height)?height:1e9); material.setParameter("mapFloor",Number.isFinite(floor)?floor:-1e9); } }
dispose() { this.camera.camera!.layers=this.camera.camera!.layers.filter(id=>id!==this.layer.id&&id!==this.surfaceLayer.id);this.app.scene.layers.remove(this.layer);this.app.scene.layers.remove(this.surfaceLayer);this.entity.destroy();for(const mesh of this.meshes)mesh.destroy();for(const material of this.materials)material.destroy(); }
}
@@ -0,0 +1,23 @@
import { useState } from "react";
import { Icon, IconButton, LayerStackIndicator, ProgressButton, ToastStack } from "@nodedc/ui-react";
import type { UrbanMap } from "../../core/simulation/urbanMap";
import { analysisProgressLabel, useInfrastructureAnalysis } from "../../core/simulation/infrastructureAnalysis";
export function InfrastructureAnalysis({worldId,worldSha,busy,hasMap,onMap}:{worldId:string;worldSha:string;busy:boolean;hasMap:boolean;onMap:(map:UrbanMap)=>void}) {
const {job,error,clearError,sending,checking,start,cancel}=useInfrastructureAnalysis(worldId,worldSha,onMap);
const [dismissedFailure,setDismissedFailure]=useState<string|null>(null);
const pending=job?.status==="queued"||job?.status==="running";
const phase=sending?(pending?"Отменяем расчёт":"Запускаем расчёт"):checking?"Проверяем состояние":pending?analysisProgressLabel(job):null;
const recalculate=hasMap||job?.status==="ready";
return <>
{!phase&&!busy?<IconButton label={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"} title={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"} onClick={()=>void start(recalculate)}><Icon name="layers"/></IconButton>:null}
{phase?<ProgressButton label={recalculate?"Пересчитать инфраструктуру":"Рассчитать инфраструктуру"}
icon={phase?<LayerStackIndicator/>:<Icon name="layers"/>} disabled={busy}
title={pending?"Прогноз уточняется по выполненным этапам. Ожидание Worker и подготовка исходного проекта считаются отдельно.":undefined}
progress={phase?{label:phase,value:pending&&!job.progress?.stale?job.progress?.fraction??undefined:undefined}:undefined}
onClick={()=>void start(recalculate)}/>:null}
{pending&&!job.cancel_requested?<IconButton label="Отменить расчёт инфраструктуры" loading={sending}
onClick={()=>void cancel()}><Icon name="stop"/></IconButton>:null}
{error?<ToastStack items={[{id:"infrastructure",tone:"error",title:"Не удалось выполнить расчёт",description:error}]} onDismiss={clearError}/>:null}
{job?.status==="failed"&&job.error&&dismissedFailure!==job.key?<ToastStack items={[{id:job.key,tone:"error",title:"Расчёт не завершён",description:job.error}]} onDismiss={()=>setDismissedFailure(job.key)}/>:null}
</>;
}
@@ -0,0 +1,22 @@
import {usePlannerPreferences} from "./usePlannerPreferences";
import {useEffect,useState} from "react";
import {Button,Dropdown,Icon,IconButton,NavigationCube} from "@nodedc/ui-react";
import {createPortal} from "react-dom";
import {useSimulationLayout} from "./useSimulationLayout";
import type {AiEditorRuntime} from "./AiEditorRuntime";
export function PlannerCameraTools({runtime,viewport,disabled}:{runtime:AiEditorRuntime;viewport:HTMLElement;semantic:boolean;disabled:boolean}) {
const [preferences]=usePlannerPreferences();
const [layout,updateLayout]=useSimulationLayout();
const projection=layout.projection;
const [quaternion,setQuaternion]=useState<[number,number,number,number]>([0,0,0,1]);
useEffect(()=>{viewport.style.setProperty("--planner-cube-size",`${preferences.cube.size}px`);return()=>{viewport.style.removeProperty("--planner-cube-size");};},[viewport,preferences.cube.size]);
useEffect(()=>{runtime.watchCamera(setQuaternion);return()=>runtime.watchCamera(null);},[runtime]);
useEffect(()=>{runtime.setProjection(projection);},[runtime,projection]);
return <>
<Dropdown placement="bottom-end" width={220} trigger={({toggle,setTriggerRef,open})=><IconButton ref={setTriggerRef}
label={`Проекция: ${projection==="orthographic"?"ортографическая":"перспективная"}`} title="Выбрать проекцию" disabled={disabled} aria-expanded={open} onClick={toggle}><Icon name={projection}/></IconButton>}>
{({close})=><div className="semantic-tools__menu">{([['orthographic','Ортографическая'],['perspective','Перспективная']] as const).map(([mode,label])=><Button key={mode} width="full" variant={projection===mode?"primary":"secondary"} tone="neutral" aria-pressed={projection===mode} onClick={()=>{updateLayout({projection:mode});close();}}>{label}</Button>)}</div>}
</Dropdown>
{createPortal(<div className="ai-local-editor__cube"><NavigationCube quaternion={quaternion} {...preferences.cube} disabled={disabled} onSelect={direction=>runtime.view(direction)}/></div>,viewport)}
</>;
}
@@ -0,0 +1,10 @@
import {ColorField,ControlRow,RangeControl} from "@nodedc/ui-react";
import type {PlannerPreferences} from "../../core/simulation/plannerPreferences";
export function PlannerCubeSettings({value,set}:{value:PlannerPreferences["cube"];set:(key:string,value:string|number)=>void}) {
return <>
<RangeControl label="Размер 3D-куба" min={48} max={160} step={1} value={value.size} onChange={v=>set("size",v)} formatValue={v=>`${v} px`}/>
<RangeControl label="Непрозрачность куба" min={.2} max={1} step={.05} value={value.opacity} onChange={v=>set("opacity",v)} formatValue={v=>`${Math.round(v*100)}%`}/>
<RangeControl label="Прозрачность линий" min={0} max={1} step={.05} value={1-value.edgeOpacity} onChange={v=>set("edgeOpacity",1-v)} formatValue={v=>`${Math.round(v*100)}%`}/>
{([["face","Грани"],["text","Подписи"],["edge","Рёбра"],["hover","Подсветка"],["hoverText","Подписи при наведении"]] as const).map(([key,label])=><ControlRow key={key} label={label}><ColorField label={label} value={value[key]} onChange={v=>set(key,v)}/></ControlRow>)}
</>;
}
@@ -0,0 +1,54 @@
import {useSimulationLayout} from "./useSimulationLayout";
import { useEffect, useState } from "react";
import { Checker, Dropdown, SegmentedButton } from "@nodedc/ui-react";
import { createPortal } from "react-dom";
import { loadExperience, attemptLabel, experienceMap, type SpatialExperience } from "../../core/simulation/spatialExperience";
import type { ScreenPoint } from "../../core/simulation/aiPolygon";
import type { AiEditorRuntime } from "./AiEditorRuntime";
import { URBAN_COLORS } from "../../core/simulation/urbanMap";
export function PlannerExperience({worldId,worldSha,runtime,viewport,onVisibilityChange}: {
worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;onVisibilityChange:(visible:boolean)=>void;
}) {
const [memory,setMemory]=useState<SpatialExperience|null>(null);
const [layout,updateLayout]=useSimulationLayout();
const visible=layout.memory,setVisible=(memory:boolean)=>updateLayout({memory});
const [projected,setProjected]=useState<ScreenPoint[]>([]),[error,setError]=useState<string|null>(null);
useEffect(()=>{
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
const refresh=async()=>{
try {const value=await loadExperience(worldId,worldSha,abort.signal);
if(abort.signal.aborted)return;setMemory(value);setError(null);
if(value)runtime.setExperience(experienceMap(value),value.attempts.map(a=>a.xyz),setProjected);
} catch(e) {if(!abort.signal.aborted)setError((e as Error).message);}
if(!abort.signal.aborted)timer=setTimeout(refresh,5000);
};
void refresh();return ()=>{abort.abort();clearTimeout(timer);runtime.clearExperience();};
},[worldId,worldSha,runtime]);
useEffect(()=>{runtime.showExperience(visible);onVisibilityChange(visible&&!!memory);},[runtime,visible,memory,onVisibilityChange]);
useEffect(()=>()=>onVisibilityChange(false),[onVisibilityChange]);
return <>
<Dropdown placement="bottom-start" width={340} surfaceRole="dialog"
trigger={({open,toggle,setTriggerRef,surfaceId})=><SegmentedButton ref={setTriggerRef} aria-label="Память локации" active={visible||open}
aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Память</SegmentedButton>}>
<div className="ai-polygon__layer-options">
<strong>Память локации</strong>
<p>Сохраняет посещённые места и попытки проезда между заездами. Новый заезд с той же конфигурацией ровера продолжает эту историю.</p>
{error?<p role="alert">{error}</p>:memory?<>
<p>Посещено участков: {memory.visits.length}. Попыток проезда: {memory.attempts.length}, из них позже пройдено: {memory.attempts.filter(a=>a.status==="revisited-successfully").length}.</p>
<Checker label="Показывать на карте" checked={visible} onChange={setVisible}/>
</>:<p>Сохранённых проездов пока нет. Память появится после движения ровера.</p>}
<p>Прежние попытки помогают выбрать другой подход. Возможность проезда всегда проверяется заново по текущим данным.</p>
<p>Показана накопленная память конфигурации ровера из последнего заезда. Для другой версии локации или конфигурации сохраняется отдельная память.</p>
</div>
</Dropdown>
{visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов">
{memory.attempts.map((attempt,i)=>{const p=projected[i];if(!p)return null;
const label=attemptLabel(attempt),color=URBAN_COLORS[attempt.status==="unresolved"?"attempt":"revisited"];
return <g key={attempt.id} role="img" aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
<title>{label}</title><circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
</g>;
})}
</svg>,viewport):null}
</>;
}
@@ -0,0 +1,21 @@
import { GlassSurface, SegmentedControl } from "@nodedc/ui-react";
import { URBAN_COLORS, URBAN_LABELS, availableUrbanClasses, type UrbanClassId, type UrbanMap } from "../../core/simulation/urbanMap";
export function PlannerLegend({map,memory,selected,onChange,disabled=false}: {
map:UrbanMap|null;memory:boolean;selected:readonly UrbanClassId[];
onChange:(selected:UrbanClassId[])=>void;disabled?:boolean;
}) {
const classes=map?availableUrbanClasses(map):[];
if(!classes.length&&!memory)return null;
const swatch=(id:string)=><i className="ai-local-editor__legend-swatch" aria-hidden="true"
style={{background:`rgb(${URBAN_COLORS[id].join(",")})`}}/>;
return <div className="ai-local-editor__legend nodedc-scene-controls" inert={disabled}>
{classes.length?<SegmentedControl label="Слои инфраструктуры" selectionMode="multiple"
className="ai-local-editor__legend-controls" value={selected} onChange={onChange}
items={classes.map(id=>({value:id,label:URBAN_LABELS[id],icon:swatch(id)}))}/>:null}
{memory?<GlassSurface padding="sm" materialRim={false} aria-label="Легенда памяти">
<span className="ai-inference-preview__legend">{[["visited","Проехал"],["attempt","Попытка проезда"],["revisited","Позже проехал"]].map(([id,label])=>
<span key={id}>{swatch(id)}{label}</span>)}</span>
</GlassSurface>:null}
</div>;
}
@@ -1,4 +1,4 @@
import { Application, BLEND_NORMAL, Color, Entity, Layer, StandardMaterial, Vec3 } from "playcanvas";
import { Application, BLEND_NORMAL, Color, Entity, Layer, PROJECTION_ORTHOGRAPHIC, StandardMaterial, Vec3 } from "playcanvas";
import { toEditor } from "../../core/simulation/aiEditor";
import type { AiWaypoint } from "../../core/simulation/aiPolygon";
import { axisWorldLength, DEFAULT_PLANNER_PREFERENCES, type PlannerPreferences } from "../../core/simulation/plannerPreferences";
@@ -69,11 +69,14 @@ export class PlannerMarkers {
if(point)this.centroid.setPosition(point.x,point.y,point.z);
return changed;
}
private pixelLength(depth:number,pixels:number) {
return this.camera.camera!.projection===PROJECTION_ORTHOGRAPHIC?2*this.camera.camera!.orthoHeight*pixels/Math.max(1,this.canvas.clientHeight):axisWorldLength(depth,this.canvas.clientHeight,pixels);
}
update(dt: number) {
this.elapsed+=dt;
if(this.centroid?.enabled) {
const depth=this.centroid.getPosition().clone().sub(this.camera.getPosition()).dot(this.camera.forward);
const size=axisWorldLength(depth,this.canvas.clientHeight,this.preferences.navigation.centroidPixels);
const size=this.pixelLength(depth,this.preferences.navigation.centroidPixels);
this.centroid.setLocalScale(size,size,size);
}
const w=this.preferences.waypoint,p=this.preferences.pivot;
@@ -84,7 +87,7 @@ export class PlannerMarkers {
const position=new Vec3(...toEditor(point.position));this.pivot.setPosition(position);
const depth=position.clone().sub(this.camera.getPosition()).dot(this.camera.forward);
this.pivot.enabled=depth>0;
this.axisLength=axisWorldLength(depth,this.canvas.clientHeight,p.pixels);
this.axisLength=this.pixelLength(depth,p.pixels);
const unit=this.axisLength/p.pixels,tip=p.cone*unit,stem=this.axisLength-tip;
for(const {axis,shaft,cone} of this.arrows) {
const v=axis==="x"?new Vec3(1,0,0):axis==="y"?new Vec3(0,1,0):new Vec3(0,0,1);
@@ -1,9 +1,11 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import { ColorField, ControlRow, RangeControl, Select, ToastStack, WorkspaceWindow } from "@nodedc/ui-react";
import type { PlannerPreferences } from "../../core/simulation/plannerPreferences";
import {PlannerCubeSettings} from "./PlannerCubeSettings";
import {PlannerToolbarSettings} from "./PlannerToolbarSettings";
import { usePlannerPreferences } from "./usePlannerPreferences";
export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<HTMLDivElement|null>; onClose: () => void }) {
const [section,setSection] = useState<"pivot"|"waypoint"|"navigation">("pivot");
const [section,setSection] = useState<"pivot"|"waypoint"|"navigation"|"toolbar"|"cube">("pivot");
const [saved,update] = usePlannerPreferences();
const [value,setValue] = useState(saved);
const [rect,setRect] = useState(()=>{
@@ -38,13 +40,13 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
window.removeEventListener("keydown",escape);
};
},[onClose]);
const set = (group: "pivot"|"waypoint"|"navigation", key: string, next: string|number) => {
const set = (group: "pivot"|"waypoint"|"navigation"|"toolbar"|"cube", key: string, next: string|number|boolean) => {
const base=pending.current??value;
const changed={...base,[group]:{...base[group],[key]:next}};
pending.current=changed;setValue(changed);
if(!editing.current)commit();
};
const range = (group: "pivot"|"waypoint"|"navigation", key: string, label: string, min: number, max: number, step: number, unit: string) =>
const range = (group: "pivot"|"waypoint"|"navigation"|"toolbar"|"cube", key: string, label: string, min: number, max: number, step: number, unit: string) =>
<RangeControl key={key} label={label} min={min} max={max} step={step}
value={Number(value[group][key as keyof typeof value[typeof group]])} onChange={(v)=>set(group,key,v)}
formatValue={(v)=>`${Number(v.toFixed(2))} ${unit}`} />;
@@ -59,8 +61,8 @@ export function PlannerSettings({ boundsRef, onClose }: { boundsRef: RefObject<H
if((e.target as Element).matches('input[type="range"], [role="slider"]') && ["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(e.key))editing.current=true;
}}>
<Select label="Раздел настроек планировщика" value={section} onChange={setSection}
options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"}]}/>
{section === "pivot" ? <>
options={[{value:"pivot",label:"Пивот"},{value:"waypoint",label:"Waypoint"},{value:"navigation",label:"Навигация"},{value:"toolbar",label:"Тулбар"},{value:"cube",label:"3D-куб"}]}/>
{section === "cube" ? <PlannerCubeSettings value={value.cube} set={(key,v)=>set("cube",key,v)}/> : section === "toolbar" ? <PlannerToolbarSettings value={value.toolbar} set={(key,v)=>set("toolbar",key,v)}/> : section === "pivot" ? <>
{range("pivot","pixels","Размер осей",50,220,5,"px")}
{range("pivot","diameter","Диаметр стержня",2,16,1,"px")}
{range("pivot","cone","Размер конусов",10,40,1,"px")}
@@ -0,0 +1,16 @@
import {Checker,ColorField,ControlRow,RangeControl,Select} from "@nodedc/ui-react";
import type {PlannerPreferences} from "../../core/simulation/plannerPreferences";
type Settings=PlannerPreferences["toolbar"];
export function PlannerToolbarSettings({value,set}:{value:Settings;set:(key:string,value:string|number|boolean)=>void}) {
const range=(key:keyof Settings,label:string,min:number,max:number,step:number,unit:string)=><RangeControl label={label} value={Number(value[key])} min={min} max={max} step={step} onChange={v=>set(key,v)} formatValue={v=>`${unit==="с"?v/1000:v} ${unit}`}/>;
return <>
<Select label="Положение тулбара" value={value.placement} options={[{value:"left",label:"Слева"},{value:"right",label:"Справа"},{value:"top",label:"Сверху"},{value:"bottom",label:"Снизу"}]} onChange={v=>set("placement",v)}/>
{range("minSize","Минимальный размер",18,42,1,"px")}
{range("maxSize","Максимальный размер",value.minSize,88,1,"px")}
{range("lensCount","Линза",1,13,2,"иконок")}
{range("gap","Расстояние между кнопками",0,24,1,"px")}
<Checker label="Автоскрытие" checked={value.autoHide} onChange={v=>set("autoHide",v)}/>
{value.autoHide?range("hideDelay","Задержка скрытия",0,15000,250,"с"):null}
{([["background","Фон"],["border","Рамка"],["outline","Подсветка"],["accent","Цвет инструментов"]] as const).map(([key,label])=><ControlRow key={key} label={label}><ColorField label={label} value={value[key]} onChange={v=>set(key,v)}/></ControlRow>)}
</>;
}
@@ -0,0 +1,57 @@
import {useEffect,useState} from "react";
import {createPortal} from "react-dom";
import {semanticPaths,semanticMembers,isRigidMarking} from "../../core/simulation/semanticEdits";
import {curveControlScale,curveControlPoint} from "../../core/simulation/semanticCurveControls";
import {editablePaths,knots} from "../../core/simulation/semanticVector";
import {URBAN_COLORS} from "../../core/simulation/urbanMap";
import {useSemanticGestures} from "./useSemanticGestures";
import {semanticAnchor,type SemanticOverlayProps} from "./semanticEditorTypes";
export type {SemanticChoice} from "./semanticEditorTypes";
export function SemanticEditOverlay(props:SemanticOverlayProps) {
const {runtime,viewport,map,original,layers,selected}=props;
const [,redraw]=useState(0);
const {hover,ghostMap,marquee,brush}=useSemanticGestures(props);
useEffect(()=>{runtime.watchSemantic(()=>redraw(n=>n+1));return()=>runtime.watchSemantic(null);},[runtime]);
const rect=viewport.querySelector("canvas")?.getBoundingClientRect();if(!rect)return null;
const project=(v:number[])=>{const q=runtime.projectSemantic(v);return q?[q[0]*rect.width,q[1]*rect.height]:null;};
const line=(path:number[][])=>{const p=path.map(project);return p.map((v,i)=>v?`${i&&p[i-1]?"L":"M"}${v[0]},${v[1]}`:"").join(" ");};
const selectedIds=new Set([...(selected?[selected.feature_id]:[]),...props.selection.map(v=>v.feature_id)]);
const chosen=[...new Set([...selectedIds].flatMap(id=>semanticMembers(map,id)))],highlight=hover?semanticMembers(map,hover):[];
const point=semanticAnchor(props),g=point?runtime.semanticGizmo(point):null,base=point?project(point):null;
const featureColor=(id:string)=>`rgb(${(URBAN_COLORS[id]??URBAN_COLORS.road_boundary).join(",")})`;
const color=featureColor(chosen[0]?.properties.class??layers.at(-1)??"road_boundary");
const visible=map.features.filter(f=>layers.includes(f.properties.class as typeof layers[number])&&f.properties.review_status!=="rejected");
const node=selected&&!selected.object&&chosen[0]&&!isRigidMarking(chosen[0])?knots(chosen[0],selected.path)[selected.index]:null;
const handleScale=node?curveControlScale(knots(chosen[0],selected!.path),selected!.index,chosen[0].geometry.type==="Polygon",project):1;
return createPortal(<svg className="ai-local-editor__markers" width="100%" height="100%" aria-label="Редактор контуров">
{original?.features.filter(f=>f.properties.review_status!=="rejected").flatMap(f=>semanticPaths(f).map((r,i)=><path key={`${f.id}-${i}`} d={line(r)} fill="none" stroke={`rgb(${URBAN_COLORS[f.properties.class]?.join(",")??"255,255,255"})`} strokeWidth={1.5} strokeDasharray="5 5" opacity={.65}/>))}
{visible.map(f=><g key={f.id} data-semantic-feature={f.id}>
{semanticPaths(f).map((r,i)=><g key={i}>
{chosen.includes(f)||highlight.includes(f)?<><path d={line(r)} fill="none" stroke="var(--nodedc-glass-panel-bg)" strokeWidth={6}/><path d={line(r)} fill="none" stroke={highlight.includes(f)?"var(--nodedc-text-primary)":featureColor(f.properties.class)} strokeWidth={3}/></>:null}
</g>)}
{props.editing&&!isRigidMarking(f)&&chosen.includes(f)?editablePaths(f).flatMap((r,i)=>r.slice(0,r.length-Number(f.geometry.type==="Polygon")).map((v,k)=>{const p=project(v);const active=props.selection.some(s=>!s.object&&s.feature_id===f.id&&s.path===i&&s.index===k);return p?<circle key={`${i}-${k}`} data-semantic-vertex={`${f.id}:${i}:${k}`} cx={p[0]} cy={p[1]} r={active?5:3} fill={active?"var(--nodedc-text-primary)":featureColor(f.properties.class)} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={1.5}/>:null;})):null}
</g>)}
{ghostMap?.features.map(f=><path key={f.id} d={semanticPaths(f).map(line).join(" ")} fill={color} fillRule="evenodd" fillOpacity={.4} stroke={color} strokeWidth={2}/>)}
{brush.length?<><path d={line(brush)} fill="none" stroke={color} strokeWidth={2}/>{brush.map((v,i)=>{const p=project(v);return p?<circle key={i} cx={p[0]} cy={p[1]} r={i?3:6} fill={color}/>:null;})}</>:null}
{marquee?<rect x={Math.min(marquee[0],marquee[2])} y={Math.min(marquee[1],marquee[3])} width={Math.abs(marquee[2]-marquee[0])} height={Math.abs(marquee[3]-marquee[1])} fill="var(--nodedc-text-primary)" fillOpacity={.1} stroke="var(--nodedc-text-primary)" strokeDasharray="4 3"/>:null}
{props.editing&&!props.blocked&&base&&g?<g aria-label="Пивот перемещения">
{(["x","y","z"] as const).map(axis=>{const end=g[axis];if(!end)return null;const p=[end[0]*rect.width,end[1]*rect.height],d=Math.hypot(p[0]-base[0],p[1]-base[1]);if(d<12)return null;
const ux=(p[0]-base[0])/d,uy=(p[1]-base[1])/d;
return <g key={axis} data-semantic-axis={axis} style={{pointerEvents:"stroke",cursor:"move"}}>
<title>{`Переместить по ${axis.toUpperCase()}`}</title>
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke="transparent" strokeWidth={18}/>
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke={g.colors[axis]} strokeWidth={3}/>
<path d={`M${p[0]},${p[1]} L${p[0]-ux*12-uy*5},${p[1]-uy*12+ux*5} L${p[0]-ux*12+uy*5},${p[1]-uy*12-ux*5} Z`} fill={g.colors[axis]}/>
<text x={p[0]+7} y={p[1]-7} fill={g.colors[axis]} fontSize={12}>{axis.toUpperCase()}</text>
</g>;
})}
<rect data-semantic-axis={props.axis} x={base[0]-7} y={base[1]-7} width={14} height={14} fill={color} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>{`Переместить: ${props.axis.toUpperCase()}`}</title></rect>
{chosen[0]&&(isRigidMarking(chosen[0])||selected?.object)?<circle data-semantic-axis="rotate" cx={base[0]} cy={base[1]} r={48} fill="none" stroke={color} strokeWidth={3} style={{pointerEvents:"stroke",cursor:"grab"}}><title>Повернуть элемент в плоскости</title></circle>:null}
</g>:null}
{props.editing&&node&&props.selection.length===1?(["incoming","outgoing"] as const).map(key=>{
const a=project(node.point),b=project(curveControlPoint(node,key,handleScale));
if(!a||!b||!node[key].some(Boolean))return null;
return <g key={key} data-semantic-handle-scale={handleScale}><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={4}/><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke={color} strokeWidth={1.5}/><circle data-semantic-handle={key} cx={b[0]} cy={b[1]} r={6} fill="var(--nodedc-text-primary)" stroke={color} strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>Ручка кривой</title></circle></g>;
}):null}
</svg>,viewport);
}
@@ -0,0 +1,147 @@
import {useSimulationLayout} from "./useSimulationLayout";
import {useEffect,useRef,useState} from "react";
import {createPortal} from "react-dom";
import {Button,Icon,IconButton,SegmentedControl,ToastStack,Window} from "@nodedc/ui-react";
import {URBAN_LABELS,availableUrbanClasses,visibleUrbanMap,type UrbanMap,type UrbanClassId} from "../../core/simulation/urbanMap";
import {isRigidMarking,isEditableMarking,semanticMembers,commitSemantic,redoSemantic,semanticDraft,semanticOperation,semanticRequest,undoSemantic,
type SemanticDraft,type SemanticOperation,type SemanticRevision,type Vertex} from "../../core/simulation/semanticEdits";
import type {AiEditorRuntime} from "./AiEditorRuntime";
import {SemanticEditOverlay,type SemanticChoice} from "./SemanticEditOverlay";
import {SemanticTools} from "./SemanticTools";
import type {SemanticTool} from "./semanticEditorTypes";
import {duplicateIndex,type SemanticAxis} from "../../core/simulation/semanticVector";
export function SemanticEditor({worldId,worldSha,runtime,viewport,active,busy,source,headerHost}:{
headerHost:HTMLElement|null;worldId:string;worldSha:string;runtime:AiEditorRuntime;viewport:HTMLElement;active:boolean;busy:boolean;source:UrbanMap;
}) {
const [revision,setRevision]=useState<SemanticRevision|null>(null);
const [draft,setDraft]=useState<SemanticDraft|null>(null);
const [error,setError]=useState<string|null>(null),[saving,setSaving]=useState(false);
const [loading,setLoading]=useState(true);
const [editing,setEditing]=useState(true);
const [layout,updateLayout]=useSimulationLayout();
const visible=layout.visible,setVisible=(v:typeof visible|((prior:typeof visible)=>typeof visible))=>updateLayout({visible:typeof v==="function"?v(visible):v});
const [selection,setSelection]=useState<Vertex[]>([]),[wholeContour,setWholeContour]=useState(false);
const selectVertices=(vertices:Vertex[],whole=false)=>{setSelection(vertices);setWholeContour(whole);};
const axis=layout.axis,setAxis=(axis:SemanticAxis)=>updateLayout({axis});
const areaMode=layout.areaMode,setAreaMode=(areaMode:typeof layout.areaMode)=>updateLayout({areaMode});
const layers=layout.layers,setLayers=(layers:UrbanClassId[])=>updateLayout({layers});
const selected=selection[0]??null;
const setSelected=(v:Vertex|null)=>selectVertices(v?[v]:[]);
const [choices,setChoices]=useState<SemanticChoice[]>([]);
const [tool,setTool]=useState<SemanticTool>("select");
const [template,setTemplate]=useState<string|null>(null);
const [preview,setPreview]=useState<SemanticOperation|null>(null);
const attempt=useRef<{key:string;signature:string}|null>(null);
const current=useRef({draft,revision});current.current={draft,revision};
const accept=(value:SemanticRevision)=>{
if(value.model.source.world_sha256!==worldSha||value.edited.source.world_sha256!==worldSha)
throw new Error("Правки относятся к другой сцене.");
setRevision(value);setDraft(semanticDraft(value.edited));attempt.current=null;setSelected(null);
};
useEffect(()=>{
if(!active||revision)return;
const abort=new AbortController();
setLoading(true);setError(null);
void semanticRequest(worldId,undefined,abort.signal).then(accept)
.catch(e=>{if(!abort.signal.aborted)setError(e.message);})
.finally(()=>{if(!abort.signal.aborted)setLoading(false);});
return()=>abort.abort();
},[active,worldId,worldSha,revision]);
useEffect(()=>{if(active){setEditing(true);}},[active]);
useEffect(()=>{runtime.setSemanticSelection(active&&editing);viewport.dataset.semanticEditing=String(active&&editing);
return()=>{runtime.setSemanticSelection(false);delete viewport.dataset.semanticEditing;};},[runtime,viewport,active,editing]);
const operate=(op:SemanticOperation)=>{
if(busy||saving)return;
try{const prior=current.current.draft!,next=commitSemantic(prior,op);setDraft(next);setError(null);
if(op.kind==="duplicate_vertex"&&next!==prior)setSelected({feature_id:op.feature_id,path:op.path,index:duplicateIndex(op.index,prior.map.features.find(f=>f.id===op.feature_id)!.geometry.type==="Polygon",op.side)});
if(op.kind==="duplicate_marking"&&next!==prior)setSelected({feature_id:op.new_feature_id,path:0,index:0,object:true});
if(op.kind==="insert")setSelected({...op,index:op.index+1});
}
catch(e){setError((e as Error).message);}
};
const removeSelected=()=>{
if(!selected||!draft)return;
const f=draft.map.features.find(f=>f.id===selected.feature_id);if(!f)return;
operate(isRigidMarking(f)||selected.object?{kind:"remove",feature_id:f.id}:{kind:"delete_vertices",vertices:selection});setSelected(null);
};
const display=draft?.map??source;
let overlay=display;
if(preview)try{overlay=semanticOperation(display,preview);}catch{/* Retain the last valid preview. */}
useEffect(()=>{
if(!active)return;
const hidden=editing&&selected&&preview?.kind!=="duplicate_marking"?semanticMembers(display,selected.feature_id):[];
const rendered=hidden.length?{...display,features:display.features.filter(f=>!hidden.includes(f))}:display;
runtime.setUrbanMap(rendered);runtime.setUrbanClasses(layers);runtime.showUrbanMap(visible.user);
},[runtime,active,display,editing,selected?.feature_id,visible.user,preview?.kind,layers]);
useEffect(()=>{
if(!active)return;
runtime.setAddMode(false);
const keyboard=(e:KeyboardEvent)=>{
if(!editing||busy||saving||preview||(e.target as Element).closest('input,textarea,select,[contenteditable="true"],[role="dialog"]')||document.querySelector('[data-dropdown-lineage]'))return;
if((e.metaKey||e.ctrlKey)&&e.code==="KeyZ"){
e.preventDefault();e.stopImmediatePropagation();setPreview(null);
setDraft(s=>s?(e.shiftKey?redoSemantic(s):undoSemantic(s)):s);setSelected(null);
}else if(!e.ctrlKey&&!e.metaKey&&["KeyV","KeyA","KeyP","KeyR"].includes(e.code)) {
const contours=layers.some(id=>!["road_marking","crosswalk_marking"].includes(id)),area=layers.some(id=>["pedestrian_area","sidewalk"].includes(id));
if((e.code==="KeyA"&&!contours&&!selection.some(v=>{const f=display.features.find(f=>f.id===v.feature_id);return f&&isEditableMarking(f);}))||(["KeyP","KeyR"].includes(e.code)&&!area))return;
e.preventDefault();e.stopImmediatePropagation();setTemplate(null);setTool(e.code==="KeyV"?"select":e.code==="KeyA"?"insert":e.code==="KeyP"?"pen":"rectangle");
}else if((e.key==="Delete"||e.key==="Backspace")&&selected){
e.preventDefault();e.stopImmediatePropagation();removeSelected();
}
};
document.addEventListener("keydown",keyboard,true);
return()=>document.removeEventListener("keydown",keyboard,true);
},[active,editing,busy,saving,preview,selection,layers,viewport,runtime,display]);
useEffect(()=>{
if(!draft?.operations.length)return;
const warn=(e:BeforeUnloadEvent)=>{e.preventDefault();};
window.addEventListener("beforeunload",warn);return()=>window.removeEventListener("beforeunload",warn);
},[draft?.operations.length]);
const save=async()=>{
const s=current.current;if(!s.draft?.operations.length||!s.revision||saving)return;
const body={expected_revision:s.revision.revision,model_sha256:s.revision.model_sha256,operations:s.draft.operations};
const signature=JSON.stringify(body);
if(attempt.current?.signature!==signature)attempt.current={signature,key:crypto.randomUUID()};
setSaving(true);setError(null);
try{accept(await semanticRequest(worldId,{...body,request_id:attempt.current.key}));}
catch(e){setError((e as Error).message);}
finally{setSaving(false);}
};
if(!active)return null;
const classes=availableUrbanClasses(display);
if(!classes.includes("road_marking"))classes.push("road_marking");
const overlaySelection=preview?.kind==="duplicate_marking"&&overlay!==display?[{feature_id:preview.new_feature_id,path:0,index:0,object:true as const}]:preview?.kind==="duplicate_vertex"&&overlay!==display?[{feature_id:preview.feature_id,path:preview.path,index:duplicateIndex(preview.index,display.features.find(f=>f.id===preview.feature_id)!.geometry.type==="Polygon",preview.side)}]:selection;
const marking=layers.some(id=>["road_marking","crosswalk_marking"].includes(id));
const contours=layers.some(id=>!["road_marking","crosswalk_marking"].includes(id));
const chooseTool=(next:SemanticTool)=>{setTool(next);setTemplate(null);setPreview(null);};
const undo=()=>{setDraft(s=>s?undoSemantic(s):s);setSelected(null);};
const redo=()=>{setDraft(s=>s?redoSemantic(s):s);setSelected(null);};
const controls=<>
{revision?<IconButton label={editing?"Завершить редактирование":"Редактировать разметку"} title={editing?"Завершить редактирование · Escape":"Редактировать разметку"} aria-pressed={editing}
onClick={()=>{setEditing(v=>!v);setSelected(null);chooseTool("select");setVisible(v=>({...v,user:true}));}}><Icon name="edit"/></IconButton>:null}
{draft?.operations.length?<IconButton label="Сохранить правки" title="Сохранить правки" loading={saving} onClick={()=>void save()}><Icon name="save"/></IconButton>:null}
</>;
return <>
{headerHost?createPortal(controls,headerHost):null}
{!revision?<Button loading={loading} onClick={()=>{setLoading(true);setError(null);void semanticRequest(worldId).then(accept).catch(e=>setError(e.message)).finally(()=>setLoading(false));}}>{loading?"Открываем разметку":"Повторить открытие"}</Button>:null}
{revision?<SemanticTools viewport={viewport} editing={editing&&visible.user&&layers.length>0&&!busy&&!saving} tool={tool} setTool={chooseTool} marking={marking} contours={contours}
area={layers.some(id=>["pedestrian_area","sidewalk"].includes(id))} template={template} setTemplate={id=>{setTemplate(id);setSelected(null);setTool("select");}}
selection={selection} map={display} operate={operate} remove={removeSelected} undo={undo} redo={redo} canUndo={!!draft?.operations.length} canRedo={!!draft?.future.length}
axis={axis} setAxis={setAxis} visible={visible} setVisible={v=>{setVisible(v);if(!v.user)setSelected(null);}} areaMode={areaMode} setAreaMode={setAreaMode} onError={setError}/>:null}
{createPortal(<div className="ai-local-editor__legend nodedc-scene-controls">
{classes.length?<SegmentedControl label="Видимые и редактируемые слои" selectionMode="multiple" value={layers} onChange={v=>{setLayers(v);setSelection(s=>s.filter(x=>v.includes(display.features.find(f=>f.id===x.feature_id)?.properties.class as UrbanClassId)));chooseTool("select");}}
items={classes.map(id=>({value:id,label:URBAN_LABELS[id]}))}/>:null}
</div>,viewport)}
<SemanticEditOverlay runtime={runtime} viewport={viewport} map={visibleUrbanMap(overlay,visible.user?layers:[])}
original={visible.model&&revision?visibleUrbanMap(revision.model,layers):null} layers={layers} selected={overlaySelection[0]??null} selection={overlaySelection} wholeContour={wholeContour}
editing={editing&&visible.user&&layers.length>0} blocked={busy||saving} tool={tool} template={template} onPlaced={()=>chooseTool("select")}
axis={axis} areaMode={areaMode} onSelect={setSelected} onSelection={selectVertices} onChoose={setChoices} onOperation={operate} onPreview={setPreview} onError={setError}
onExit={()=>{setEditing(false);setSelected(null);chooseTool("select");}}/>
<Window open={choices.length>0} onClose={()=>setChoices([])} title="Выберите контур">
{choices.map(({vertex,selection,wholeContour,operation},index)=><Button key={vertex.feature_id} onClick={()=>{selectVertices(selection,wholeContour);if(operation)operate(operation);setChoices([]);}}>{URBAN_LABELS[display.features.find(f=>f.id===vertex.feature_id)?.properties.class as UrbanClassId]} · {index+1}</Button>)}
</Window>
<ToastStack items={error?[{id:"semantic",tone:"error",title:"Не удалось выполнить действие",description:error}]:[]} onDismiss={()=>setError(null)}/>
</>;
}
@@ -0,0 +1,47 @@
import {Button,Checker,Toolbar,type ToolbarItem} from "@nodedc/ui-react";
import {createPortal} from "react-dom";
import {MARKING_TEMPLATES,isEditableMarking,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import {knots,type SemanticAxis} from "../../core/simulation/semanticVector";
import type {UrbanMap} from "../../core/simulation/urbanMap";
import type {SemanticTool} from "./semanticEditorTypes";
import {usePlannerPreferences} from "./usePlannerPreferences";
export function SemanticTools(p:{viewport:HTMLElement;editing:boolean;tool:SemanticTool;setTool:(v:SemanticTool)=>void;marking:boolean;contours:boolean;area:boolean;template:string|null;setTemplate:(v:string)=>void;
selection:Vertex[];map:UrbanMap;operate:(op:SemanticOperation)=>void;remove:()=>void;undo:()=>void;redo:()=>void;canUndo:boolean;canRedo:boolean;axis:SemanticAxis;setAxis:(v:SemanticAxis)=>void;
visible:{model:boolean;user:boolean};setVisible:(v:{model:boolean;user:boolean})=>void;areaMode:"union"|"difference";setAreaMode:(m:"union"|"difference")=>void;onError:(s:string)=>void}) {
const [prefs,update]=usePlannerPreferences();
const items:ToolbarItem[]=[{id:"hold",label:prefs.toolbar.autoHide?"Hold · Закрепить тулбар":"Hold · Открепить тулбар",icon:"lock",active:!prefs.toolbar.autoHide,onSelect:()=>{try{update({...prefs,toolbar:{...prefs.toolbar,autoHide:!prefs.toolbar.autoHide}});}catch{p.onError("Не удалось сохранить закрепление тулбара.");}}}];
const editableMarking=p.selection.some(v=>{const f=p.map.features.find(f=>f.id===v.feature_id);return f&&isEditableMarking(f);});
const menu=(children:React.ReactNode)=><div className="semantic-tools__menu">{children}</div>;
if(p.editing){
items.push({id:"select",label:"Выделение",shortcut:"V",icon:"select",active:p.tool==="select"&&!p.template,onSelect:()=>p.setTool("select")});
if(p.contours||editableMarking)items.push({id:"insert",label:"Добавить точку на контур",shortcut:"A",icon:"add-point",active:p.tool==="insert",onSelect:()=>p.setTool("insert")});
if(p.area){
items.push({id:"pen",label:"Перо: замкните контур или Enter",shortcut:"P",icon:"pen",active:p.tool==="pen",onSelect:()=>p.setTool("pen")},
{id:"rectangle",label:"Прямоугольник: два противоположных угла",shortcut:"R",icon:"rectangle",active:p.tool==="rectangle",onSelect:()=>p.setTool("rectangle")},
{id:"area-mode",label:"Действие области",icon:p.areaMode==="union"?"plus":"trash",onSelect:()=>{},menu:close=>menu(([['union','Заполнить область'],['difference','Вырезать область']] as const).map(([id,label])=><Button key={id} width="full" variant={p.areaMode===id?"primary":"secondary"} tone="neutral" aria-pressed={p.areaMode===id} onClick={()=>{p.setAreaMode(id);close();}}>{label}</Button>))});
}
items.push({id:"axes",label:`Оси перемещения: ${p.axis.toUpperCase()}`,icon:"target",onSelect:()=>{},menu:close=>menu((["x","y","z","xy","xz","yz"] as const).map(axis=><Button key={axis} width="full" variant={p.axis===axis?"primary":"secondary"} tone="neutral" aria-pressed={p.axis===axis} onClick={()=>{p.setAxis(axis);close();}}>{axis.toUpperCase()}</Button>))});
if(p.selection.length===1&&!p.selection[0].object){
const v=p.selection[0],f=p.map.features.find(f=>f.id===v.feature_id),nodes=f?knots(f,v.path):[],n=nodes[v.index];
const curved=!!n&&[...n.incoming,...n.outgoing].some(Boolean);
if(n)items.push({id:"properties",label:"Свойства точки",icon:"curve",onSelect:()=>{},menu:close=>menu(<>
<Button width="full" variant={!curved?"primary":"secondary"} tone="neutral" aria-pressed={!curved} onClick={()=>{p.operate({...v,kind:"curve",incoming:[0,0],outgoing:[0,0]});close();}}>Угловая точка</Button>
<Button width="full" variant={curved?"primary":"secondary"} tone="neutral" aria-pressed={curved} onClick={()=>{
const closed=f!.geometry.type==="Polygon",prev=nodes[v.index-1]??(closed?nodes.at(-1)!:n),next=nodes[v.index+1]??(closed?nodes[0]:n);
const tangent=next.point.slice(0,2).map((a,k)=>a-prev.point[k]),length=Math.hypot(...tangent)||1;
const before=Math.hypot(...n.point.slice(0,2).map((a,k)=>a-prev.point[k]))/3,after=Math.hypot(...n.point.slice(0,2).map((a,k)=>a-next.point[k]))/3;
p.operate({...v,kind:"curve",incoming:tangent.map(x=>-x/length*before),outgoing:tangent.map(x=>x/length*after)});close();
}}>Кривая с ручками</Button>
</>)});
}
if(p.selection.length)items.push({id:"delete",label:"Удалить выделенное",shortcut:"Delete",icon:"trash",onSelect:p.remove});
if(p.canUndo)items.push({id:"undo",label:"Отменить",shortcut:"Control+Z Meta+Z",icon:"undo",onSelect:p.undo});
if(p.canRedo)items.push({id:"redo",label:"Повторить",shortcut:"Control+Shift+Z Meta+Shift+Z",icon:"redo",onSelect:p.redo});
}
items.push({id:"visibility",label:"Видимость разметки",icon:"eye",onSelect:()=>{},menu:menu(<>
<Checker label="Алгоритмическая разметка" checked={p.visible.model} onChange={model=>p.setVisible({...p.visible,model})}/>
<Checker label="Ручная разметка" checked={p.visible.user} onChange={user=>p.setVisible({...p.visible,user})}/>
</>)}, {id:"quality",label:"Качество Gaussian-сцены",icon:"sliders",onSelect:()=>{},menu:close=>menu(([["low","Низкое"],["medium","Среднее"],["high","Высокое"],["ultra","Ультра"],["maximum","Максимум"]] as const).map(([quality,label])=><Button key={quality} width="full" variant={prefs.quality===quality?"primary":"secondary"} tone="neutral" aria-pressed={prefs.quality===quality} onClick={()=>{try{update({...prefs,quality});close();}catch{p.onError("Не удалось сохранить качество.");}}}>{label}</Button>))});
if(p.editing&&p.marking)items.push({id:"marking",label:"Добавить элемент разметки",icon:"plus",active:!!p.template,onSelect:()=>{},menu:close=>menu(MARKING_TEMPLATES.templates.filter(t=>!(t as {hidden?:boolean}).hidden).map(t=><Button key={t.id} width="full" onClick={()=>{p.setTemplate(t.id);close();}}>{t.label}</Button>))});
return createPortal(<Toolbar container={p.viewport} {...prefs.toolbar} label="Инструменты семантики" items={items}/>,p.viewport);
}
@@ -27,7 +27,7 @@ export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{
const show=(id:string,checked:boolean)=>setLayout(value=>({...value,catalogVisible:checked?[...new Set([...(value.catalogVisible??[]),id])]:(value.catalogVisible??[]).filter(key=>key!==id),hidden:checked?value.hidden.filter(key=>key!==id):[...new Set([...value.hidden,id])]}));
useEffect(()=>{const escape=(event:KeyboardEvent)=>{if(document.querySelector('[data-docking="true"]'))return;if(event.key==='Escape'&&effectiveFull&&!document.querySelector('[role=dialog],[role=listbox]')){setFull(null);event.stopImmediatePropagation();}};window.addEventListener('keydown',escape,true);return()=>window.removeEventListener('keydown',escape,true);},[effectiveFull]);
return <div className="ai-polygon__observation">
<div className="ai-polygon__observation-toolbar">
<div className="ai-polygon__observation-toolbar nodedc-viewport-controls">
{effectiveFull&&<Button onClick={()=>setFull(null)}>Все окна</Button>}
<Dropdown placement="bottom-end" width={340} surfaceRole="dialog" trigger={({open,toggle,setTriggerRef,surfaceId})=><Button ref={setTriggerRef} icon={<Icon name="layers"/>} aria-haspopup="dialog" aria-expanded={open} aria-controls={surfaceId} onClick={toggle}>Камеры и слои</Button>}>
{({close})=><div className="ai-polygon__layer-options" role="group" aria-label="Камеры и слои">
@@ -3,26 +3,30 @@ import { Icon, IconButton, Select, ToastStack, Window } from "@nodedc/ui-react";
import { PlannerSettings } from "./PlannerSettings";
import { usePlannerPreferences } from "./usePlannerPreferences";
export function SimulationViewTools({expanded,toggle,planning=false,boundsRef,children}: {expanded:boolean;toggle:()=>void;planning?:boolean;boundsRef:RefObject<HTMLDivElement|null>;children?:ReactNode}) {
export function SimulationViewTools({expanded,toggle,semantic=false,planning=false,routeEditing=planning,boundsRef,children}: {expanded:boolean;toggle:()=>void;semantic?:boolean;planning?:boolean;routeEditing?:boolean;boundsRef:RefObject<HTMLDivElement|null>;children?:ReactNode}) {
const [prefs,update]=usePlannerPreferences();
const [settings,setSettings]=useState(false),[help,setHelp]=useState(false),[error,setError]=useState<string|null>(null);
return <>
<div className="ai-simulation__view-tools nodedc-scene-controls">
{children}
<Select label="Качество Gaussian-сцены" value={prefs.quality} minMenuWidth={210}
<div className={`ai-simulation__view-tools nodedc-scene-controls ${planning?"ai-simulation__view-tools--planning":""}`}>
{!planning?children:null}
<div className="ai-simulation__display-tools">
{!semantic?<Select label="Качество Gaussian-сцены" value={prefs.quality} minMenuWidth={210}
options={[{value:"low",label:"Низкое"},{value:"medium",label:"Среднее"},{value:"high",label:"Высокое"},{value:"ultra",label:"Ультра"},{value:"maximum",label:"Максимум"}]}
onChange={(quality)=>{try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>
onChange={(quality)=>{try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/>:null}
<IconButton label="Помощь по управлению" onClick={()=>setHelp(true)}><Icon name="info"/></IconButton>
{planning?<IconButton label="Настройки планировщика" onClick={()=>setSettings(true)}><Icon name="settings"/></IconButton>:null}
{planning?<IconButton label="Настройки сцены" onClick={()=>setSettings(true)}><Icon name="settings"/></IconButton>:null}
<IconButton label={expanded?"Свернуть просмотр":"Развернуть просмотр"} onClick={toggle}><Icon name={expanded?"minimize":"expand"}/></IconButton>
</div>
{planning?children:null}
</div>
{settings?<PlannerSettings boundsRef={boundsRef} onClose={()=>setSettings(false)}/>:null}
<Window open={help} onClose={()=>setHelp(false)} title="Управление сценой">
<div className="ai-polygon__form">{planning?<>
<p>ЛКМ — вращение вокруг точки нажатия. ПКМ или клик двумя пальцами с движением — сдвиг.</p>
<p>Прокрутка — зум к курсору, в том числе в режиме добавления точек.</p>
<p>{semantic?"При редактировании Ctrl + перетаскивание ЛКМ — вращение камеры; без Ctrl — выбранный инструмент. Вне редактирования ЛКМ вращает камеру без Ctrl.":"ЛКМ — вращение вокруг точки нажатия."} ПКМ или клик двумя пальцами с движением — сдвиг.</p>
<p>{semantic?"При редактировании прокрутка двумя пальцами сдвигает вид; щипок или Ctrl + прокрутка — зум к курсору.":"Прокрутка — зум к курсору, в том числе в режиме добавления точек."}</p>
<p>WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.</p>
<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>
{semantic?<p>Клик по полосе выбирает элемент целиком, по её вершине — точку; рамка или Shift + клик выбирают несколько точек. Shift + перетаскивание пивота копирует целый элемент или продолжает выбранную точку. Escape отменяет действие, Ctrl/Cmd+Z — отменяет правку. Hold закрепляет тулбар.</p>:null}
{routeEditing?<p>Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.</p>:null}
</>:<><p>WASD / стрелки — движение. Пробел — тормоз. R — к старту.</p><p>Мышь — обзор.</p></>}</div>
</Window>
{error?<ToastStack items={[{id:"quality",tone:"error",title:error}]} onDismiss={()=>setError(null)}/>:null}
@@ -258,7 +258,7 @@ export function SimulationViewport({
</StatusBadge>
<span>Engine 2.21.4</span>
</div>
<div className="simulation-viewport__controls">
<div className="simulation-viewport__controls nodedc-viewport-controls">
<Select
label="Качество Gaussian-сцены"
value={quality}
@@ -13,7 +13,7 @@ export function localScene(cache: EditorCache): SimulationWorldManifest {
return {
schemaVersion: "missioncore.simulation-world-manifest/v1", projectId: cache.world.world_id,
visual: { previewSogUrl: null, streamedSogUrl: saved?.visual_url ?? editorAssetUrl(cache.key,"scene.sog") },
collision: { meshUrl: saved?.collision_url ?? editorAssetUrl(cache.key,"collision.glb"), available: true },
collision: { meshUrl: saved ? saved.collision_url : editorAssetUrl(cache.key,"collision.glb"), available: saved ? !!saved.collision_url : true },
transforms: { worldFromVisual: Array.from(visual.data),
worldFromCollision: Array.from((saved ? matrix(saved.collision_rotation) : new Mat4()).data) },
};
@@ -0,0 +1,20 @@
import type {UrbanClassId,UrbanMap} from "../../core/simulation/urbanMap";
import {isRigidMarking,semanticMembers,semanticPivot,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import {knots,type SemanticAxis} from "../../core/simulation/semanticVector";
import type {AiEditorRuntime} from "./AiEditorRuntime";
export type SemanticTool="select"|"insert"|"pen"|"rectangle";
export type SemanticChoice={vertex:Vertex;selection:Vertex[];wholeContour?:boolean;operation?:SemanticOperation};
export interface SemanticOverlayProps {
runtime:AiEditorRuntime;viewport:HTMLElement;map:UrbanMap;original:UrbanMap|null;layers:readonly UrbanClassId[];
selected:Vertex|null;selection:Vertex[];wholeContour?:boolean;editing:boolean;blocked:boolean;tool:SemanticTool;template:string|null;
axis:SemanticAxis;areaMode:"union"|"difference";
onSelect:(v:Vertex|null)=>void;onSelection:(v:Vertex[],wholeContour?:boolean)=>void;onChoose:(v:SemanticChoice[])=>void;
onPlaced:()=>void;onOperation:(op:SemanticOperation)=>void;onPreview:(op:SemanticOperation|null)=>void;
onError:(message:string)=>void;onExit:()=>void;
}
export function semanticAnchor(p:SemanticOverlayProps) {
const members=p.selected?semanticMembers(p.map,p.selected.feature_id):[];if(!members.length)return null;
if(isRigidMarking(members[0])||p.selected?.object)return semanticPivot(members);
const points=p.selection.flatMap(v=>{const f=p.map.features.find(f=>f.id===v.feature_id);const q=f?knots(f,v.path)[v.index]?.point:null;return q?[q]:[];});
return points.length?[0,1,2].map(k=>points.reduce((n,q)=>n+q[k],0)/points.length):null;
}
@@ -0,0 +1,170 @@
import {curveControlScale,moveCurveControl} from "../../core/simulation/semanticCurveControls";
import {useEffect,useRef,useState} from "react";
import {isMarking,isRigidMarking,semanticOperation,type SemanticOperation,type Vertex} from "../../core/simulation/semanticEdits";
import {semanticHits,semanticHitSelection} from "../../core/simulation/semanticPicking";
import {duplicateSide,editablePaths,knots,type SemanticAxis} from "../../core/simulation/semanticVector";
import {regionOperation} from "../../core/simulation/semanticArea";
import {semanticAnchor,type SemanticOverlayProps} from "./semanticEditorTypes";
export function useSemanticGestures(props:SemanticOverlayProps) {
const latest=useRef(props);latest.current=props;
const [hover,setHover]=useState<string|null>(null),[ghost,setGhost]=useState<SemanticOperation|null>(null);
const [marquee,setMarquee]=useState<number[]|null>(null),[brush,setBrush]=useState<number[][]>([]);
useEffect(()=>{
const {runtime,viewport}=props,canvas=viewport.querySelector("canvas")!;
let generation=0,disposed=false,picking=false,pending:number[]|null=null,placing=false;
let shape:number[][]=[],rectangle:number[]|null=null,orbit:number|null=null;
let box:{id:number;start:number[];shift:boolean}|null=null;
let drag:{id:number;point:number[];start:number[];screen:number[];axis:SemanticAxis|"rotate";op:SemanticOperation|null;selected:Vertex;selection:Vertex[];map:SemanticOverlayProps["map"];handle?:"incoming"|"outgoing";handleScale?:number;handleStart?:number[];duplicate?:Vertex;copy?:{feature_id:string;new_feature_id:string}}|null=null;
const stop=(e:Event)=>{e.preventDefault();e.stopImmediatePropagation();};
const screen=(e:PointerEvent)=>{const r=canvas.getBoundingClientRect();return [e.clientX-r.left,e.clientY-r.top];};
const norm=(e:PointerEvent)=>{const xy=screen(e);return [xy[0]/canvas.clientWidth,xy[1]/canvas.clientHeight];};
const project=(v:number[])=>{const q=runtime.projectSemantic(v);return q?[q[0]*canvas.clientWidth,q[1]*canvas.clientHeight]:null;};
const hits=(e:PointerEvent)=>semanticHits(latest.current.map,latest.current.layers,screen(e),project,latest.current.tool==="select",latest.current.selection.map(v=>v.feature_id));
const focus=()=>canvas.focus({preventScroll:true});
const place=(position:number[],id:string):Extract<SemanticOperation,{kind:"place"}>=>({kind:"place",feature_id:id,template_id:latest.current.template!,position,surface:"gaussian-visual"});
const pick=async()=>{
if(picking||!pending)return;const xy=pending;pending=null;picking=true;const version=generation;
try{const point=await runtime.pickSemanticSurface(xy[0],xy[1]);
if(!disposed&&version===generation&&latest.current.template)setGhost(point?place(point,"user-preview-placement"):null);
}catch{if(!disposed)setGhost(null);}finally{picking=false;if(pending&&!disposed)void pick();}
};
const release=(id:number)=>{if(viewport.hasPointerCapture(id))viewport.releasePointerCapture(id);};
const finish=(cancel:boolean)=>{
const d=drag;drag=null;latest.current.onPreview(null);
if(d){if(!cancel&&d.op)latest.current.onOperation(d.op);release(d.id);}
if(box){const id=box.id;box=null;release(id);}setMarquee(null);
runtime.setNavigation(!latest.current.blocked);
};
const commitShape=(points:number[][])=>{
try{const p=latest.current,f=p.map.features.find(f=>f.id===p.selected?.feature_id&&["pedestrian_area","sidewalk"].includes(f.properties.class));
p.onOperation(regionOperation(f,[...points,points[0]],p.areaMode));
}catch(e){latest.current.onError((e as Error).message);}
shape=[];rectangle=null;setBrush([]);
};
const beginDrag=(e:PointerEvent,p:SemanticOverlayProps,selected:Vertex,selection:Vertex[],activeAxis:SemanticAxis|"rotate",handle?:"incoming"|"outgoing")=>{
const f=p.map.features.find(f=>f.id===selected.feature_id);if(!f)return;
const copy=e.shiftKey&&!handle&&activeAxis!=="rotate"&&isMarking(f)&&(isRigidMarking(f)||selected.object);
const duplicate=e.shiftKey&&!handle&&activeAxis!=="rotate"&&!copy&&!isRigidMarking(f);
if(duplicate&&selection.length!==1){stop(e);p.onError("Для продолжения сплайна выберите одну точку.");return;}
const point=semanticAnchor({...p,selected,selection});if(!point)return;
const [x,y]=norm(e),start=runtime.moveSemantic(point,x,y,activeAxis==="rotate"?"xy":activeAxis);if(!start)return;
stop(e);focus();drag={id:e.pointerId,point,start,screen:screen(e),axis:activeAxis,op:null,selected,selection,map:p.map,handle,
duplicate:duplicate?{feature_id:selected.feature_id,path:selected.path,index:selected.index}:undefined,
copy:copy?{feature_id:selected.feature_id,new_feature_id:`user-${crypto.randomUUID()}`}:undefined};
if(handle){const nodes=knots(f,selected.path);drag.handleScale=curveControlScale(nodes,selected.index,f.geometry.type==="Polygon",project);drag.handleStart=nodes[selected.index][handle];}
runtime.setNavigation(false);viewport.setPointerCapture(e.pointerId);
};
const down=(e:PointerEvent)=>{
const p=latest.current;if(!p.editing||p.blocked)return;
const target=e.target as Element,[x,y]=norm(e);
if(e.ctrlKey&&[0,2].includes(e.button)&&(target===canvas||target.closest("[data-semantic-axis],[data-semantic-handle]"))){
if(drag||box)return;
generation++;pending=null;setGhost(null);setHover(null);orbit=e.pointerId;
e.preventDefault();return; // Bubble to EditorCamera; never edit during this gesture.
}
if(e.button!==0)return;
const axis=target.closest<SVGElement>("[data-semantic-axis]")?.dataset.semanticAxis as SemanticAxis|"rotate"|undefined;
const handle=target.closest<SVGElement>("[data-semantic-handle]")?.dataset.semanticHandle as "incoming"|"outgoing"|undefined;
if((axis||handle)&&p.selected){
beginDrag(e,p,p.selected,p.selection,handle?"xy":axis!,handle);return;
}
if(e.target!==canvas)return;stop(e);focus();
if(p.template){
if(placing)return;placing=true;generation++;pending=null;const version=generation;
void runtime.pickSemanticSurface(x,y).then(point=>{
if(!disposed&&version===generation&&point){const op=place(point,`user-${crypto.randomUUID()}`);p.onOperation(op);p.onSelect({feature_id:op.feature_id,path:0,index:0,object:true});p.onPlaced();setGhost(null);}
}).catch(e=>p.onError(e.message)).finally(()=>{placing=false;});return;
}
if(p.tool==="pen"||p.tool==="rectangle"){
if(shape.length>=128){p.onError("Замкните область: не более 128 точек за один контур.");return;}
const first=shape[0]?project(shape[0]):null;
if(p.tool==="pen"&&shape.length>=3&&first&&Math.hypot(screen(e)[0]-first[0],screen(e)[1]-first[1])<12){commitShape(shape);return;}
const version=generation;
if(p.tool==="rectangle"&&rectangle){const q=runtime.moveSemantic(rectangle,x,y,"xy");if(q)commitShape([rectangle,[q[0],rectangle[1],rectangle[2]],q,[rectangle[0],q[1],rectangle[2]]]);return;}
if(placing)return;placing=true;
void runtime.pickSemanticSurface(x,y).then(point=>{if(!disposed&&version===generation&&point){
if(p.tool==="rectangle")rectangle=point;shape=[...shape,point];setBrush(shape);
}}).catch(e=>p.onError(e.message)).finally(()=>{placing=false;});return;
}
const options=hits(e);
if(!options.length){box={id:e.pointerId,start:screen(e),shift:e.shiftKey};viewport.setPointerCapture(e.pointerId);return;}
const best=options[0],near=options.filter(c=>!!c.point===!!best.point&&c.distance<=best.distance+2);
const ids=[...new Set(near.map(c=>c.vertex.feature_id))];
const choice=(h:typeof best)=>{
const s=h.segment,t=s?s.start+(s.end-s.start)*runtime.semanticSegmentParameter(s.a,s.b,s.t):h.t;
const selection=p.tool==="select"?semanticHitSelection(p.map,h):[h.vertex],vertex=selection[0];
return {vertex,selection,wholeContour:p.tool==="select"&&!h.point&&!vertex.object,operation:p.tool==="insert"&&t>0&&t<1?{...h.vertex,kind:"insert" as const,t}:undefined};
};
if(ids.length>1){p.onChoose(ids.map(id=>choice(near.find(c=>c.vertex.feature_id===id)!)));return;}
const picked=choice(best),vertex=picked.vertex;
if(p.tool==="select"&&!best.point&&!vertex.object){
const selection=e.shiftKey?[...p.selection.filter(v=>!v.object),...picked.selection]:picked.selection;
p.onSelection([...new Map(selection.map(v=>[JSON.stringify(v),v])).values()],!e.shiftKey);
}else if(e.shiftKey&&p.tool==="select"&&!vertex.object){
const previous=p.selection.filter(v=>!v.object),exists=previous.some(v=>JSON.stringify(v)===JSON.stringify(vertex));p.onSelection(exists?previous.filter(v=>JSON.stringify(v)!==JSON.stringify(vertex)):[...previous,vertex]);
}else if(p.tool==="select"&&best.point){
const selected=!p.wholeContour&&p.selection.some(v=>!v.object&&v.feature_id===vertex.feature_id&&v.path===vertex.path&&v.index===vertex.index)?p.selection:[vertex];
p.onSelection(selected);beginDrag(e,p,vertex,selected,p.axis);
}else p.onSelect(vertex);
if(p.tool==="insert"&&choice(best).operation)p.onOperation(choice(best).operation!);
};
const move=(e:PointerEvent)=>{
if(orbit===e.pointerId)return;
const p=latest.current;
if(box&&e.pointerId===box.id){stop(e);setMarquee([...box.start,...screen(e)]);return;}
if(!drag){
if(!p.editing||p.blocked||e.target!==canvas){setHover(null);return;}
if(rectangle){const [x,y]=norm(e),q=runtime.moveSemantic(rectangle,x,y,"xy");if(q)setBrush([rectangle,[q[0],rectangle[1],rectangle[2]],q,[rectangle[0],q[1],rectangle[2]],rectangle]);return;}
if(p.template){pending=norm(e);void pick();}else setHover(hits(e)[0]?.vertex.feature_id??null);return;
}
if(e.pointerId!==drag.id)return;if(p.blocked){finish(true);return;}stop(e);
if(Math.hypot(...screen(e).map((v,k)=>v-drag!.screen[k]))<2){drag.op=null;p.onPreview(null);return;}
const [x,y]=norm(e),q=runtime.moveSemantic(drag.point,x,y,drag.axis==="rotate"?"xy":drag.axis);if(!q)return;
const selected=drag.selected,selection=drag.selection,map=drag.map;
if(drag.handle){const f=map.features.find(f=>f.id===selected.feature_id)!;const node=knots(f,selected.path)[selected.index];
const value=moveCurveControl(drag.handleStart!,drag.start,q,drag.handleScale!);
drag.op={kind:"curve",...selected,incoming:drag.handle==="incoming"?value:node.incoming,outgoing:drag.handle==="outgoing"?value:node.outgoing};
}else if(drag.axis==="rotate"){
const angle=Math.atan2(q[1]-drag.point[1],q[0]-drag.point[0])-Math.atan2(drag.start[1]-drag.point[1],drag.start[0]-drag.point[0]);
drag.op={kind:"transform",feature_id:selected.feature_id,delta:[0,0],angle};
}else {
const delta=q.map((v,k)=>drag!.axis.includes("xyz"[k])?v-drag!.start[k]:0);
drag.op=drag.copy?{kind:"duplicate_marking",...drag.copy,axis:drag.axis,delta}:drag.duplicate?{kind:"duplicate_vertex",...drag.duplicate,axis:drag.axis,delta,
side:duplicateSide(knots(map.features.find(f=>f.id===drag!.duplicate!.feature_id)!,drag.duplicate.path),drag.duplicate.index,map.features.find(f=>f.id===drag!.duplicate!.feature_id)!.geometry.type==="Polygon",delta)}:
{kind:!selected.object?"translate_vertices":"translate",feature_id:selected.feature_id,vertices:selection.filter(v=>!v.object),axis:drag.axis,delta};
}
p.onPreview(drag.op);
};
const up=(e:PointerEvent)=>{
if(orbit===e.pointerId){orbit=null;return;}
if(box&&box.id===e.pointerId){stop(e);const p=latest.current,end=screen(e),start=box.start;
const selected:Vertex[]=box.shift?p.selection.filter(v=>!v.object):[];
if(Math.hypot(end[0]-start[0],end[1]-start[1])>3)for(const f of p.map.features){
if(!p.layers.includes(f.properties.class as typeof p.layers[number])||f.properties.review_status==="rejected"||isRigidMarking(f))continue;
editablePaths(f).forEach((path,j)=>path.slice(0,path.length-Number(f.geometry.type==="Polygon")).forEach((v,i)=>{
const q=project(v);if(q&&q.every((v,k)=>v>=Math.min(start[k],end[k])&&v<=Math.max(start[k],end[k])))selected.push({feature_id:f.id,path:j,index:i});
}));
}
p.onSelection([...new Map(selected.map(v=>[JSON.stringify(v),v])).values()]);finish(true);
}else if(drag&&e.pointerId===drag.id){stop(e);finish(false);}
};
const cancel=()=>{orbit=null;generation++;pending=null;finish(true);shape=[];rectangle=null;setBrush([]);setGhost(null);};
const key=(e:KeyboardEvent)=>{
const p=latest.current;if(!p.editing||p.blocked||e.defaultPrevented)return;
if(e.key==="Escape"){
// Dropdown gets the first Escape. Editor owns placement even after focus left canvas.
if(document.querySelector('[data-dropdown-lineage]'))return;
stop(e);
if(drag||box||shape.length||p.template||p.tool!=="select"){cancel();p.onPlaced();}
else if(p.selection.length)p.onSelection([]);else p.onExit();
}else if(e.key==="Enter"&&shape.length>=3){stop(e);commitShape(shape);}
};
const leave=()=>{if(!drag&&!box){generation++;pending=null;setGhost(null);setHover(null);}};
viewport.addEventListener("pointerdown",down,true);viewport.addEventListener("pointermove",move,true);viewport.addEventListener("pointerup",up,true);
viewport.addEventListener("pointercancel",cancel,true);viewport.addEventListener("pointerleave",leave);document.addEventListener("keydown",key,true);
window.addEventListener("blur",cancel);
return()=>{disposed=true;cancel();viewport.removeEventListener("pointerdown",down,true);viewport.removeEventListener("pointermove",move,true);viewport.removeEventListener("pointerup",up,true);viewport.removeEventListener("pointercancel",cancel,true);viewport.removeEventListener("pointerleave",leave);document.removeEventListener("keydown",key,true);window.removeEventListener("blur",cancel);};
},[props.runtime,props.viewport,props.editing,props.tool,props.template,props.layers]);
const ghostMap=ghost?semanticOperation({...props.map,features:[]},ghost):null;
return {hover,ghostMap,marquee,brush};
}
@@ -6,7 +6,7 @@ export function useSimulationFullscreen(view: RefObject<HTMLDivElement | null>)
const sync = () => setExpanded(!!view.current && document.fullscreenElement === view.current);
const escape = (event: KeyboardEvent) => {
if (event.key !== "Escape" || !view.current || document.fullscreenElement !== view.current) return;
if (view.current.querySelector('[role="dialog"], .nodedc-dropdown-surface, [data-docking="true"]')) return;
if (view.current.querySelector('[data-semantic-editing="true"], [role="dialog"], .nodedc-dropdown-surface, [data-docking="true"]')) return;
event.preventDefault();
event.stopPropagation();
void document.exitFullscreen().catch(() => undefined);
@@ -0,0 +1,22 @@
import {useSyncExternalStore} from "react";
import {normalizeSimulationLayout,normalizeSceneView,type SimulationLayout,type SceneView} from "../../core/simulation/simulationLayout";
const KEY="missioncore.simulation-layout/v1",SCENES="missioncore.simulation-cameras/v1";
const listeners=new Set<()=>void>();
function read(key:string){try{return JSON.parse(localStorage.getItem(key)??"null");}catch{return null;}}
let current=normalizeSimulationLayout(read(KEY));
export const getSimulationLayout=()=>current;
export function updateSimulationLayout(patch:Partial<SimulationLayout>){
const next=normalizeSimulationLayout({...current,...patch});
// UI choices stay usable in private/blocked storage; no edits or observations are stored here.
try{localStorage.setItem(KEY,JSON.stringify(next));}catch{/* Session-only fallback. */}
current=next;listeners.forEach(fn=>fn());
}
window.addEventListener("storage",e=>{if(e.key!==KEY&&e.key!==null)return;current=normalizeSimulationLayout(read(KEY));listeners.forEach(fn=>fn());});
export function useSimulationLayout(){return [useSyncExternalStore(fn=>{listeners.add(fn);return()=>{listeners.delete(fn);};},getSimulationLayout),updateSimulationLayout] as const;}
export function readSceneView(key:string){return normalizeSceneView(read(SCENES)?.[key]);}
export function writeSceneView(key:string,value:SceneView){
const valid=normalizeSceneView(value);if(!valid)return;
const old=read(SCENES),entries=old&&typeof old==="object"?Object.entries(old):[];
const next=Object.fromEntries([...entries.filter(([k,v])=>k!==key&&normalizeSceneView(v)).slice(-15),[key,valid]]);
try{localStorage.setItem(SCENES,JSON.stringify(next));}catch{/* Keep the live scene usable. */}
}
@@ -1,3 +1,4 @@
import {usbCanSensorUi} from '../../../../plugins/usb-can/frontend/src/plugin';
import {vescSensorUi} from '../../../../plugins/vesc/frontend/src/plugin';
import type { DeviceUiPlugin } from "../core/device-plugins/contracts";
import { xgridsK1Plugin } from "@xgrids-k1/frontend/plugin";
@@ -11,4 +12,4 @@ export const installedDevicePlugins: readonly DeviceUiPlugin[] = Object.freeze([
// Node-executed camera controls use the existing sensor contribution contract;
// they do not register a desktop capture/AI runtime or a new product workspace.
export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi]);
export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi,usbCanSensorUi]);
@@ -2,42 +2,51 @@ import {useEffect,useState} from 'react';
export interface MetricDefinition {label:string;group:string;resource:string;unit:string;reason:string|null}
export interface BoardMonitor {
available:boolean;fresh:boolean;storage:string;source_id:string;
available:boolean;fresh:boolean;mode:'live';history_available:false;ttl_seconds:number;
source_id:string|null;
latest:{seq:number;at:number;boot_id:string;values:Record<string,number|null>}|null;
definitions:Record<string,MetricDefinition>;received_at:number;backlog:number;
database_bytes:number|null;database_budget_bytes:number;archive_since:number|null;
start:number;end:number;bucket_seconds:number;
series:{at:number;min:number|null;max:number|null;mean:number|null;count:number}[];
definitions:Record<string,MetricDefinition>;received_at:number|null;
sample_age_seconds:number|null;received_age_seconds:number|null;expires_in_seconds:number;
events:{at:number;code:string;kind:string;locations:string[]}[];
}
export function useBoardMonitor(vehicle:string,metric:string,window:number,end:number|null){
const [value,setValue]=useState<BoardMonitor|null>(null),[error,setError]=useState('');
export function ageBoardMonitor(value:BoardMonitor|null,elapsed:number):BoardMonitor|null {
if(!value)return null;
const age=Math.max(0,elapsed);
if(!value.available||!Number.isFinite(age)||age>=value.expires_in_seconds){
return {...value,available:false,fresh:false,latest:null,definitions:{},events:[],source_id:null,received_at:null,expires_in_seconds:0};
}
return {...value,fresh:value.fresh&&(value.sample_age_seconds??Infinity)+age<10&&(value.received_age_seconds??Infinity)+age<15};
}
export function useBoardMonitor(vehicle:string){
const [snapshot,setSnapshot]=useState<{vehicle:string;value:BoardMonitor;tick:number;wall:number}|null>(null);
const [error,setError]=useState(''),[loading,setLoading]=useState(true),[,setTick]=useState(0);
useEffect(()=>{
let active=true;let pending:AbortController|undefined;let timer:ReturnType<typeof setTimeout>|undefined;
setValue(null);setError('');
setSnapshot(null);setError('');setLoading(true);
// Expiry still reaches the screen when requests fail, hang, or a suspended tab resumes.
const expiry=setInterval(()=>setTick(value=>value+1),1000);
const read=async()=>{
const controller=new AbortController();pending=controller;
const started=performance.now(),wall=Date.now();
const deadline=setTimeout(()=>controller.abort(),12000);
try {
const query=new URLSearchParams({metric,window:String(window),...(end===null?{}:{end:String(end)})});
const response=await fetch(`/api/v1/fleet/${encodeURIComponent(vehicle)}/monitor?${query}`,{credentials:'same-origin',cache:'no-store',signal:controller.signal});
const response=await fetch(`/api/v1/fleet/${encodeURIComponent(vehicle)}/monitor`,{credentials:'same-origin',cache:'no-store',signal:controller.signal});
if(!response.ok)throw new Error('Мониторинг БК недоступен.');
const next=await response.json() as BoardMonitor;
if(active){setValue(next);setError('');}
if(next.mode!=='live'||next.history_available!==false||!Number.isFinite(next.expires_in_seconds)||next.expires_in_seconds<0||next.expires_in_seconds>30)throw new Error('Invalid live monitor contract');
if(active){setSnapshot({vehicle,value:next,tick:started,wall});setError('');}
}catch {if(active)setError('Не удалось обновить мониторинг БК.');}
finally {clearTimeout(deadline);if(active)timer=setTimeout(()=>void read(),5000);}
finally {clearTimeout(deadline);if(active){setLoading(false);timer=setTimeout(()=>void read(),5000);}}
};
void read();return()=>{active=false;pending?.abort();clearTimeout(timer);};
},[vehicle,metric,window,end]);
return {value,error,dismissError:()=>setError('')};
}
export function monitorSeries(value:BoardMonitor,mode:'min'|'max'|'mean') {
const count=Math.ceil((value.end-value.start)/value.bucket_seconds)+1;
const values:Array<number|null>=Array(Math.min(count,302)).fill(null);
const first=Math.floor(value.start/value.bucket_seconds)*value.bucket_seconds;
for(const point of value.series){const index=Math.round((point.at-first)/value.bucket_seconds);if(index>=0&&index<values.length)values[index]=point[mode];}
return values;
void read();return()=>{active=false;pending?.abort();clearTimeout(timer);clearInterval(expiry);};
},[vehicle]);
const current=snapshot?.vehicle===vehicle?snapshot:null;
const elapsed=current?Math.max(performance.now()-current.tick,Date.now()-current.wall)/1000:0;
return {value:ageBoardMonitor(current?.value??null,elapsed),error,loading,dismissError:()=>setError('')};
}
export function monitorValue(value:number|null|undefined,unit=''){
if(value==null||!Number.isFinite(value))return 'Нет измерения';
if(unit==='bytes'||unit==='bytes/s'){
@@ -38,6 +38,10 @@ export function observationTree(layout:ObservationLayout,ids:string[]):DockTree|
const axis=layout.arrangement==='rows'?'y':layout.arrangement==='columns'?'x':depth%2?'y':'x';
return {axis,ratio:layout.splits[JSON.stringify(keys)]??50,first:build(keys.slice(0,mid),depth+1)!,second:build(keys.slice(mid),depth+1)!};
};
if(layout.arrangement==='auto' && !Object.keys(layout.splits).length && ids.includes('telemetry') && ids.length>=3){
const other=ids.filter(id=>id!=='telemetry');
return {axis:'x',ratio:65,first:build(other.slice(0,-1))!,second:{axis:'y',ratio:40,first:{id:'telemetry'},second:{id:other.at(-1)!}}};
}
return build(ids);
}
export function dockObservation(layout:ObservationLayout,ids:string[],move:DockMove):ObservationLayout {
@@ -0,0 +1,48 @@
import {sameConfiguration} from './configurationEquality';
const queues=new Map<string,Promise<unknown>>();
/** A pending save survives unmount. The next mount reads only after its ACK. */
export function observationSerial<T>(key:string,work:()=>Promise<T>):Promise<T>{
const previous=queues.get(key)??Promise.resolve();
const next=previous.catch(()=>{}).then(work);queues.set(key,next);
void next.finally(()=>{if(queues.get(key)===next)queues.delete(key);}).catch(()=>{});
return next;
}
const object=(v:unknown):v is Record<string,unknown>=>v!==null&&typeof v==='object'&&!Array.isArray(v);
/** Three-way merge: unrelated fields survive; arrays and conflicting leaves are atomic. */
export function mergeObservation<T>(base:T,local:T,remote:T):{value:T;conflicts:string[]}{
const conflicts:string[]=[];
function merge(b:unknown,l:unknown,r:unknown,path:string):unknown{
if(sameConfiguration(l,b))return r;
if(sameConfiguration(r,b)||sameConfiguration(l,r))return l;
if(object(b)&&object(l)&&object(r)){
const result:Record<string,unknown>={};
for(const key of new Set([...Object.keys(b),...Object.keys(l),...Object.keys(r)])){
const value=merge(b[key],l[key],r[key],path?path+'.'+key:key);
if(value!==undefined)result[key]=value;
}
return result;
}
conflicts.push(path);return l;
}
return {value:merge(base,local,remote,'') as T,conflicts};
}
export interface ObservationReceipt<T>{revision:number;document:T|null;writable:boolean}
export async function saveObservation<T>(revision:number,base:T,local:T,read:()=>Promise<ObservationReceipt<T>>,write:(revision:number,value:T)=>Promise<ObservationReceipt<T>>,normalize:(value:T|null)=>T){
let payload=local;
for(let attempt=0;attempt<2;attempt++){
try{return {receipt:await write(revision,payload),document:payload};}
catch(error){
// Read after any failed ACK, including timeout. Identity/equality can prove
// an already committed write without retrying it or incrementing revision.
const latest=await read();if(!latest.writable)throw error;
const remote=normalize(latest.document);
if(sameConfiguration(remote,payload))return {receipt:latest,document:remote};
const merged=mergeObservation(base,payload,remote);
if(merged.conflicts.length)throw Error('Раскладка изменена в другом окне. Черновик сохранён: можно загрузить бортовую версию или применить свой черновик.');
if(attempt===1)throw error;
revision=latest.revision;base=remote;payload=merged.value;
}
}
throw Error('Подтверждение сохранения не получено.');
}
@@ -0,0 +1,7 @@
import type {RouterTransport} from '../../../../../packages/router-ui/src/contracts';
import {fleetRequest} from './useFleet';
export function routerTransport(vehicleID:string):RouterTransport{
const base=`/${encodeURIComponent(vehicleID)}/routers`;
return {control:value=>fleetRequest(base+'/control','POST',value),read:()=>fleetRequest(base),authorize:value=>fleetRequest(base+'/access','POST',value),operation:id=>fleetRequest(base+'/access/'+encodeURIComponent(id))};
}
@@ -0,0 +1,38 @@
/** Opt-in bounded queues on the operator host. Never awaited by motor transport. */
type Row=Record<string,unknown>;
export class BrowserEvidence {
id:string|null=null;rows:Row[]=[];busy=false;dropped=0;
constructor(readonly url:string,readonly local=false){}
set(id:string|null){if(this.id!==id){this.rows=[];this.dropped=0;this.id=id;}}
record(event:string,data:Row={}){
if(!this.id)return;
const row={event,browser_ms:performance.now(),...data};
if(JSON.stringify(row).length>2048){this.dropped++;return;}
if(this.rows.length>=256){this.rows.shift();this.dropped++;}
this.rows.push(row);
}
async flush(){
if(this.busy||!this.id||!this.rows.length)return;
const id=this.id,rows=this.rows.splice(0,32);this.busy=true;
try{const r=await fetch(this.url+(this.local?'/diagnostics/local/events':'/diagnostics/events'),{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({id,events:rows}),signal:AbortSignal.timeout(2000),keepalive:true});
if(!r.ok)throw Error('trace');
if(this.local&&(await r.json()).accepted!==true&&id===this.id)this.set(null);
}
catch{if(id===this.id){const pending=[...rows,...this.rows];this.dropped+=Math.max(0,pending.length-256);this.rows=pending.slice(-256);}}
finally{this.busy=false;}
}
}
const sessions=new Map<string,{remote:BrowserEvidence;local:BrowserEvidence;preview:boolean}>();
export function roverDevEvent(url:string,event:string,data:Row={}){try{const pair=sessions.get(url);pair?.remote.record(event,data);pair?.local.record(event,data);}catch{/* No change to input authority. */}}
/** Camera metrics never enter the optional WAN recorder. */
export function roverPreviewEvidence(url:string,sample:Row){try{const pair=sessions.get(url);if(pair?.preview)pair.local.record('preview',{sample});}catch{/* No preview/control side effect. */}}
export function connectRoverEvidence(url:string){
const pair={remote:new BrowserEvidence(url),local:new BrowserEvidence(url,true),preview:true};sessions.set(url,pair);
const timer=setInterval(()=>{for(const e of [pair.remote,pair.local]){if(e.dropped){const dropped=e.dropped;e.dropped=0;e.record('lifecycle',{reason:'browser_queue_gap',dropped});}void e.flush();}},250);
return {set(id:string|null,localID:string|null=null,preview=true){pair.preview=preview;pair.remote.set(id);const changed=pair.local.id!==localID;pair.local.set(localID);if(changed&&localID)pair.local.record('lifecycle',{reason:'local_capture_attached',foreground:roverEvidenceForeground()});},
async flush(){for(const e of [pair.remote,pair.local])for(let n=0;n<9&&e.rows.length;n++){if(e.busy)await new Promise(r=>setTimeout(r,25));else await e.flush();}},
close(){clearInterval(timer);for(const e of [pair.remote,pair.local])void e.flush();if(sessions.get(url)===pair)sessions.delete(url);}};
}
export function roverEvidenceForeground(){try{return typeof document!=='undefined'&&!document.hidden&&document.hasFocus();}catch{return false;}}
@@ -0,0 +1,18 @@
import type {RoverState} from './useRoverControl';
/** Opening a view reads state; only a new failure produces an event toast. */
export class RoverFaultNotice {
private baseline=false;
private key='';
private message='';
update(value:RoverState,ownedSession:string|null):{show?:string;clear?:string}{
if(!value.fresh)return {};
const s=value.snapshot,message=s.state==='fault'?s.message??'':'';
const key=message?JSON.stringify([s.instance,s.session_id,message]):'';
const changed=key!==this.key;
const show=changed&&message&&(this.baseline||!!ownedSession)?message:undefined;
const clear=changed&&this.message?this.message:undefined;
this.baseline=true;this.key=key;this.message=message;
return {show,clear};
}
}
@@ -1,44 +1,53 @@
import {keyDemand,keysFor,type Demand,type RoverMode} from './roverInput';
// The network heartbeat is not evidence that a physical key is still held.
// Allow the initial OS repeat delay, then require continuing keyboard evidence.
export const firstKeyLeaseMs=1000,repeatKeyLeaseMs=300;
// Key state is keydown/keyup, independent of OS autorepeat (which may
// stop for the remaining key after releasing the last key in a chord).
// Focus/visibility revoke input; Core and Node independently expire heartbeat.
export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{
trace?:(event:string,data:Record<string,unknown>)=>void;
held:(keys:Set<string>)=>void;demand:(value:Demand)=>void;pause:()=>void;stop:()=>void;
},now:()=>number=()=>performance.now()){
}){
const doc=scope.ownerDocument,win=doc.defaultView!;
const keyboard=new Set<string>(),pointers=new Map<number,string>();
let deadline=0,closed=false,suspended=false;
const clear=()=>{keyboard.clear();pointers.clear();deadline=0;callbacks.held(new Set());};
const pause=()=>{if(closed||suspended)return;suspended=true;clear();callbacks.pause();};
const stop=()=>{if(closed)return;closed=true;clear();callbacks.stop();};
const focused=()=>!doc.hidden&&doc.hasFocus()&&scope.contains(doc.activeElement);
let closed=false,suspended=false;
const trace=(event:string,data:Record<string,unknown>={})=>{try{callbacks.trace?.(event,{mode,held:[...keyboard,...pointers.values()],...data});}catch{}};
const clear=()=>{keyboard.clear();pointers.clear();callbacks.held(new Set());};
const pause=(reason:unknown="contextmenu")=>{if(closed||suspended)return;trace("pause",{reason:typeof reason==="string"?reason:"contextmenu"});suspended=true;clear();callbacks.pause();};
const stop=()=>{if(closed)return;trace("stop",{reason:"operator_or_pagehide"});closed=true;clear();callbacks.stop();};
// Armed authority belongs to the visible observation center, not one canvas.
// Modal focus returns to its header Play button; browser chrome can return it
// to body. Neither should require a canvas click before a NEW physical press.
const editable='input,textarea,select,[contenteditable]:not([contenteditable="false"]),[role=dialog],[role=listbox],[role=menu]';
const focused=()=>!doc.hidden&&doc.hasFocus()
&&(scope.contains(doc.activeElement)||doc.activeElement===doc.body)
&&!doc.activeElement?.closest(editable)&&!doc.querySelector('[role=dialog],[role=listbox],[role=menu]');
const valid=()=>{
if(closed)return false;
if(!focused()||(keyboard.size>0&&now()>=deadline)){pause();return false;}
if(!focused()){pause("focus_lost");return false;}
return true;
};
const publish=()=>{const held=new Set([...keyboard,...pointers.values()]);callbacks.held(held);callbacks.demand(keyDemand(mode,held));};
const down=(e:KeyboardEvent)=>{
if(!e.isTrusted||closed)return;
if(keysFor(mode).includes(e.code)||e.code==='Space'||e.code==='Escape')trace('key_down',{code:e.code,repeat:e.repeat});
if(e.code==='Space'||e.code==='Escape'){e.preventDefault();stop();return;}
if(e.altKey||e.ctrlKey||e.metaKey){pause();return;}
if(!keysFor(mode).includes(e.code)||!valid())return;
if((e.target as HTMLElement)?.closest('input,textarea,select,[role=dialog],[role=listbox]')){pause();return;}
if((e.target as HTMLElement)?.closest(editable)){pause();return;}
// A repeat delivered after focus returns cannot become a fresh press.
if(e.repeat&&!keyboard.has(e.code))return;
e.preventDefault();suspended=false;keyboard.add(e.code);
deadline=now()+(e.repeat?repeatKeyLeaseMs:firstKeyLeaseMs);publish();
publish();
};
const up=(e:KeyboardEvent)=>{
if(!e.isTrusted||closed||!keyboard.delete(e.code))return;
e.preventDefault();if(!keyboard.size)deadline=0;publish();
trace("key_up",{code:e.code});e.preventDefault();publish();
};
const blur=(e:Event)=>{if(e.target===win)pause();};
const blur=(e:Event)=>{if(e.target===win)pause("window_blur");};
const focusOut=(e:FocusEvent)=>{if(scope.contains(e.target as Node)&&!scope.contains(e.relatedTarget as Node|null))pause();};
const focusIn=()=>{if(!focused())pause();};
const hidden=()=>{if(doc.hidden)pause();};
const outside=(e:Event)=>{if(!scope.contains(e.target as Node))pause();};
const hidden=()=>{if(doc.hidden)pause("page_hidden");};
const outside=(e:Event)=>{if(!scope.contains(e.target as Node))pause("outside_pointer");};
const pointerUp=(e:PointerEvent)=>{if(!closed&&pointers.delete(e.pointerId))publish();};
const pointerCancel=(e:PointerEvent)=>{if(pointers.has(e.pointerId))pause();};
win.addEventListener('keydown',down,true);win.addEventListener('keyup',up,true);
@@ -50,11 +59,11 @@ export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{
const timer=win.setInterval(valid,50);
return {
valid,
pointerDown(id:number,code:string){if(valid()){suspended=false;pointers.set(id,code);publish();}},
pointerDown(id:number,code:string){if(valid()){trace("pointer_down",{code});suspended=false;pointers.set(id,code);publish();}},
pointerUp(id:number){if(!closed&&pointers.delete(id))publish();},
pointerCancel(id:number){if(pointers.has(id))pause();},
pointerCancel(id:number){if(pointers.has(id)){trace("pointer_cancel");pause("pointer_cancel");}},
dispose(){
closed=true;clear();callbacks.demand({left:0,right:0});win.clearInterval(timer);
trace("lifecycle",{reason:"input_disposed"});closed=true;clear();callbacks.demand({left:0,right:0});win.clearInterval(timer);
win.removeEventListener('keydown',down,true);win.removeEventListener('keyup',up,true);
win.removeEventListener('blur',blur,true);win.removeEventListener('pagehide',stop);
doc.removeEventListener('focusout',focusOut,true);doc.removeEventListener('focusin',focusIn,true);
@@ -8,13 +8,25 @@ export function keyDemand(mode:RoverMode,held:ReadonlySet<string>):Demand {
const scale=Math.max(1,Math.abs(forward)+Math.abs(turn));
return {left:(forward+turn)/scale,right:(forward-turn)/scale};
}
export const defaultRoverSettings={version:1,mode:'arcade' as RoverMode,currentA:30,maxErpm:2000,model:''};
export const defaultRoverSettings={version:3,mode:'arcade' as RoverMode,currentA:30,maxErpm:2000,throttlePercent:10,model:''};
export function roverSettings(value:unknown):typeof defaultRoverSettings {
const v=value as Partial<typeof defaultRoverSettings>|null;
return {...defaultRoverSettings,...(v?.version===1?{
return {...defaultRoverSettings,...(v?.version===1||v?.version===2||v?.version===3?{
mode:v.mode==='tank'?'tank':'arcade',
currentA:typeof v.currentA==='number'&&Number.isFinite(v.currentA)?Math.max(.5,Math.min(30,v.currentA)):30,
// Legacy forms persisted an empty field as 0, then clamped it to .5.
// Repair that legacy floor once; v3 keeps an explicitly chosen .5 A.
currentA:typeof v.currentA==='number'&&Number.isFinite(v.currentA)&&v.currentA>=.5&&!(v.version!==3&&v.currentA===.5)?v.currentA:30,
maxErpm:typeof v.maxErpm==='number'&&Number.isFinite(v.maxErpm)?Math.max(300,Math.min(3000,v.maxErpm)):2000,
// ERPM has no trustworthy conversion to throttle. Migrate at 10%, never
// reinterpret an old saved number as a percentage or full throttle.
throttlePercent:v.version!==1&&typeof v.throttlePercent==='number'&&Number.isFinite(v.throttlePercent)?Math.max(1,Math.min(100,v.throttlePercent)):10,
model:v.model==='dcd006-v020'?v.model:'',
}:{} )};
}
export const roverNumberInput=(value:string)=>value.trim()===''?Number.NaN:Number(value);
export function persistableRoverSettings(v:typeof defaultRoverSettings){
return Number.isFinite(v.currentA)&&v.currentA>=.5
&&Number.isFinite(v.throttlePercent)&&v.throttlePercent>=1&&v.throttlePercent<=100
&&Number.isFinite(v.maxErpm)&&v.maxErpm>=300&&v.maxErpm<=3000;
}
@@ -0,0 +1,16 @@
/** Stream the complete onboard snapshot to the operator's chosen file. */
import {transferRoverLog} from './roverLogTransfer';
type SaveWindow=Window&{showSaveFilePicker?:(options:unknown)=>Promise<FileSystemFileHandle>};
export async function saveRoverLog(url:string,name:string){
const picker=(window as SaveWindow).showSaveFilePicker;
if(!picker){
// Native download remains a streaming fallback; the browser owns its save UI.
const a=document.createElement('a');a.href=url+'/diagnostics/export';a.download=name;a.click();return;
}
const handle=await picker.call(window,{suggestedName:name,types:[{description:'Лог сессии JSONL',accept:{'application/x-ndjson':['.jsonl']}}]});
const writable=await handle.createWritable();
try{
await transferRoverLog(url,data=>writable.write(data));
await writable.close();
}catch(error){await writable.abort().catch(()=>{});throw error;}
}
@@ -0,0 +1,62 @@
/** Bounded transfer of an immutable onboard snapshot over the existing HTTP API. */
export type LogCursor={capture_id:string;total_bytes:number;snapshot:string;offset:number};
const MAX_LINE=100*1024;
const failure=()=>new Error('Не удалось проверить файл с борта. Повторите сохранение.');
export async function readLogBlocks(response:Response,cursor:LogCursor|undefined,write:(data:Uint8Array<ArrayBuffer>)=>Promise<void>,confirmed:(value:LogCursor)=>void){
if(!response.body)throw failure();
const reader=response.body.getReader(),decoder=new TextDecoder('utf-8',{fatal:true});
let pending='',complete=false;
try{
while(true){
const {done,value}=await reader.read();
if(done){if(pending||!complete)throw failure();return;}
// Split before decoding so even an unexpectedly large HTTP read cannot create
// an unbounded accumulated string. Only a single export block is retained.
for(let start=0;start<value.length;start+=8192){
pending+=decoder.decode(value.subarray(start,start+8192),{stream:true});
let end:number;
while((end=pending.indexOf('\n'))>=0){
if(end>MAX_LINE||complete)throw failure();
const row=JSON.parse(pending.slice(0,end));pending=pending.slice(end+1);
if(!/^[a-f0-9]{32}$/.test(row.capture_id)||!/^[a-f0-9]{64}$/.test(row.snapshot)||!/^[a-f0-9]{64}$/.test(row.sha256)
||![row.offset,row.next,row.total_bytes].every(Number.isSafeInteger)
||row.offset<0||row.next<row.offset||row.next>row.total_bytes
||typeof row.data!=='string'||row.data.length>87384)throw failure();
if(cursor?(row.capture_id!==cursor.capture_id||row.snapshot!==cursor.snapshot||row.total_bytes!==cursor.total_bytes||row.offset!==cursor.offset):row.offset!==0)throw failure();
const raw=Uint8Array.from(atob(row.data),c=>c.charCodeAt(0));
if(raw.length>65536||raw.length!==row.next-row.offset||(!raw.length&&row.next!==row.total_bytes))throw failure();
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',raw)),n=>n.toString(16).padStart(2,'0')).join('');
if(digest!==row.sha256)throw failure();
await write(raw);
cursor={capture_id:row.capture_id,total_bytes:row.total_bytes,snapshot:row.snapshot,offset:row.next};
confirmed(cursor);complete=cursor.offset===cursor.total_bytes;
}
if(pending.length>MAX_LINE)throw failure();
}
}
}finally{await reader.cancel().catch(()=>{});reader.releaseLock();}
}
export async function transferRoverLog(url:string,write:(data:Uint8Array<ArrayBuffer>)=>Promise<void>){
let cursor:LogCursor|undefined;
for(let attempt=0;attempt<4;attempt++){
const params=new URLSearchParams({format:'chunks'});
if(cursor)for(const [key,value] of Object.entries(cursor))params.set(key,String(value));
const controller=new AbortController();
let timer:ReturnType<typeof setTimeout>;
const reset=()=>{clearTimeout(timer);timer=setTimeout(()=>controller.abort(),130000);};
reset();
try{
const response=await fetch(url+'/diagnostics/export?'+params,{signal:controller.signal});
if(!response.ok)throw new Error('Не удалось получить файл с борта. Проверьте связь и повторите сохранение.');
await readLogBlocks(response,cursor,write,value=>{cursor=value;reset();});
return;
}catch(error){
if(attempt===3)throw error;
// No session-duration limit. Retry only a failed download, retaining the
// exact snapshot and the last verified, successfully written offset.
await new Promise(resolve=>setTimeout(resolve,1000*(attempt+1)));
}finally{clearTimeout(timer!);controller.abort();}
}
}
@@ -0,0 +1,21 @@
import type {RoverConnection} from './roverTransport';
import type {RoverState} from './useRoverControl';
export interface RoverObservationStatus {label:string|null;pulse:boolean}
/** Presentation only. A fresh driver snapshot owns its attachment lifecycle;
* inventory and elapsed UI time cannot establish readiness or motor authority. */
export function roverObservationStatus(state:RoverState,connection:RoverConnection):RoverObservationStatus{
const pending=(label:string)=>({label,pulse:true});
if(connection==='connecting')return pending('Подключение к Mission Core');
if(connection!=='connected')return pending('Восстановление связи с Mission Core');
if(!state.fresh)return pending('Ожидание телеметрии с борта');
const snapshot=state.snapshot;
if(!snapshot.supported)return {label:'Служба управления на борту недоступна',pulse:false};
if(snapshot.message||snapshot.state==='fault')return {label:null,pulse:false};
const readings=snapshot.devices??[],expected=Object.values(snapshot.profile?.bindings??{});
const missing=expected.filter(b=>!readings.some(d=>d.id===b.device_id&&d.uuid===b.uuid));
const initializing=snapshot.observation?.initializing_devices??[];
if(initializing.length&&(missing.length?missing.every(b=>initializing.includes(b.device_id)):!expected.length&&!readings.length))return pending('Инициализация VESC');
if(missing.length||!readings.length||readings.some(d=>!Number.isFinite(d.age_ms)||d.age_ms<0||d.age_ms>=1000))return pending('Ожидание свежих показаний VESC');
return {label:null,pulse:false};
}
@@ -0,0 +1,12 @@
/** Bounded local diagnostic download. No request to the board or motion API. */
export async function saveOperatorCapture(url:string,id:string,beforeSnapshot:()=>Promise<void>=async()=>{}){
if(!/^[a-f0-9]{32}$/.test(id))throw Error('Запись изменилась.');
await beforeSnapshot();
const response=await fetch(url+'/diagnostics/local/export?capture_id='+id,{cache:'no-store',signal:AbortSignal.timeout(5000)});
if(!response.ok)throw Error('Не удалось выгрузить замер компьютера. Запись сохранена в Core.');
const blob=await response.blob();if(blob.size>4*1024*1024)throw Error('Размер замера превышает допустимый.');
// The bounded snapshot uses the browser's normal download flow, including fullscreen.
const href=URL.createObjectURL(blob),a=document.createElement('a');
try{a.href=href;a.download=`rover-operator-${id}.jsonl`;document.body.append(a);a.click();}
finally{a.remove();setTimeout(()=>URL.revokeObjectURL(href),1000);}
}
@@ -0,0 +1,84 @@
import type {RoverState} from './useRoverControl';
export interface RoverArmSettings {currentA:number;speed:number;mode:'rpm'|'duty'}
const MAX_RETRY_BACKOFF=3;
const STABLE_CONNECTION_MS=30000;
const MAX_READY_OBSERVATION_GAP_MS=1000;
const profileKey=(s:RoverState['snapshot'])=>JSON.stringify(s.profile??null);
const motorKey=(s:RoverState['snapshot'])=>(s.devices??[]).map(d=>d.uuid+'@'+(d.session_id??'')).sort().join(':');
// Reacquire a NEW neutral lease after transport loss. Never revive an expired
// lease or remember motion. Explicit Stop, hardware faults and RC takeover end
// the operator's request; navigation/reload never persists it.
export class RoverRecovery {
private request:{settings:RoverArmSettings;instance:string;profile:string;motors:string;previousSession:string|null|undefined}|null=null;
private pendingSession:string|null=null;
private quietSince:number|null=null;
private retryAt=0;
private attempts=0;
private readySince:number|null=null;
private lastReadyAt:number|null=null;
private retiredSession:string|null=null;
waiting=false;
remember(settings:RoverArmSettings,value:RoverState){
this.clear();
if(value.fresh&&value.snapshot.instance&&value.snapshot.devices?.length&&value.snapshot.devices.every(d=>d.session_id))this.request={settings:{...settings},instance:value.snapshot.instance,profile:profileKey(value.snapshot),motors:motorKey(value.snapshot),previousSession:value.snapshot.session_id};
}
clear(){this.request=null;this.waiting=false;this.quietSince=null;this.attempts=0;this.retryAt=0;this.retiredSession=null;this.pendingSession=null;this.readySince=null;this.lastReadyAt=null;}
started(session:string){if(!this.waiting)this.pendingSession=session;}
previousStatus(value:RoverState,ownedSession:string|null){
// An explicit new arm acknowledges the previous terminal session. Core may
// still expose that snapshot until the board receives the new neutral lease.
return !!this.request&&!!ownedSession&&ownedSession===this.pendingSession&&!this.waiting
&&value.fresh&&value.controlling&&value.snapshot.session_id===this.request.previousSession
&&value.snapshot.session_id!==ownedSession&&['fault','stopped','receiver','observing'].includes(value.snapshot.state??'');
}
connected(now:number){
this.waiting=false;this.quietSince=null;this.pendingSession=null;
// One ready snapshot is not a recovered link. Require continuous fresh
// observations before forgiving repeated automatic rearm attempts.
if(this.lastReadyAt===null||now<this.lastReadyAt||now-this.lastReadyAt>MAX_READY_OBSERVATION_GAP_MS)this.readySince=now;
this.lastReadyAt=now;this.readySince??=now;
if(now-this.readySince>=STABLE_CONNECTION_MS){this.attempts=0;this.retryAt=0;}
}
interrupt(now:number,session:string|null){
if(!this.request)return false;
this.readySince=null;this.lastReadyAt=null;
if(!this.waiting){this.retryAt=Math.max(this.retryAt,now+500);this.quietSince=null;}
this.retiredSession=session??this.retiredSession;this.waiting=true;this.pendingSession=null;return true;
}
blocker(value:RoverState,ownedSession:string|null=null){
if(!this.request||!value.fresh)return null;
const s=value.snapshot;
if(s.instance!==this.request.instance)return 'Борт перезапустился. Проверьте состояние и включите управление.';
if(motorKey(s)!==this.request.motors)return 'Подключение VESC изменилось. Проверьте состояние и включите управление.';
if(profileKey(s)!==this.request.profile)return 'Назначение моторов изменилось. Проверьте настройки управления.';
if(s.supported!==true||(this.request.settings.mode==='duty'&&!s.control_modes?.includes('duty')))return 'Режим управления на борту изменился.';
if(s.session_id===ownedSession)this.pendingSession=null;
if(this.previousStatus(value,ownedSession))return null;
const ended=s.last_stop;
if(ended?.state==='fault'&&(ended.session_id===ownedSession||ended.session_id===this.retiredSession))return ended.message||'Предыдущий сеанс завершился с ошибкой. Включите управление заново.';
// Stopping is an interlock, not a terminal cancellation. The board may need
// fresh passive samples to verify release. next() still requires confirmed
// stopped state; a hardware fault (including historical fault) still blocks.
if(s.state==='fault'||(s.release_confirmed===false&&s.state!=='stopping'))return s.message||'Борт сообщил об ошибке. Проверьте состояние перед включением.';
if(s.state==='receiver')return 'Управление передано пульту.';
if(this.waiting&&value.controlling&&s.session_id&&s.session_id!==this.retiredSession&&s.session_id!==ownedSession)return 'Управление включено в другом окне.';
return null;
}
next(value:RoverState,now:number,focused:boolean):RoverArmSettings|null{
if(!this.waiting||!this.request)return null;
if(this.blocker(value)){this.clear();return null;}
const s=value.snapshot,devices=s.devices??[];
const quiet=value.fresh&&!value.controlling&&s.state==='stopped'&&s.release_confirmed===true
&&motorKey(s)===this.request.motors&&devices.length>0&&devices.every(d=>Number.isFinite(d.age_ms)&&d.age_ms>=0&&d.age_ms<=500
&&Number.isFinite(d.values.erpm)&&Math.abs(d.values.erpm)<60&&d.values.fault_code===0);
if(!focused||!quiet){this.quietSince=null;return null;}
this.quietSince??=now;
if(now-this.quietSince<500||now<this.retryAt)return null;
// Transport loss retains the operator request; only retry rate is bounded.
// Saturate the exponent so a long outage cannot grow an attempt counter.
this.retryAt=now+1000*2**this.attempts;this.attempts=Math.min(this.attempts+1,MAX_RETRY_BACKOFF);this.quietSince=null;
return {...this.request.settings};
}
}
@@ -0,0 +1,36 @@
/** Bounded, volatile engineering evidence. Never participates in control decisions. */
export class RoverTiming {
private lastTick:number|null=null;
private events:Record<string,string|number|boolean>[]=[];
private started=performance.now();
private tickGap=0;
private requestMS=0;
private samples=0;
private staleSamples=0;
private hadFresh=false;
view(fresh:boolean){this.samples++;if(fresh)this.hadFresh=true;else if(this.hadFresh)this.staleSamples++;this.publish();}
private event(value:Record<string,string|number|boolean>){
this.events.push({at_ms:Math.round(performance.now()-this.started),...value});this.events=this.events.slice(-16);
}
tick(active:boolean){
const now=performance.now();this.tickGap=this.lastTick===null?0:Math.round(now-this.lastTick);this.lastTick=now;
if(this.tickGap>=200)this.event({kind:'heartbeat-gap',gap_ms:this.tickGap,active,hidden:document.hidden,focused:document.hasFocus()});
this.publish();
}
request(kind:'view'|'arm'|'command',started:number,outcome:'ok'|'http'|'transport',url?:string){
this.requestMS=Math.round(performance.now()-started);
let network:Record<string,number>={};
try{if(url&&typeof performance.getEntriesByName==='function'){
const entry=performance.getEntriesByName(new URL(url,window.location.href).href,'resource').at(-1) as PerformanceResourceTiming|undefined;
if(entry&&entry.startTime>=started-1&&entry.requestStart>0)network={browser_wait_ms:Math.round(entry.requestStart-entry.fetchStart),response_wait_ms:Math.round(entry.responseStart-entry.requestStart),body_ms:Math.round(entry.responseEnd-entry.responseStart)};
}}catch{/* Diagnostics cannot interfere with a command. */}
if(this.requestMS>=200||outcome!=='ok')this.event({kind,outcome,duration_ms:this.requestMS,hidden:document.hidden,focused:document.hasFocus(),...network});
this.publish();
}
private publish(){
// One replaceable DOM diagnostic record; no telemetry archive or product control.
if(document.documentElement)document.documentElement.dataset.roverTiming=JSON.stringify({sampled_at_ms:Math.round(performance.now()),tick_gap_ms:this.tickGap,request_ms:this.requestMS,state_samples:this.samples,stale_after_fresh:this.staleSamples,events:this.events});
}
clear(){this.lastTick=null;this.events=[];this.samples=0;this.staleSamples=0;this.hadFresh=false;this.started=performance.now();if(document.documentElement)delete document.documentElement.dataset.roverTiming;}
}
export const roverTiming=new RoverTiming();
@@ -0,0 +1,107 @@
import {roverDevEvent,roverEvidenceForeground} from './roverDevEvents';
/** Separate socket from HTTP asset/SSE queues. No queued or replayed commands. */
export class RoverHttpError extends Error {constructor(message:string,readonly status:number){super(message);}}
export type RoverConnection='connecting'|'connected'|'reconnecting'|'closed';
type Pending={resolve:(value:any)=>void;reject:(reason:Error)=>void;timer:ReturnType<typeof setTimeout>};
export class RoverTransport {
private socket:WebSocket|null=null;
private latest:unknown;
private seen=-Infinity;
private clock=0;
private clockAt=0;
private next=0;
private socketID='';
private lastSent:number|null=null;
private pending=new Map<number,Pending>();
private waiting=new Set<Pending>();
private retry:ReturnType<typeof setTimeout>|undefined;
private closed=false;
private watchdog:ReturnType<typeof setTimeout>|undefined;
private failures=0;
private received=false;
connection():RoverConnection{return this.closed?'closed':performance.now()-this.seen<600?'connected':this.received||this.failures>0?'reconnecting':'connecting';}
private touch(socket:WebSocket){
clearTimeout(this.watchdog);
this.watchdog=setTimeout(()=>this.disconnect(socket,"watchdog"),1500);
}
private disconnect(socket:WebSocket,reason:string){
if(this.socket!==socket)return;
roverDevEvent(this.url,"transport",{reason,ready_state:socket.readyState,buffered_bytes:socket.bufferedAmount,pending:this.pending.size});
this.socket=null;this.seen=-Infinity;clearTimeout(this.watchdog);this.fail();
// Retire locally even when the browser never emits a close event.
socket.onopen=socket.onmessage=socket.onclose=socket.onerror=null;socket.close();
if(!this.closed)this.retry=setTimeout(()=>this.connect(),Math.min(250*2**Math.min(this.failures++,4),4000));
}
constructor(private url:string,private create:(url:string)=>WebSocket=url=>new WebSocket(url)){this.connect();}
private connect(){
if(this.closed)return;
const url=new URL(this.url+'-channel',window.location.href);url.protocol=url.protocol==='https:'?'wss:':'ws:';
const socket=this.create(url.href);this.socket=socket;this.socketID='';this.lastSent=null;
// A browser handshake owns no motion authority. Do not repeatedly cancel a
// cold connection with the live-state deadline before it can open. Once open,
// the original watchdog and all sample/command deadlines still apply.
clearTimeout(this.watchdog);
this.watchdog=setTimeout(()=>this.disconnect(socket,'connect_timeout'),10000);
socket.onopen=()=>{if(this.socket===socket)this.touch(socket);};
if(socket.readyState===1)this.touch(socket);
socket.onmessage=event=>{
if(this.socket!==socket)return;
try{const value=JSON.parse(event.data);
if(typeof value.socket_id==='string')this.socketID=value.socket_id;
if(value.type==='reply')roverDevEvent(this.url,'transport',{reason:'reply_received',request_id:value.id,socket_id:this.socketID,clock_ms:value.clock_ms,outcome:String(value.status??200)});
if(value.type==='state'&&Number.isFinite(value.clock_ms)){
this.received=true;this.latest=value.value;this.seen=performance.now();this.clock=value.clock_ms;this.clockAt=this.seen;this.failures=0;this.touch(socket);
for(const p of this.waiting){clearTimeout(p.timer);p.resolve(this.latest);}this.waiting.clear();
}else if(value.type==='reply'){
const p=this.pending.get(value.id);if(!p)return;this.pending.delete(value.id);clearTimeout(p.timer);
if(value.state&&Number.isFinite(value.clock_ms)){
this.latest=value.state;this.seen=performance.now();this.clock=value.clock_ms;this.clockAt=this.seen;this.failures=0;this.touch(socket);
for(const waiter of this.waiting){clearTimeout(waiter.timer);waiter.resolve(this.latest);}this.waiting.clear();
}
if(value.error)roverDevEvent(this.url,'transport',{reason:'reply_rejected',outcome:String(value.status??409)});
if(value.error)p.reject(new RoverHttpError(value.error,value.status??409));else p.resolve(value.value);
}
}catch{/* Invalid frames never acknowledge a request. */}
};
socket.onclose=event=>{roverDevEvent(this.url,"transport",{reason:"close",close_code:event?.code});this.disconnect(socket,"close");};
socket.onerror=()=>this.disconnect(socket,"error");
}
private fail(){
for(const p of [...this.pending.values(),...this.waiting]){clearTimeout(p.timer);p.reject(new Error('Канал управления недоступен.'));}
this.pending.clear();this.waiting.clear();
}
view():Promise<unknown>{
if(this.closed)return Promise.reject(new Error('Канал управления недоступен.'));
if(performance.now()-this.seen<600)return Promise.resolve(this.latest);
return new Promise((resolve,reject)=>{const p:Pending={resolve,reject,timer:setTimeout(()=>{this.waiting.delete(p);reject(new Error('Нет свежих данных с борта.'));},1000)};this.waiting.add(p);});
}
command(action:'arm'|'command'|'hold',body:unknown):Promise<unknown>{
const socket=this.socket,now=performance.now();
if(!socket||socket.readyState!==1||socket.bufferedAmount>4096||now-this.seen>=600||this.pending.size>=4)return Promise.reject(new Error('Канал управления недоступен.'));
const id=++this.next;
return new Promise((resolve,reject)=>{
this.pending.set(id,{resolve,reject,timer:setTimeout(()=>{this.pending.delete(id);roverDevEvent(this.url,'transport',{reason:'ack_timeout',action,request_id:id,socket_id:this.socketID});reject(new Error('Команда не подтверждена.'));},350)});
try{
const expires=this.clock+(now-this.clockAt)+400;
const fields=body&&typeof body==='object'?body as Record<string,unknown>:{};
roverDevEvent(this.url,'request',{reason:'socket_send',request_id:id,socket_id:this.socketID,action,
session_id:fields.session_id,sequence:fields.sequence,expires_ms:expires,state_age_ms:now-this.seen,
gap_ms:this.lastSent===null?0:now-this.lastSent,foreground:roverEvidenceForeground()});
socket.send(JSON.stringify({id,action,body,expires_ms:expires}));this.lastSent=now;
}
catch{const p=this.pending.get(id);if(p){clearTimeout(p.timer);this.pending.delete(id);}reject(new Error('Канал управления недоступен.'));}
});
}
close(){this.closed=true;clearTimeout(this.retry);clearTimeout(this.watchdog);const socket=this.socket;this.socket=null;this.seen=-Infinity;this.fail();socket?.close();}
}
const clients=new Map<string,{transport:RoverTransport;users:number}>();
export function retainRoverTransport(url:string){
let entry=clients.get(url);if(!entry){entry={transport:new RoverTransport(url),users:0};clients.set(url,entry);}entry.users++;
return()=>{if(--entry!.users===0){entry!.transport.close();clients.delete(url);}};
}
export function roverRequest<T>(url:string,body?:unknown):Promise<T>{
const action=url.endsWith('/arm')?'arm':url.endsWith('/hold')?'hold':'command',base=body?url.slice(0,url.lastIndexOf('/')):url,client=clients.get(base);
if(!client)return Promise.reject(new Error('Канал управления недоступен.'));
return (body?client.transport.command(action,body):client.transport.view()) as Promise<T>;
}
export function roverConnection(url:string):RoverConnection{return clients.get(url)?.transport.connection()??'closed';}
@@ -1,17 +1,23 @@
import type {SensorInventory, SensorTransport} from '../../../../../packages/sensor-ui/src/contracts';
import type {SensorInventory, SensorTransport, SensorLiveFrame} from '../../../../../packages/sensor-ui/src/contracts';
import {fleetRequest} from './useFleet';
import {roverPreviewEvidence} from './roverDevEvents';
export function createFleetSensorTransport(vehicleID:string):SensorTransport {
const path=`/${encodeURIComponent(vehicleID)}/devices`;
const inventory=(fleet:{items:{id:string;connectivity:string;enrollment:string;sensor_state:SensorInventory}[]})=>{
const inventory=(fleet:{items:{id:string;core_endpoint?:string;connectivity:string;enrollment:string;inventory_fresh?:boolean;sensor_state:SensorInventory}[]})=>{
const value=fleet.items.find(v=>v.id===vehicleID);
if(!value)throw new Error('Аппарат не найден.');
return {...value.sensor_state,fresh:value.connectivity==='online'&&value.enrollment==='paired'};
return {...value.sensor_state,items:value.sensor_state.items.map(item=>({...item,transport_generation:value.core_endpoint})),fresh:value.connectivity==='online'&&value.enrollment==='paired'&&value.inventory_fresh!==false};
};
return {
previewEvidence:sample=>roverPreviewEvidence(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,sample),
liveTelemetry:async signal=>{
const value=await fleetRequest<{fresh:boolean;snapshot:Omit<SensorLiveFrame,'fresh'>}>(`/${encodeURIComponent(vehicleID)}/rover`,'GET',undefined,1200,signal);
return {...value.snapshot,fresh:value.fresh};
},
configurationArchive:{list:(device,before)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations${before?'?before='+encodeURIComponent(before):''}`),read:(device,version)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations/${encodeURIComponent(version)}`)},
enrollment:{state:()=>fleetRequest(`${path}/enrollment`),submit:value=>fleetRequest(`${path}/enrollment/operations`,'POST',value),operation:id=>fleetRequest(`${path}/enrollment/operations/${encodeURIComponent(id)}`)},
inventory:async()=>inventory(await fleetRequest()),
inventory:async signal=>inventory(await fleetRequest('','GET',undefined,12000,signal)),
subscribe:(receive,unavailable)=>{const events=new EventSource('/api/v1/fleet/events');events.onmessage=e=>{try{receive(inventory(JSON.parse(e.data)));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},
submit:value=>fleetRequest(`${path}/operations`,'POST',value),
operation:id=>fleetRequest(`${path}/operations/${encodeURIComponent(id)}`),
@@ -0,0 +1,35 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {fleetRequest} from './useFleet';
export type NetworkProvider='tailscale'|'wireguard';
export interface SharedNetworkProfile {id:string;name:string;endpoint:string;state:string;boards:number}
export interface BoardNetworkView {
profiles:SharedNetworkProfile[];available:boolean;
node:{provider:NetworkProvider;server_id?:string;revision:number;phase:string;error?:string;tailscale_endpoint?:string}|null;
operation:{id:string;state:string;error?:string}|null;
}
export function useBoardNetwork(vehicleId:string){
const [value,setValue]=useState<BoardNetworkView|null>(null),[provider,setProvider]=useState<NetworkProvider>('tailscale'),[profileId,setProfileId]=useState('');
const [error,setError]=useState(''),[busy,setBusy]=useState(false);
const revision=useRef<number|null>(null);
const accept=useCallback((next:BoardNetworkView)=>{
setValue(next);
if(next.node&&revision.current!==next.node.revision){revision.current=next.node.revision;setProvider(next.node.provider);setProfileId(next.node.server_id||'');}
},[]);
const refresh=useCallback(async()=>{const next=await fleetRequest<BoardNetworkView>(`/${encodeURIComponent(vehicleId)}/network-profile`);accept(next);return next;},[vehicleId,accept]);
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;const controller=new AbortController();
const poll=async()=>{try{const next=await fleetRequest<BoardNetworkView>(`/${encodeURIComponent(vehicleId)}/network-profile`,'GET',undefined,12000,controller.signal);if(active)accept(next);}catch(e){if(active){setError(e instanceof Error?e.message:'Состояние подключения недоступно.');setValue(current=>current?{...current,available:false}:null);}}finally{if(active)timer=setTimeout(poll,2000);}};
revision.current=null;void poll();return()=>{active=false;controller.abort();clearTimeout(timer);};
},[vehicleId,accept]);
const importing=async(file:File)=>{if(busy)return;setBusy(true);setError('');try{
if(file.size>16384)throw Error('Выберите файл подключения, созданный установщиком VPS.');
const item=await fleetRequest<SharedNetworkProfile>('/network-profiles/import','POST',{document:await file.text()},240000);
await refresh();setProvider('wireguard');setProfileId(item.id);
}catch(e){setError(e instanceof Error?e.message:'Файл не удалось импортировать.');}finally{setBusy(false);}};
const applying=value?.operation?.state==='applying'||value?.operation?.state==='rolling_back';
const dirty=Boolean(value?.node&&(provider!==value.node.provider||(provider==='wireguard'&&profileId!==value.node.server_id)));
const save=async()=>{if(!value?.node||busy||applying)return;setBusy(true);setError('');try{
await fleetRequest(`/${encodeURIComponent(vehicleId)}/network-profile`,'PUT',{provider,profile_id:provider==='wireguard'?profileId:null,expected_revision:value.node.revision});await refresh();
}catch(e){setError(e instanceof Error?e.message:'Подключение не применено.');}finally{setBusy(false);}};
return {value,provider,setProvider,profileId,setProfileId,error,busy,applying,dirty,importing,save,
canSave:Boolean(value?.available&&dirty&&!busy&&!applying&&(provider==='tailscale'?value.node?.tailscale_endpoint:profileId))};
}
@@ -16,11 +16,11 @@ export interface FleetPreview {
preview_id: string; node_id: string; name: string; host: BoardHost;
endpoint: string; expires_at: number;
}
export async function fleetRequest<T>(path = "", method = "GET", body?: unknown, timeoutMs = 12000): Promise<T> {
export async function fleetRequest<T>(path = "", method = "GET", body?: unknown, timeoutMs = 12000, signal?:AbortSignal): Promise<T> {
const response = await fetch(`/api/v1/fleet${path}`, {
method, credentials: "same-origin", cache: "no-store",
headers: body === undefined ? {} : { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs),
body: body === undefined ? undefined : JSON.stringify(body), signal: signal?AbortSignal.any([signal,AbortSignal.timeout(timeoutMs)]):AbortSignal.timeout(timeoutMs),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
@@ -1,79 +1,139 @@
import {roverDevEvent} from './roverDevEvents';
import {useCallback,useEffect,useRef,useState} from 'react';
import type {Demand} from './roverInput';
import {RoverRecovery,type RoverArmSettings} from './roverRecovery';
import {RoverFaultNotice} from './roverFaultNotice';
import {roverTiming} from './roverTiming';
import {retainRoverTransport,roverRequest,roverConnection,RoverHttpError,type RoverConnection} from './roverTransport';
export interface RoverReading {
id:string;uuid:string;slot:string|null;label:string;age_ms:number;
id:string;uuid:string;session_id?:string;slot:string|null;label:string;age_ms:number;
current_limits?:{motor_a:number;brake_a:number}|null;
values:{motor_current_a:number;input_current_a:number;input_voltage_v:number;erpm:number;duty:number;mos_temperature_c:number;fault_code:number};
}
export interface RoverState {
fresh:boolean;controlling:boolean;
snapshot:{supported?:boolean;instance?:string;state?:string;session_id?:string|null;message?:string|null;devices?:RoverReading[];
snapshot:{supported?:boolean;control_modes?:string[];instance?:string;state?:string;session_id?:string|null;message?:string|null;release_confirmed?:boolean|null;devices?:RoverReading[];
observation?:{initializing_devices:string[]};
last_stop?:{session_id:string;state:string;message:string|null;recovered_at?:string};
profile?:{layout:null|'1x1'|'2x2';bindings:Record<string,{device_id:string;uuid:string}>}};
}
// Generate fresh intent at the command channel cadence. Keepalive frames do
// not renew the original 400 ms deadline; duplicating a 100 ms-old sample
// wastes half of the 50 ms carrier opportunities during a network burst.
const INTENT_INTERVAL_MS=50;
const empty:RoverState={fresh:false,controlling:false,snapshot:{}};
async function request<T>(url:string,body?:unknown,keepalive=false):Promise<T>{
const response=await fetch(url,{method:body?'POST':'GET',headers:body?{'Content-Type':'application/json'}:undefined,
body:body?JSON.stringify(body):undefined,cache:'no-store',signal:AbortSignal.timeout(body?350:1000),keepalive});
const result=await response.json();
if(!response.ok)throw new Error(typeof result.detail==='string'?result.detail:'Канал управления недоступен.');
const retryable=(e:unknown)=>!(e instanceof RoverHttpError)||e.status>=500||[408,429].includes(e.status)||['Управление завершено. Включите его заново.','Команда устарела до передачи на борт.','Канал управления бортом недоступен.','Дождитесь завершения предыдущего управления.'].includes(e.message);
async function request<T>(url:string,body?:unknown,_keepalive=false):Promise<T>{
const started=performance.now(),kind=url.endsWith('/arm')?'arm':body?'command':'view';let outcome:'ok'|'http'|'transport'='transport';
try{
const result=await roverRequest<T>(url,body);
outcome='ok';
return result;
}catch(e){if(e instanceof RoverHttpError)outcome='http';throw e;}finally{roverTiming.request(kind,started,outcome);if(body)roverDevEvent(url.slice(0,url.lastIndexOf('/')),'request',{action:kind,outcome,elapsed_ms:performance.now()-started});}
}
export function useRoverControl(vehicleID:string,visible:boolean){
const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`;
const [state,setState]=useState<RoverState>(empty),[armed,setArmed]=useState(false),[pending,setPending]=useState(false),[error,setError]=useState<string|null>(null);
const [connecting,setConnecting]=useState(true),armPending=useRef(false);
const session=useRef<string|null>(null),seq=useRef(0),demand=useRef<Demand>({left:0,right:0}),sending=useRef(false),generation=useRef(0);
const [connection,setConnection]=useState<RoverConnection>('connecting'),armPending=useRef(false);
const [recovering,setRecovering]=useState(false),recovery=useRef(new RoverRecovery()),latest=useRef<RoverState>(empty);
const [controlMode,setControlMode]=useState<'unknown'|'rpm'|'duty'>('unknown');
const session=useRef<string|null>(null),seq=useRef(0),demand=useRef<Demand>({left:0,right:0}),sending=useRef(new Set<string>()),acknowledged=useRef(0),generation=useRef(0);
const holding=useRef<string|null>(null);
const inputGuard=useRef<(()=>boolean)|null>(null);
const setInputGuard=useCallback((guard:(()=>boolean)|null)=>{inputGuard.current=guard;},[]);
const stop=useCallback(()=>{
generation.current++;armPending.current=false;const id=session.current;session.current=null;demand.current={left:0,right:0};setArmed(false);setPending(false);
const retire=useCallback(()=>{
holding.current=null;generation.current++;armPending.current=false;const id=session.current;session.current=null;sending.current.clear();inputGuard.current=null;demand.current={left:0,right:0};setArmed(false);setPending(false);
if(id)void request(url+'/command',{session_id:id,sequence:++seq.current,left:0,right:0,stop:true},true).catch(()=>{});
},[url]);
const stop=useCallback(()=>{recovery.current.clear();setRecovering(false);retire();},[retire]);
const interrupt=useCallback((reason:string)=>{
roverDevEvent(url,"lifecycle",{reason,action:"interrupt",session_id:session.current});
const resume=recovery.current.interrupt(performance.now(),session.current);retire();setRecovering(resume);setError(resume?null:reason);
},[retire]);
const send=useCallback(async()=>{
roverTiming.tick(session.current!==null);
const id=session.current;if(!id)return;
// Check on every heartbeat, even when a previous request is still pending.
const inputValid=(demand.current.left===0&&demand.current.right===0)||inputGuard.current?.();
if(document.hidden||!document.hasFocus()||!inputValid)demand.current={left:0,right:0};
if(sending.current)return;
sending.current=true;
try{await request(url+'/command',{session_id:id,sequence:++seq.current,...demand.current,stop:false});}
catch(e){if(session.current===id){stop();setError(e instanceof Error?e.message:'Команда не подтверждена.');}}
finally{sending.current=false;}
},[url,stop]);
const setDemand=useCallback((next:Demand)=>{demand.current=next;void send();},[send]);
const foreground=!document.hidden&&document.hasFocus();
const inputValid=inputGuard.current?.()??false;
roverDevEvent(url,"heartbeat",{session_id:id,sequence:seq.current,foreground,input_valid:inputValid,pending:sending.current.size,...demand.current});
if(!foreground||!inputValid)demand.current={left:0,right:0};
// A hidden renderer cannot provide a reliable heartbeat. Hand only neutral
// readiness to the native Core owner socket; it can never renew movement.
if(!foreground&&holding.current===id)return;
// A delayed HTTP acknowledgement must not delay the next fresh intent.
// Bound concurrent requests; keep no queue and never renew remembered input.
if(sending.current.size>=4)return;
const sequence=++seq.current,key=`${id}:${sequence}`;sending.current.add(key);
const hold=!foreground;holding.current=hold?id:null;
try{await request(url+(hold?'/hold':'/command'),hold?{session_id:id,sequence}:{session_id:id,sequence,...demand.current,stop:false});
if(session.current===id)acknowledged.current=Math.max(acknowledged.current,sequence);
}catch(e){if(session.current===id&&sequence>acknowledged.current&&sequence===seq.current){const reason=e instanceof Error?e.message:'Команда не подтверждена.';
if(hold&&retryable(e)){holding.current=null;return;} // A delayed JS ack is not a lost board; poll verifies the lease.
if(retryable(e))interrupt(reason);else{stop();setError(reason);}}}
finally{sending.current.delete(key);}
},[url,stop,interrupt]);
const setDemand=useCallback((next:Demand)=>{roverDevEvent(url,"demand",next);demand.current=next;void send();},[send]);
const pauseInput=useCallback(()=>{demand.current={left:0,right:0};void send();},[send]);
const arm=useCallback(async(currentA:number,maxErpm:number)=>{
if(session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true);
const start=useCallback(async({currentA,speed,mode}:RoverArmSettings)=>{
if(document.hidden||!document.hasFocus()||session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true);
try{
const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,max_erpm:maxErpm});
const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,...(mode==='duty'?{max_duty_percent:speed}:{max_erpm:speed})});
if(g!==generation.current){void request(url+'/command',{session_id:result.session_id,sequence:1,left:0,right:0,stop:true},true).catch(()=>{});return false;}
// Retire every read started before this acknowledgement, including reads
// begun while POST /arm was pending. They describe the previous authority.
generation.current++;armPending.current=false;setPending(false);
seq.current=0;demand.current={left:0,right:0};session.current=result.session_id;setArmed(true);void send();
seq.current=0;acknowledged.current=0;demand.current={left:0,right:0};session.current=result.session_id;recovery.current.started(result.session_id);setArmed(true);void send();
return true;
}catch(e){if(g===generation.current)setError(e instanceof Error?e.message:'Не удалось включить управление.');return false;}
}catch(e){if(g===generation.current){const reason=e instanceof Error?e.message:'Не удалось включить управление.';
if(retryable(e)){interrupt(reason);return recovery.current.waiting;}stop();setError(reason);
}return false;}
finally{if(g===generation.current){armPending.current=false;setPending(false);}}
},[url,send]);
},[url,send,interrupt,stop]);
const arm=useCallback((currentA:number,speed:number,mode:'rpm'|'duty'='rpm')=>{
if(session.current||armPending.current||recovery.current.waiting)return Promise.resolve(false);
const settings={currentA,speed,mode};recovery.current.remember(settings,latest.current);return start(settings);
},[start]);
useEffect(()=>{
if(!visible){stop();setState(empty);setConnecting(false);return;}
let alive=true,busy=false,lastFault='';const started=performance.now();setConnecting(true);
if(!visible){stop();setState(empty);setError(null);setConnection('closed');return;}
const releaseTransport=retainRoverTransport(url);
let alive=true,busy=false;const notices=new RoverFaultNotice();setError(null);setConnection(roverConnection(url));setControlMode('unknown');
const recover=(value:RoverState,focused:boolean)=>{
if(session.current||armPending.current)return;
const settings=recovery.current.next(value,performance.now(),focused);
if(settings)void start(settings);
};
const poll=async()=>{
if(busy)return;busy=true;const before=generation.current;
try{const value=await request<RoverState>(url);if(alive&&before===generation.current){setState(value);
setConnecting(!value.fresh&&performance.now()-started<2000);
if(session.current&&(!value.fresh||!value.controlling)){stop();}
const fault=value.snapshot.state==='fault'?value.snapshot.message??'':'';
if(fault&&lastFault!==fault){lastFault=fault;setError(fault);}
}}catch{if(alive&&before===generation.current){setState(empty);setConnecting(false);if(session.current)stop();}}finally{busy=false;}
try{const value=await request<RoverState>(url);if(alive&&before===generation.current){roverTiming.view(value.fresh);setState(value);latest.current=value;
setConnection(roverConnection(url));
// Telemetry absence is not a declaration of an old RPM-only driver.
if(value.fresh&&value.snapshot.supported)setControlMode(value.snapshot.control_modes?.includes('duty')?'duty':'rpm');
const ownedSession=session.current;
const previousStatus=armPending.current||recovery.current.previousStatus(value,ownedSession);
const blocker=armPending.current?null:recovery.current.blocker(value,session.current);
if(blocker){stop();setError(blocker);}
else if(session.current&&(!value.fresh||!value.controlling||(value.snapshot.session_id===session.current&&value.snapshot.state==='stopping'))){
const reason=value.snapshot.message||(!value.fresh?'Управление прервано: нет свежих данных с борта.':value.snapshot.state==='receiver'?'Управление передано пульту.':'Управление прервано: борт перестал подтверждать команды. Повторите включение.');
interrupt(reason);
}
if(session.current&&value.fresh&&value.snapshot.session_id===session.current&&['ready','driving'].includes(value.snapshot.state??'')){
recovery.current.connected(performance.now());setRecovering(false);
}
recover(value,!document.hidden&&document.hasFocus());
if(!previousStatus){const notice=notices.update(value,ownedSession);if(notice.show)setError(notice.show);else if(notice.clear)setError(current=>current===notice.clear?null:current);}
}}catch{if(alive&&before===generation.current){setState(empty);latest.current=empty;setConnection(roverConnection(url));if(session.current)interrupt('Управление прервано: не удалось проверить связь с бортом.');recover(empty,false);}}finally{busy=false;}
};
void poll();const timer=setInterval(()=>void poll(),200),heartbeat=setInterval(()=>void send(),100);
const blur=()=>pauseInput(),hidden=()=>{if(document.hidden)pauseInput();};
window.addEventListener('blur',blur);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden);
return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();};
},[url,visible,stop,send,pauseInput]);
void poll();const timer=setInterval(()=>void poll(),200),heartbeat=setInterval(()=>void send(),INTENT_INTERVAL_MS);
const blur=()=>pauseInput();
const foreground=()=>{if(document.hidden||!document.hasFocus())return;void poll();void send();};
const hidden=()=>{if(document.hidden)pauseInput();else foreground();};
window.addEventListener('blur',blur);window.addEventListener('focus',foreground);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden);
return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('focus',foreground);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();releaseTransport();roverTiming.clear();};
},[url,visible,stop,send,pauseInput,start,interrupt]);
const ready=armed&&state.fresh&&state.snapshot.session_id===session.current&&['ready','driving'].includes(state.snapshot.state??'');
const canArm=state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??'');
return {state,armed,pending,error,connecting,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)};
const canArm=!recovering&&state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??'');
return {state,armed,pending,error,connection,connecting:connection==='connecting',controlMode,recovering,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)};
}
export type RoverController=ReturnType<typeof useRoverControl>;
@@ -0,0 +1,61 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {connectRoverEvidence,roverDevEvent} from './roverDevEvents';
import {saveRoverLog} from './roverLogSave';
import {saveOperatorCapture} from './roverOperatorCapture';
export type LocalCaptureOptions={enabled:boolean;preview:boolean};
export type DevOptions={live:boolean;core_trace:boolean;motor_samples:boolean;network:boolean;live_kbps:number;core_kbps:number};
export const localDevOptions:DevOptions={live:false,core_trace:false,motor_samples:true,network:true,live_kbps:16,core_kbps:16};
export type DevRow={record_sequence:number;source:string;event:string;at_utc:string;record?:DevRow;[key:string]:unknown};
export type DevState={local_capture?:{id:string|null;active:boolean;preview?:boolean;dropped?:number;sequence?:number};options?:DevOptions;options_supported?:boolean;id:string|null;active:boolean;closing:boolean;sequence:number;frames:DevRow[];
node?:{active?:boolean;transport_error?:string;storage?:{file?:string;closed:boolean;written:number;dropped:number;error?:string}}};
const empty:DevState={id:null,active:false,closing:false,sequence:0,frames:[]};
export function useRoverDiagnostics(vehicleID:string){
const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`;
const [state,setState]=useState<DevState>(empty),[rows,setRows]=useState<DevRow[]>([]);
const [pending,setPending]=useState(false),[saving,setSaving]=useState(false),[error,setError]=useState<string|null>(null);
const savedLocal=useRef<string|null>(null);
const evidence=useRef<ReturnType<typeof connectRoverEvidence>|null>(null),latest=useRef(empty);
const accept=useCallback((value:DevState)=>{
const previous=latest.current;latest.current=value;setState(value);evidence.current?.set(value.active&&value.options?.core_trace!==false?value.id:null,value.local_capture?.active?value.local_capture.id:null,value.local_capture?.preview!==false);
const failure=value.node?.storage?.error;
if(failure&&(previous.id!==value.id||previous.node?.storage?.error!==failure))
setError(failure==='CaptureInterrupted'?'DEV-запись прервана перезапуском борта. Сохранившийся файл оставлен на борту. Можно начать новую запись.':failure==='CaptureNotFound'?'Предыдущая DEV-запись на борту не найдена. Можно начать новую запись.':`Запись остановлена: ${failure}. Файл может быть неполным.`);
setRows(rows=>[...(previous.id===value.id?rows:[]),...value.frames.filter(r=>previous.id!==value.id||r.record_sequence>previous.sequence)].slice(-200));
},[]);
useEffect(()=>{
let alive=true,busy=false;latest.current=empty;setState(empty);setRows([]);
const client=connectRoverEvidence(url);evidence.current=client;
const poll=async()=>{if(busy)return;busy=true;const started=performance.now();try{
const r=await fetch(url+'/diagnostics?after='+latest.current.sequence,{cache:'no-store',signal:AbortSignal.timeout(3000)});
if(!r.ok)throw Error();const value:DevState=await r.json();
if(performance.now()-started>=200)roverDevEvent(url,'request',{action:'diagnostics_view',outcome:'slow',elapsed_ms:performance.now()-started});if(alive){accept(value);setError(current=>current==='Нет связи с Mission Core. Файл остаётся на борту.'?null:current);}
}catch{roverDevEvent(url,'request',{action:'diagnostics_view',outcome:'transport',elapsed_ms:performance.now()-started});if(alive&&latest.current.active)setError('Нет связи с Mission Core. Файл остаётся на борту.');}finally{busy=false;}};
void poll();const timer=setInterval(()=>void poll(),500);
return()=>{alive=false;clearInterval(timer);client.close();evidence.current=null;};
},[url,accept]);
const toggle=useCallback(async(options?:DevOptions,local?:LocalCaptureOptions)=>{
if(pending||latest.current.closing)return false;
setPending(true);setError(null);
try{
const enabled=!latest.current.active;if(!enabled)await evidence.current?.flush();
const previousID=latest.current.local_capture?.id;
if(enabled&&local?.enabled&&previousID&&savedLocal.current!==previousID)throw Error("Сначала сохраните предыдущий замер компьютера в окне логов.");
const r=await fetch(url+'/diagnostics',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(enabled?{enabled,options:options??localDevOptions,...(local?{local_options:{...local,previous_id:previousID??null}}:{})}:{enabled})});
const value=await r.json();if(!r.ok)throw Error(value.detail??'Не удалось переключить DEV.');accept(value);return enabled;
}catch(e){setError(e instanceof Error?e.message:'Не удалось переключить DEV.');return false;}finally{setPending(false);}
},[url,pending,accept]);
const save=useCallback(async()=>{
if(saving)return;setSaving(true);setError(null);
try{await saveRoverLog(url,latest.current.node?.storage?.file?.split('/').pop()??`rover-${latest.current.id}.jsonl`);}
catch(e){if(!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Не удалось сохранить файл.');}
finally{setSaving(false);}
},[url,saving]);
const saveLocal=useCallback(async()=>{
const id=latest.current.local_capture?.id;if(!id||saving)return;setSaving(true);setError(null);
try{await saveOperatorCapture(url,id,async()=>{await evidence.current?.flush();});if(latest.current.local_capture?.id===id&&!latest.current.local_capture.active)savedLocal.current=id;}
catch(e){if(!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Не удалось сохранить замер.');}
finally{setSaving(false);}
},[url,saving]);
return {state,rows,pending,saving,error,toggle,save,saveLocal,clearError:()=>setError(null)};
}
export type RoverDiagnostics=ReturnType<typeof useRoverDiagnostics>;
@@ -4,56 +4,105 @@ import type {ObservationLayout} from './observationLayout';
import {decodeObservationPresets,saveObservationPreset,selectObservationPreset,renameObservationPreset,removeObservationPreset,type ObservationPresets} from './observationPresets';
import {fleetRequest} from './useFleet';
import {sameConfiguration} from './configurationEquality';
import {observationSerial,mergeObservation,saveObservation} from './observationSync';
interface Document {layouts:ObservationPresets;cameras:Record<string,CameraPresentation>}
interface Receipt {schema:'missioncore.rover-configuration/v1';revision:number;document:Document|null;draft?:Document|null;source:'onboard'|'mirror';writable:boolean;available:boolean}
interface Draft {revision:number;document:Document}
interface Draft {revision:number;document:Document;base?:Document}
export function useVehicleObservation(vehicleID:string) {
const draftKey=`missioncore.observation.draft.v1:${vehicleID}`;
const stored=(key:string)=>{try{return JSON.parse(localStorage.getItem(key)??'null');}catch{return null;}};
const initial=():Document=>({layouts:decodeObservationPresets(null,stored(`missioncore.observation.v1:${vehicleID}`)),cameras:{}});
const [recovery,setRecovery]=useState<Document|null>(null);
const [connectionError,setConnectionError]=useState<string|null>(null);
const [document,setDocument]=useState(initial),[ready,setReady]=useState(false),[error,setError]=useState<string|null>(null),[edit,setEdit]=useState(0),[pending,setPending]=useState(false),[errorDismissed,setErrorDismissed]=useState(false);
const state=useRef({document,edit:0,saved:0,revision:0,ready:false});
const state=useRef({document,base:document,edit:0,saved:0,revision:0,ready:false});
const mounted=useRef(true),writes=useRef(Promise.resolve());
const path=`/${encodeURIComponent(vehicleID)}/observation-configuration`;
const normalize=(value:Document):Document=>({...value,layouts:decodeObservationPresets(value.layouts)});
const remember=()=>{try{localStorage.setItem(draftKey,JSON.stringify({revision:state.current.revision,document:state.current.document}));}catch{/* The board acknowledgement remains the durable save. */}};
const normalize=(value:Document|null):Document=>value?({...value,layouts:decodeObservationPresets(value.layouts)}):initial();
const remember=(current=state.current)=>{try{localStorage.setItem(draftKey,JSON.stringify({revision:current.revision,document:current.document,base:current.base}));}catch{/* The board acknowledgement remains the durable save. */}};
const flush=()=>{
const current=state.current;
const write=async()=>{
const current=state.current;if(!current.ready||current.saved===current.edit)return;
if(!current.ready||current.saved===current.edit)return;
const version=current.edit,payload=current.document;
if(mounted.current)setPending(true);
if((mounted.current&&state.current===current))setPending(true);
try {
const receipt=await fleetRequest<Receipt>(path,'PUT',{expected_revision:current.revision,document:payload},20000);
current.revision=receipt.revision;current.saved=version;
if(current.edit===version){try{localStorage.removeItem(draftKey);}catch{}}else remember();
if(mounted.current)setError(null);
}catch(cause){if(mounted.current){setErrorDismissed(false);setError(cause instanceof Error?cause.message:'Подтверждение записи на борт не получено.');}}
finally{if(mounted.current)setPending(current.saved!==current.edit);}
const saved=await saveObservation(current.revision,current.base,payload,
()=>fleetRequest<Receipt>(path),(revision,document)=>fleetRequest<Receipt>(path,'PUT',{expected_revision:revision,document},20000),normalize);
current.revision=saved.receipt.revision;current.base=saved.document;current.saved=version;
// Preserve edits made while the request was pending, plus unrelated changes
// which were merged from the board. Conflicting new edits remain local.
current.document=mergeObservation(payload,current.document,saved.document).value;
if((mounted.current&&state.current===current))setDocument(current.document);
if(current.edit===version){try{localStorage.removeItem(draftKey);}catch{}}else remember(current);
if((mounted.current&&state.current===current))setError(null);
}catch(cause){if((mounted.current&&state.current===current)){setErrorDismissed(false);setError(cause instanceof Error?cause.message:'Подтверждение записи на борт не получено.');}}
finally{if((mounted.current&&state.current===current))setPending(current.saved!==current.edit);}
};
writes.current=writes.current.then(write,write);return writes.current;
writes.current=observationSerial(vehicleID,write);return writes.current;
};
useEffect(()=>{
mounted.current=true;let active=true;
fleetRequest<Receipt>(path).then(receipt=>{
mounted.current=true;let active=true,timer:ReturnType<typeof setTimeout>|undefined,wasWritable=false;
const empty=initial();state.current={document:empty,base:empty,edit:0,saved:0,revision:0,ready:false};
setReady(false);setError(null);setConnectionError(null);setErrorDismissed(false);setRecovery(null);
const refresh=async()=>{
let retrySave=false;
try{await observationSerial(vehicleID,async()=>{
if(!active)return;
const saved=receipt.document?normalize(receipt.document):initial();
const receipt=await fleetRequest<Receipt>(path);
if(!active)return;
setConnectionError(receipt.writable?null:'Связь с хранилищем конфигурации на борту не подтверждена. Изменения останутся черновиком.');
const recovered=receipt.writable&&!wasWritable;wasWritable=receipt.writable;
const current=state.current;
if(current.ready){
// Availability is rechecked independently of edits. A mirror cannot roll
// back the acknowledged board version or overwrite an unsaved local draft.
if(!receipt.writable||receipt.revision<current.revision)return;
const remote=normalize(receipt.document),merged=mergeObservation(current.base,current.document,remote);
if(merged.conflicts.length)return;
current.document=merged.value;current.base=remote;current.revision=receipt.revision;
if(sameConfiguration(current.document,remote)){
// A timed-out save may already be committed on the board. Its fresh
// read-back settles both the draft and the old acknowledgement error.
if(current.saved!==current.edit)setError(null);
current.saved=current.edit;try{localStorage.removeItem(draftKey);}catch{}
}else remember(current);
setDocument(current.document);setPending(current.saved!==current.edit);
retrySave=recovered&&current.saved!==current.edit;
return;
}
const saved=normalize(receipt.document);
const draft=stored(draftKey) as Draft|null;
const candidate=draft?.document??(!receipt.document?receipt.draft:null);
const same=candidate&&sameConfiguration(candidate,receipt.document);
const dirty=!!candidate&&!same;
const value=dirty?normalize(candidate):saved;
const revision=draft&&dirty?draft.revision:receipt.revision;
state.current={document:value,edit:dirty?1:0,saved:0,revision,ready:true};
let value=candidate?normalize(candidate):saved;
let dirty=!!candidate&&!sameConfiguration(value,saved);
if(dirty&&draft&&draft.revision!==receipt.revision){
const merge=draft.base?mergeObservation(normalize(draft.base),value,saved):null;
if(merge&&!merge.conflicts.length){value=merge.value;dirty=!sameConfiguration(value,saved);}
else {
// Legacy drafts lack a merge ancestor. Keep a recoverable copy and open
// the latest board version instead of endlessly replaying a stale revision.
try{localStorage.setItem(draftKey+':recovery',JSON.stringify(value));}catch{}
setRecovery(value);value=saved;dirty=false;
}
}
if(!dirty){try{localStorage.removeItem(draftKey);}catch{}}
const retained=stored(draftKey+':recovery');if(retained)setRecovery(normalize(retained));
state.current={document:value,base:saved,edit:dirty?1:0,saved:0,revision:receipt.revision,ready:true};
setDocument(value);setReady(true);setEdit(dirty?1:0);setPending(dirty);
if(!receipt.writable)setError('Связь с хранилищем конфигурации на борту не подтверждена. Изменения останутся черновиком.');
}).catch(cause=>{if(active)setError(cause instanceof Error?cause.message:'Настройки недоступны.');});
return()=>{active=false;mounted.current=false;void flush();};
});
if(active&&retrySave)void flush();
}catch(cause){if(active){wasWritable=false;setConnectionError(cause instanceof Error?cause.message:'Настройки недоступны.');}}
finally{if(active)timer=setTimeout(()=>void refresh(),5000);}
};
void refresh();
return()=>{active=false;clearTimeout(timer);mounted.current=false;void flush();};
},[vehicleID]);
useEffect(()=>{if(!ready||edit===0)return;const timer=setTimeout(()=>void flush(),350);return()=>clearTimeout(timer);},[edit,ready]);
const update=(change:(value:Document)=>Document)=>{
if(!state.current.ready)return;
const current=state.current;current.document=change(current.document);current.edit++;remember();
const current=state.current;const next=change(current.document);if(sameConfiguration(next,current.document))return;current.document=next;current.edit++;remember();
setDocument(current.document);setEdit(current.edit);setPending(true);
};
const changeLayouts=(change:(value:ObservationPresets)=>ObservationPresets)=>{
@@ -61,22 +110,32 @@ export function useVehicleObservation(vehicleID:string) {
catch(cause){setError(cause instanceof Error?cause.message:'Раскладка не сохранена.');return false;}
};
const reload=async()=>{
const current=state.current;
if(state.current.saved!==state.current.edit){const copy=state.current.document;setRecovery(copy);try{localStorage.setItem(draftKey+':recovery',JSON.stringify(copy));}catch{}}
await writes.current;
try{
const receipt=await fleetRequest<Receipt>(path);
const receipt=await observationSerial(vehicleID,()=>fleetRequest<Receipt>(path));
if(!mounted.current||state.current!==current)return false;
if(!receipt.writable)throw Error('Не удалось получить актуальную конфигурацию с борта. Черновик сохранён.');
const value=receipt.document?normalize(receipt.document):initial();
state.current={document:value,edit:0,saved:0,revision:receipt.revision,ready:true};
state.current={document:value,base:value,edit:0,saved:0,revision:receipt.revision,ready:true};
setDocument(value);setReady(true);setEdit(0);setPending(false);setError(null);
try{localStorage.removeItem(draftKey);}catch{}
}catch(cause){setError(cause instanceof Error?cause.message:'Настройки недоступны.');}
return true;
}catch(cause){setError(cause instanceof Error?cause.message:'Настройки недоступны.');return false;}
};
const setLayout=(value:SetStateAction<ObservationLayout>)=>changeLayouts(current=>({...current,layout:typeof value==='function'?value(current.layout):value}));
return {...document.layouts,ready,pending,cameras:document.cameras,setLayout,
const restore=async()=>{
const retained=recovery??state.current.document;
if(!await reload())return;
update(()=>retained);setRecovery(null);
try{localStorage.removeItem(draftKey+':recovery');}catch{}
};
return {...document.layouts,recovery:!!recovery,restore,ready,pending,cameras:document.cameras,setLayout,
setCamera:(id:string,value:CameraPresentation)=>update(current=>({...current,cameras:{...current.cameras,[id]:value}})),
select:(id:string)=>changeLayouts(current=>selectObservationPreset(current,id)),
save:(name:string)=>changeLayouts(current=>saveObservationPreset(current,name,`saved:${crypto.randomUUID()}`)),
rename:(id:string,name:string)=>changeLayouts(current=>renameObservationPreset(current,id,name)),
remove:(id:string)=>changeLayouts(current=>removeObservationPreset(current,id)),
error,toastError:errorDismissed?null:error,clearError:()=>setErrorDismissed(true),retry:flush,reload};
error:error??connectionError,toastError:errorDismissed?null:error??connectionError,clearError:()=>setErrorDismissed(true),retry:flush,reload};
}
@@ -0,0 +1,6 @@
/** View-only bounds. Each full-range endpoint disables its own clipping plane. */
export function heightSlice([lower, upper]: readonly [number, number], [min, max]: readonly [number, number]) {
const tolerance = Math.max(1, max - min) * 1e-9;
return { floor: lower <= min + tolerance ? null : lower,
ceiling: upper >= max - tolerance ? null : upper };
}
@@ -2,7 +2,7 @@ import { createContext, useCallback, useContext, useEffect, useRef, useState, ty
import { plannerBase, plannerRequest, type Draft } from './planner';
export interface PlanningLiveTest {
schema_version: 'missioncore.planning-live-test/v1'; id: string; profile: 'planning'; plugin_id:string; draft: Draft;
schema_version: 'missioncore.planning-live-test/v1'|'missioncore.planning-live-status/v1'; id: string; profile: 'planning'; plugin_id:string; draft: Omit<Draft,'route'> & {route:Omit<Draft['route'],'points'>};
state: 'preparing'|'waiting'|'running'|'completed'|'cancelled'|'error'|'interrupted';
planning_phase?: 'preparing'|'waiting-cloud'|'collecting'|'searching'|'refreshing'|'validating'|'tracking'|'lost'|'ended';
tracking_state?: 'acquiring'|'tracking'|'lost';
@@ -40,7 +40,7 @@ export function PlanningTestProvider({children}:{children:ReactNode}) {
let disposed=false, timer:ReturnType<typeof setTimeout>;
const poll=async()=>{
const expected=generation.current;
try { const next=await plannerRequest<PlanningLiveTest|null>(endpoint+'/active'); if(!disposed && expected===generation.current) {setTest(next);setPollError(null);} }
try { const next=await plannerRequest<PlanningLiveTest|null>(endpoint+'/status'); if(!disposed && expected===generation.current) {setTest(next);setPollError(null);} }
catch(e) {if(!disposed && expected===generation.current)setPollError(e instanceof Error?e.message:'Исследование недоступно.');}
if(!disposed)timer=setTimeout(()=>void poll(),1500);
};void poll();return()=>{disposed=true;clearTimeout(timer);};
@@ -22,13 +22,13 @@ export async function fetchOverviewSpatial(source: string, signal: AbortSignal):
return response.json();
}
export async function updateOverviewSpatial(source: string, ceiling: number | null, mode: OverviewViewMode | null, aspect: number, signal: AbortSignal,
comparisonGeneration: string | null = null, representation: OverviewRepresentation = "original") {
comparisonGeneration: string | null = null, representation: OverviewRepresentation = "original", floor: number | null = null) {
if (representation === "corrected" && !comparisonGeneration) throw new Error("Исправленная версия недоступна.");
const url = endpoint(source);
const generation = url.searchParams.get("generation");
url.search = "";
const response = await fetch(url, { method: "POST", signal, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ generation, ceiling_m: ceiling, mode, aspect,
body: JSON.stringify({ generation, ceiling_m: ceiling, floor_m: floor, mode, aspect,
comparison_generation: comparisonGeneration, representation }) });
if (!response.ok) throw new Error("Не удалось обновить вид облака.");
const bytes = new Uint8Array(await response.arrayBuffer());
@@ -1,6 +1,6 @@
import { polygonRequest, type AiPlan, type AiRobot, type AiWaypoint, type AiWorld } from "./aiPolygon";
export interface EditorCache {
local_scene?: { visual_url: string; collision_url: string; visual_rotation: number[]; collision_rotation: number[] };
local_scene?: { visual_url: string; collision_url: string | null; visual_rotation: number[]; collision_rotation: number[] };
key: string; world: AiWorld; status: "queued" | "preparing" | "uploading" | "ready" | "failed";
error: string | null;
files: Record<string, { sha256: string; byte_length: number; uploaded_bytes: number }>;
@@ -31,6 +31,7 @@ export interface AiSource {
description?: string;
}
export interface AiWorld extends AiSource {
display_name?: string; removed?: boolean;
local_scene?: { project_id: string };
inference_ready?: boolean; inference_message?: string;
world_id: string; filename: string; byte_length: number; uploaded_bytes: number;
@@ -123,7 +124,7 @@ export interface AiPlanningCommand {
point_id?: string; x?: number; y?: number; amount?: number; enabled?: boolean; axis?: "x" | "y" | "xy";
}
export interface AiCatalog {
sources: AiSource[]; worlds: AiWorld[]; runs: AiRun[];
sources: AiSource[]; worlds: AiWorld[]; removed_worlds?: AiWorld[]; runs: AiRun[];
robots: AiRobot[];
plans: AiPlan[];
runtime: { available: boolean; active_run: AiRun | null };
@@ -142,6 +143,8 @@ export async function polygonRequest<T>(path: string, init: RequestInit = {}): P
}
export const runJournalUrl = (run: AiRun) => `${API}/runs/${run.run_id}/decisions`;
export const fetchAiCatalog = () => polygonRequest<AiCatalog>("/catalog");
export const updateAiWorld = (id:string, changes:{display_name?:string;removed?:boolean}) =>
polygonRequest<AiWorld>(`/worlds/${id}`, {method:"PATCH",body:JSON.stringify(changes)});
export const aiPlanName = (plan: AiPlan) => plan.display_name ?? plan.name;
export const updateAiPlan = (id:string, changes:{display_name?:string;removed?:boolean}) =>
polygonRequest<AiPlan>(`/plans/${id}`, {method:"PATCH",body:JSON.stringify(changes)});
@@ -1,17 +1,18 @@
import { PerspectiveCamera, Quaternion, Vector3 } from "three";
import { Quaternion, Vector3 } from "three";
import {screenSpan,type ProjectionCamera} from "./editorProjection";
const UP = new Vector3(0,1,0);
/** Depth along the optical axis gives a metric screen-space pan at any zoom. */
export function navigationDepth(camera: PerspectiveCamera, anchor: Vector3) {
export function navigationDepth(camera: ProjectionCamera, anchor: Vector3) {
return Math.max(.1, anchor.clone().sub(camera.position).dot(camera.getWorldDirection(new Vector3())));
}
export function panCamera(camera: PerspectiveCamera, depth: number, dx: number, dy: number, height: number) {
const scale=2*depth*Math.tan(camera.fov*Math.PI/360)/Math.max(1,height);
export function panCamera(camera: ProjectionCamera, depth: number, dx: number, dy: number, height: number) {
const scale=screenSpan(camera,depth)/Math.max(1,height);
camera.position.add(new Vector3(-dx*scale,dy*scale,0).applyQuaternion(camera.quaternion));
camera.updateMatrixWorld();
}
/** Rotate the complete camera pose about the picked point: no lookAt snap.
* The picked point keeps its screen coordinates, including off-centre clicks. */
export function orbitCamera(camera: PerspectiveCamera, anchor: Vector3, dx: number, dy: number, height: number) {
export function orbitCamera(camera: ProjectionCamera, anchor: Vector3, dx: number, dy: number, height: number) {
const factor=2*Math.PI/Math.max(1,height);
const yaw=new Quaternion().setFromAxisAngle(UP,-dx*factor);
const forward=camera.getWorldDirection(new Vector3());
@@ -0,0 +1,21 @@
import {OrthographicCamera,PerspectiveCamera,Ray,Vector3} from "three";
export type EditorProjection = "orthographic"|"perspective";
export type ProjectionCamera = OrthographicCamera|PerspectiveCamera;
export const isOrthographic=(camera:ProjectionCamera):camera is OrthographicCamera=>"isOrthographicCamera" in camera;
export function screenSpan(camera:ProjectionCamera,depth:number) {
return isOrthographic(camera)?(camera.top-camera.bottom)/camera.zoom:2*depth*Math.tan(camera.fov*Math.PI/360)/camera.zoom;
}
export function cameraRay(camera:ProjectionCamera,x:number,y:number) {
const near=new Vector3(x*2-1,1-y*2,-1).unproject(camera);
const far=new Vector3(x*2-1,1-y*2,1).unproject(camera);
return new Ray(near,far.sub(near).normalize());
}
/** Match scale on the focal plane; switching projection must never move geometry. */
export function switchProjection(camera:ProjectionCamera,mode:EditorProjection,aspect:number,depth:number):ProjectionCamera {
if(isOrthographic(camera)===(mode==="orthographic"))return camera;
const span=screenSpan(camera,depth),half=span/2;
const next=mode==="orthographic"?new OrthographicCamera(-half*aspect,half*aspect,half,-half,camera.near,camera.far):new PerspectiveCamera(60,aspect,camera.near,camera.far);
next.position.copy(camera.position);next.quaternion.copy(camera.quaternion);next.up.copy(camera.up);
if(mode==="perspective")next.position.addScaledVector(camera.getWorldDirection(new Vector3()),depth-half/Math.tan(Math.PI/6));
next.updateProjectionMatrix();next.updateMatrixWorld();return next;
}
@@ -0,0 +1,79 @@
import { useEffect, useRef, useState } from "react";
import { loadUrbanMap, type UrbanMap } from "./urbanMap";
export interface AnalysisProgress {label:string;stage:number|null;stages:number;fraction:number|null;eta_seconds:number|null;stale:boolean;eta_basis:string}
export interface AnalysisJob {key:string;request_id?:string|null;status:"queued"|"running"|"ready"|"failed"|"cancelled";phase:string;completed:number;total:number;error:string|null;progress?:AnalysisProgress;cancel_requested?:boolean;queue?:{position:number|null;total:number;waiting:number}}
export function analysisProgressLabel(job:AnalysisJob):string {
const p=job.progress;
if(!p)return job.status==="queued"?"Ожидание Worker":"Расчёт инфраструктуры";
const stage=p.stage?` · этап ${p.stage} из ${p.stages}`:"";
const eta=p.eta_seconds===null?"":` · ≈ ${Math.max(1,Math.ceil(p.eta_seconds/60))} мин${job.status==="queued"?" на расчёт":job.phase==="preparing"?" после подготовки":" осталось"}`;
return `${p.stale?"Связь с расчётом потеряна":p.label}${job.status==="queued"&&job.queue?.position?` · №${job.queue.position}`:stage}${eta}`;
}
export function useInfrastructureAnalysis(worldId:string,worldSha:string,onMap:(map:UrbanMap)=>void) {
const [job,setJob]=useState<AnalysisJob|null>(null),[error,setError]=useState<string|null>(null);
const [sending,setSending]=useState(false),[checking,setChecking]=useState(true);
const callback=useRef(onMap);callback.current=onMap;
const lifecycle=useRef<AbortController|null>(null),generation=useRef(0),requestId=useRef<string|null>(null),commandPending=useRef(false);
const endpoint=`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/infrastructure-analysis`;
useEffect(()=>{
const abort=new AbortController();lifecycle.current=abort;let timer:ReturnType<typeof setTimeout>;let loaded:string|null=null;
generation.current++;requestId.current=null;commandPending.current=false;setJob(null);setError(null);setChecking(true);setSending(false);
const refresh=async()=>{
if(commandPending.current){timer=setTimeout(refresh,3000);return;}
const revision=generation.current;
try {
const response=await fetch(endpoint,{signal:abort.signal,cache:"no-store"});
if(!response.ok)throw new Error("Не удалось проверить расчёт инфраструктуры.");
const row=await response.json() as AnalysisJob|null;
if(abort.signal.aborted||revision!==generation.current)return;
if(row?.request_id&&row.request_id===requestId.current)requestId.current=null;
setJob(row);
if(row?.status==="ready"&&loaded!==row.key){
const map=await loadUrbanMap(worldId,worldSha,abort.signal);
if(map&&!abort.signal.aborted&&revision===generation.current){callback.current(map);loaded=row.key;}
}
} catch(e){if(!abort.signal.aborted&&revision===generation.current)setError((e as Error).message);}
finally{if(!abort.signal.aborted){setChecking(false);timer=setTimeout(refresh,3000);}}
};
void refresh();return()=>{abort.abort();clearTimeout(timer);};
},[endpoint,worldId,worldSha]);
const start=async(force:boolean)=>{
const abort=lifecycle.current;if(!abort||abort.signal.aborted||commandPending.current)return;
generation.current++;commandPending.current=true;setSending(true);setError(null);
requestId.current??=crypto.randomUUID().replaceAll("-","");
try {
const response=await fetch(endpoint,{method:"POST",signal:abort.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({force,request_id:requestId.current})});
const body=await response.json();
if(!response.ok)throw new Error(typeof body.detail==="string"?body.detail:"Не удалось начать расчёт.");
if(!abort.signal.aborted){setJob(body);requestId.current=null;}
}catch(e){if(!abort.signal.aborted)setError((e as Error).message);}
finally{if(!abort.signal.aborted){commandPending.current=false;setSending(false);}}
};
const cancel=async()=>{
const abort=lifecycle.current;if(!abort||abort.signal.aborted||!job||commandPending.current)return;
generation.current++;commandPending.current=true;setSending(true);setError(null);
try{
const response=await fetch(`${endpoint}/${job.key}/cancel`,{method:"POST",signal:abort.signal});
const row=await response.json();if(!response.ok)throw new Error(typeof row.detail==="string"?row.detail:"Не удалось отменить расчёт.");
if(!abort.signal.aborted)setJob(row);
}catch(e){if(!abort.signal.aborted)setError((e as Error).message);}
finally{if(!abort.signal.aborted){commandPending.current=false;setSending(false);}}
};
return {job,error,cancel,clearError:()=>setError(null),sending,checking,start};
}
export function useInfrastructureQueue(){
const [jobs,setJobs]=useState<(AnalysisJob&{world_id:string;name:string})[]>([]),[unavailable,setUnavailable]=useState(false);
useEffect(()=>{
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
const refresh=async()=>{
try{const response=await fetch('/api/v1/ai-polygon/infrastructure-analysis/queue',{signal:abort.signal,cache:'no-store'});
if(!response.ok)throw new Error('Queue unavailable');
const value=await response.json();if(!abort.signal.aborted){setJobs(value.jobs);setUnavailable(false);}
}catch{if(!abort.signal.aborted)setUnavailable(true);}
finally{if(!abort.signal.aborted)timer=setTimeout(refresh,3000);}
};
void refresh();return()=>{abort.abort();clearTimeout(timer);};
},[]);
return {jobs,unavailable};
}
@@ -0,0 +1,22 @@
import { planMatchesDraft } from "./planDraft";
import type { AiPlan, AiRobot, AiWaypoint } from "./aiPolygon";
import type { EditorCache } from "./aiEditor";
import type { PreparedRoute } from "./routePreparation";
/** The same admission conditions drive visibility and command entry points. */
export function plannerActions(input: {
draft: {cache:EditorCache;points:AiWaypoint[]}|null; robot:AiRobot|undefined;
plan:AiPlan|undefined; routeRequired:boolean; route:PreparedRoute|null; routeKey:string|null;
busy:boolean; runtimeAvailable:boolean; inferenceReady:boolean; activeRun:boolean;
}) {
const {draft,robot,plan,routeRequired,route,routeKey,busy}=input;
const pointsReady=!!draft && !!robot && draft.points.length>=2;
const routeReady=pointsReady && (!routeRequired || (!!route && !!routeKey));
const changed=!!draft && !!robot && (!planMatchesDraft(plan,draft.cache.key,robot.sha256,draft.points)
|| (routeRequired && !!route && plan?.prepared_route?.sha256!==route.sha256));
return {
save:!busy && routeReady && changed,
prepare:!busy && pointsReady && routeRequired && !routeReady && input.runtimeAvailable,
launch:!busy && routeReady && input.runtimeAvailable && input.inferenceReady && !input.activeRun,
};
}
@@ -1,14 +1,18 @@
import type { GaussianQuality } from "./gaussianQuality";
export interface PlannerPreferences {
cube: {size:number;face:string;text:string;edge:string;hover:string;hoverText:string;opacity:number;edgeOpacity:number};
quality: GaussianQuality;
toolbar: { placement:"left"|"right"|"top"|"bottom"; minSize:number; maxSize:number; lensCount:number; gap:number; autoHide:boolean; hideDelay:number; background:string; border:string; outline:string; accent:string };
navigation: { nearDistance:number; farDistance:number; nearPan:number; farPan:number; zoom:number; centroidPixels:number; centroidColor:string; centroidOpacity:number };
pivot: { pixels: number; diameter: number; cone: number; opacity: number; x: string; y: string; z: string };
waypoint: { diameter: number; height: number; color: string; opacity: number; frequency: number; emission: number; emissionColor: string };
}
export const PLANNER_PREFERENCES_KEY = "missioncore.simulation-view/v1";
export const DEFAULT_PLANNER_PREFERENCES: PlannerPreferences = {
cube: {size:66,face:"#292929",text:"#eeeeee",edge:"#888888",hover:"#eeeeee",hoverText:"#161616",opacity:1,edgeOpacity:1},
quality: "medium",
toolbar: { placement:"right",minSize:25,maxSize:42,lensCount:3,gap:10,autoHide:true,hideDelay:5000,background:"#141416",border:"#141416",outline:"#3b3b3d",accent:"#edf0eb" },
navigation: { nearDistance:3, farDistance:100, nearPan:1, farPan:1, zoom:1, centroidPixels:14, centroidColor:"#edf0eb", centroidOpacity:.8 },
pivot: { pixels: 105, diameter: 5, cone: 22, opacity: 1, x: "#e85b54", y: "#83ca61", z: "#6499ed" },
waypoint: { diameter: .35, height: 4.5, color: "#edf0eb", opacity: .65, frequency: .5, emission: 1.5, emissionColor: "#edf0eb" },
@@ -21,7 +25,15 @@ export function normalizePlannerPreferences(value: unknown): PlannerPreferences
const color = (x: unknown, fallback: string) => typeof x === "string" && /^#[0-9a-f]{6}$/i.test(x) ? x : fallback;
const nav:Partial<PlannerPreferences["navigation"]>=v.navigation??{}, dn=d.navigation;
const nearDistance=n(nav.nearDistance,dn.nearDistance,.5,50);
const c:Partial<PlannerPreferences["cube"]>=v.cube??{},dc=d.cube;
const t:Partial<PlannerPreferences["toolbar"]>=v.toolbar??{}, dt=d.toolbar;
const minSize=n(t.minSize,dt.minSize,18,42), lens=Math.round(n(t.lensCount,dt.lensCount,1,13));
return {
cube:{size:n(c.size,dc.size,48,160),face:color(c.face,dc.face),text:color(c.text,dc.text),edge:color(c.edge,dc.edge),hover:color(c.hover,dc.hover),hoverText:color(c.hoverText,dc.hoverText),opacity:n(c.opacity,dc.opacity,.2,1),edgeOpacity:n(c.edgeOpacity,dc.edgeOpacity,0,1)},
toolbar:{placement:["left","right","top","bottom"].includes(t.placement??"")?t.placement!:dt.placement,
minSize,maxSize:Math.max(minSize,n(t.maxSize,dt.maxSize,18,88)),lensCount:lens%2?lens:Math.min(13,lens+1),gap:n(t.gap,dt.gap,0,24),
autoHide:typeof t.autoHide==="boolean"?t.autoHide:dt.autoHide,hideDelay:n(t.hideDelay,dt.hideDelay,0,15000),
background:color(t.background,dt.background),border:color(t.border,dt.border),outline:color(t.outline,dt.outline),accent:color(t.accent,dt.accent)},
navigation: {nearDistance,farDistance:Math.max(nearDistance+1,n(nav.farDistance,dn.farDistance,2,500)),
nearPan:n(nav.nearPan,dn.nearPan,.1,5),farPan:n(nav.farPan,dn.farPan,.1,5),zoom:n(nav.zoom,dn.zoom,.1,3),
centroidPixels:n(nav.centroidPixels,dn.centroidPixels,6,64),centroidColor:color(nav.centroidColor,dn.centroidColor),centroidOpacity:n(nav.centroidOpacity,dn.centroidOpacity,.1,1)},
@@ -0,0 +1,11 @@
/** Scene-space height range, independent of the reduced collision proxy. */
export function sceneClipBounds(visual: readonly [number, number], collision: readonly [number, number] | null): [number, number] {
const low = Math.floor(Math.min(visual[0], collision?.[0] ?? visual[0]));
const high = Math.ceil(Math.max(500, visual[1], collision?.[1] ?? visual[1]));
return [low, Math.max(low + 1, high)];
}
/** Native range inputs can round a fractional max slightly down on readback. */
export function sceneClipValue(value: number, [low, high]: readonly [number, number]): number {
return value >= high - Math.max(1, high - low) * 1e-9 ? Infinity : value;
}
@@ -0,0 +1,25 @@
import clipping from "polygon-clipping";
import type {UrbanMapFeature} from "./urbanMap";
import {geometryPaths,type RegionOperation} from "./semanticVector";
/** Retain existing heights; new intersection vertices interpolate the nearest measured edge. */
export function regionOperation(feature:UrbanMapFeature|undefined,brush:number[][],mode:"union"|"difference"):RegionOperation {
if(mode==="difference"&&!feature)throw new Error("Сначала выберите пешеходную область для вырезания.");
if(brush.length<4)throw new Error("Замкните область минимум из трёх точек.");
if(feature&&feature.geometry.type!=="Polygon")throw new Error("Выберите пешеходную область.");
const old=feature?geometryPaths(feature):[],subject=old.map(r=>r.map(p=>p.slice(0,2) as [number,number]));
const paint=[brush.map(p=>p.slice(0,2) as [number,number])];
const result=mode==="union"?clipping.union(subject.length?subject:paint,paint):subject.length?clipping.difference(subject,paint):[];
const seeds=[...old,brush];
const height=(p:number[])=>{
for(const ring of seeds)for(const q of ring)if(p[0]===q[0]&&p[1]===q[1])return q[2];
let best=Infinity,z=brush[0][2];
for(const ring of seeds)for(let i=0;i<ring.length-1;i++){
const a=ring[i],b=ring[i+1],dx=b[0]-a[0],dy=b[1]-a[1],l=dx*dx+dy*dy;
const t=l?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/l)):0;
const d=Math.hypot(p[0]-a[0]-t*dx,p[1]-a[1]-t*dy);
if(d<best){best=d;z=a[2]+t*(b[2]-a[2]);}
}return z;
};
return {kind:"region",feature_id:feature?.id??`user-${crypto.randomUUID()}`,token:crypto.randomUUID(),mode,brush,
polygons:result.map(p=>p.map(r=>r.map(v=>[...v,height(v)])))};
}
@@ -0,0 +1,14 @@
import type {Knot} from "./semanticVector";
export function curveControlScale(nodes:Knot[],index:number,closed:boolean,project:(p:number[])=>number[]|null):number {
const node=nodes[index],base=node&&project(node.point);if(!base)return 1;
const neighbors=[nodes[index-1]??(closed?nodes.at(-1):undefined),nodes[index+1]??(closed?nodes[0]:undefined)];
const lengths=neighbors.map(n=>n&&project(n.point)).filter((q):q is number[]=>!!q).map(q=>Math.hypot(q[0]-base[0],q[1]-base[1])/3).filter(d=>d>1e-6);
return lengths.length?Math.max(1,36/Math.min(...lengths)):1;
}
export function curveControlPoint(node:Knot,key:"incoming"|"outgoing",scale:number):number[] {
return [node.point[0]+node[key][0]*scale,node.point[1]+node[key][1]*scale,node.point[2]];
}
/** Drag starts at the displayed handle, but persists only the corresponding physical delta. */
export function moveCurveControl(vector:number[],start:number[],current:number[],scale:number):number[] {
return vector.map((v,k)=>v+(current[k]-start[k])/scale);
}
@@ -0,0 +1,172 @@
import {isMarking,isRigidMarking} from "./semanticFeaturePolicy";
export {isMarking,isRigidMarking,isEditableMarking} from "./semanticFeaturePolicy";
import {vectorOperation,knots,withKnots,insertKnot,type VectorOperation} from "./semanticVector";
import MARKING_TEMPLATES from "../../../../../src/k1link/simulation/ai_polygon/marking-templates.json";
import type { UrbanMap, UrbanMapFeature } from "./urbanMap";
export type Vertex = { feature_id:string; path:number; index:number; object?:true };
export type VertexOperation = Vertex & (
{kind:"move";position:number[]}|{kind:"insert";t:number}|{kind:"delete"}
);
export type SemanticOperation = VectorOperation | VertexOperation |
{kind:"retemplate";feature_id:string;template_id:string;frame:number[][]} |
{kind:"transform";feature_id:string;delta:number[];angle:number} |
{kind:"remove";feature_id:string} |
{kind:"place";feature_id:string;template_id:string;position:number[];surface:"gaussian-visual"};
export {MARKING_TEMPLATES};
export function semanticMembers(map:UrbanMap,id:string) {
const f=map.features.find(f=>f.id===id);
if(!f)return [];
const group=f.properties.semantic_element_id;
return group?map.features.filter(q=>q.properties.semantic_element_id===group):[f];
}
export function semanticPivot(features:UrbanMapFeature[]) {
const points=features.flatMap(f=>semanticPaths(f).flat());
return [0,1,2].map(k=>(Math.min(...points.map(p=>p[k]))+Math.max(...points.map(p=>p[k])))/2);
}
function objectOperation(map:UrbanMap,op:Exclude<SemanticOperation,VertexOperation|VectorOperation>):UrbanMap {
if(op.kind==="retemplate") {
const members=semanticMembers(map,op.feature_id),t=MARKING_TEMPLATES.templates.find(t=>t.id===op.template_id);
if(members.length!==1||members[0].properties.class!=="road_marking"||members[0].properties.review_status==="rejected"||!t||t.polygons.length!==1||op.frame.length!==3||op.frame.some(v=>v.length!==3||v.some(x=>!Number.isFinite(x)||Math.abs(x)>1e6)))throw new Error("Некорректная замена шаблона.");
const [o,a,b]=op.frame,la=Math.hypot(a[0],a[1]),lb=Math.hypot(b[0],b[1]);
if([la,lb].some(n=>n<.01||n>100)||Math.abs(a[0]*b[0]+a[1]*b[1])>1e-8*la*lb||a[0]*b[1]-a[1]*b[0]<=0||Math.abs(a[2])>la||Math.abs(b[2])>lb)throw new Error("Некорректные оси шаблона.");
const f=members[0],properties={...f.properties,template_id:t.id,confidence:null,confidence_status:"not-assessed" as const,review_status:"unreviewed" as const};delete properties.editor_curves;
return {...map,schema_version:"missioncore.urban-edit/v1",features:map.features.map(q=>q===f?{...f,properties,geometry:{type:"Polygon",coordinates:t.polygons[0].map(r=>r.map(p=>o.map((v,k)=>v+p[0]*a[k]+p[1]*b[k])))}}:q)};
}
if(op.kind==="place") {
const t=MARKING_TEMPLATES.templates.find(t=>t.id===op.template_id);
if(!t||op.position.length!==3||op.position.some(v=>!Number.isFinite(v))||map.features.some(f=>f.id===op.feature_id))throw new Error("Некорректное размещение.");
const features:UrbanMapFeature[]=t.polygons.map((rings,i)=>({id:i?`${op.feature_id}-${i}`:op.feature_id,
geometry:{type:"Polygon",coordinates:rings.map(r=>r.map(v=>[v[0]+op.position[0],v[1]+op.position[1],op.position[2]]))},
properties:{class:"road_marking",authority:"observation-only",route_permission:"unassigned",...(op.template_id==="linear_marking"?{subtype:"linear_marking"}:{semantic_element_id:op.feature_id}),
template_id:op.template_id,confidence:null,confidence_status:"not-assessed",review_status:"unreviewed"}}));
return {...map,schema_version:"missioncore.urban-edit/v1",features:[...map.features,...features]};
}
const members=semanticMembers(map,op.feature_id);
if(!members.length||members.some(f=>!isMarking(f)))throw new Error("Выберите элемент разметки.");
if(op.kind==="transform" && (op.delta.length!==2||op.delta.some(v=>!Number.isFinite(v))||!Number.isFinite(op.angle)))throw new Error("Некорректное перемещение.");
if(op.kind==="transform"&&!op.angle&&op.delta.every(v=>v===0))return map;
const centre=semanticPivot(members);
return {...map,schema_version:"missioncore.urban-edit/v1",features:map.features.map(f=>{
if(!members.includes(f))return f;
const properties={...f.properties,confidence:null,confidence_status:"not-assessed" as const,review_status:op.kind==="remove"?"rejected" as const:"unreviewed" as const};
if(op.kind==="remove")return {...f,properties};
const c=Math.cos(op.angle),s=Math.sin(op.angle);
const rings=semanticPaths(f).map(r=>r.map(p=>{
let [x,y]=p;
if(op.angle)[x,y]=[centre[0]+c*(x-centre[0])-s*(y-centre[1]),centre[1]+s*(x-centre[0])+c*(y-centre[1])];
return [x+op.delta[0],y+op.delta[1],p[2]];
}));
if(f.properties.editor_curves)properties.editor_curves=Object.fromEntries(Object.entries(f.properties.editor_curves).map(([path,nodes])=>[path,nodes.map(n=>{
const c=Math.cos(op.angle),s=Math.sin(op.angle),rotate=(v:number[])=>[c*v[0]-s*v[1],s*v[0]+c*v[1]];
const relative=rotate([n.point[0]-centre[0],n.point[1]-centre[1]]);
const point=op.angle?[centre[0]+relative[0]+op.delta[0],centre[1]+relative[1]+op.delta[1],n.point[2]]:[n.point[0]+op.delta[0],n.point[1]+op.delta[1],n.point[2]];
return {...n,point,incoming:op.angle?rotate(n.incoming):n.incoming,outgoing:op.angle?rotate(n.outgoing):n.outgoing};
})]));
return {...f,properties,geometry:f.geometry.type==="Polygon"?{type:"Polygon" as const,coordinates:rings}:{type:"LineString" as const,coordinates:rings[0]}};
})};
}
export interface SemanticRevision {
schema_version:"missioncore.semantic-editor/v1";
revision:string|null;model_sha256:string;latest_model_sha256:string;
model:UrbanMap;edited:UrbanMap;
history:{revision:string;created_at:string;actions:number}[];
learning:{state:string;dataset_ready:boolean};
}
export const semanticPaths=(f:UrbanMapFeature):number[][][]=>
f.geometry.type==="Polygon"?f.geometry.coordinates:[f.geometry.coordinates];
/** Copy only the edited feature. Untouched coordinates never round-trip through GPU. */
export function semanticOperation(map:UrbanMap, op:SemanticOperation):UrbanMap {
if(op.kind==="curve"||op.kind==="delete_vertices"||op.kind==="region"||op.kind==="translate"||op.kind==="translate_vertices"||op.kind==="duplicate_vertex"||op.kind==="duplicate_marking")return vectorOperation(map,op);
if(op.kind==="place"||op.kind==="transform"||op.kind==="remove"||op.kind==="retemplate")return objectOperation(map,op);
const feature=map.features.find(f=>f.id===op.feature_id);
if(!feature)throw new Error("Контур не найден.");
if(isRigidMarking(feature))throw new Error("Разметка редактируется целиком.");
if(feature.properties.editor_curves?.[String(op.path)]) {
let nodes=knots(feature,op.path).map(k=>({...k}));
if(!nodes[op.index])throw new Error("Точка не найдена.");
if(op.kind==="move") {
if(op.position.length!==3||op.position.some(v=>!Number.isFinite(v))||op.position[2]!==nodes[op.index].point[2])throw new Error("Редактирование сохраняет высоту.");
nodes[op.index]={...nodes[op.index],point:op.position};
} else if(op.kind==="insert")nodes=insertKnot(nodes,op.index,op.t,feature.geometry.type==="Polygon");
else nodes.splice(op.index,1);
return {...map,features:map.features.map(f=>f===feature?withKnots(f,op.path,nodes):f)};
}
const rings=semanticPaths(feature).map(p=>p.map(v=>[...v]));
const points=rings[op.path],closed=feature.geometry.type==="Polygon";
if(!points||op.index<0||op.index>=points.length-Number(closed))throw new Error("Точка не найдена.");
if(op.kind==="insert"){
if(op.index>=points.length-1||!(op.t>0&&op.t<1))throw new Error("Выберите середину сегмента.");
const a=points[op.index],b=points[op.index+1];
points.splice(op.index+1,0,a.map((v,k)=>v+op.t*(b[k]-v)));
}else if(op.kind==="move"){
if(op.position.length!==3||op.position.some(v=>!Number.isFinite(v))||op.position[2]!==points[op.index][2])
throw new Error("Редактирование в плане сохраняет высоту.");
if(points[op.index].every((v,k)=>v===op.position[k]))return map;
points[op.index]=[...op.position];
}else{
if(points.length<=(closed?4:2))throw new Error("В контуре недостаточно точек для удаления.");
points.splice(op.index,1);
}
if(closed)points[points.length-1]=[...points[0]];
const edited:UrbanMapFeature={...feature,geometry:closed?{type:"Polygon",coordinates:rings}:{type:"LineString",coordinates:rings[0]},
properties:{...feature.properties,confidence:null,confidence_status:"not-assessed",review_status:"unreviewed"}};
return {...map,schema_version:"missioncore.urban-edit/v1",features:map.features.map(f=>f===feature?edited:f)};
}
export interface SemanticDraft {
base:UrbanMap;map:UrbanMap;operations:SemanticOperation[];future:SemanticOperation[];
}
export const semanticDraft=(base:UrbanMap):SemanticDraft=>({base,map:base,operations:[],future:[]});
export function commitSemantic(s:SemanticDraft,op:SemanticOperation):SemanticDraft {
if(s.operations.length>=256)throw new Error("Сохраните изменения перед продолжением.");
const map=semanticOperation(s.map,op);
return map===s.map?s:{...s,map,operations:[...s.operations,op],future:[]};
}
export function undoSemantic(s:SemanticDraft):SemanticDraft {
const last=s.operations.at(-1);if(!last)return s;
const operations=s.operations.slice(0,-1);
return {...s,operations,map:operations.reduce(semanticOperation,s.base),future:[last,...s.future]};
}
export function redoSemantic(s:SemanticDraft):SemanticDraft {
const next=s.future[0];if(!next)return s;
return {...commitSemantic(s,next),future:s.future.slice(1)};
}
/** CSS pixel distance; backing buffer DPR must not change the capture radius. */
export function segmentHit(p:number[],a:number[],b:number[]) {
const dx=b[0]-a[0],dy=b[1]-a[1],l=dx*dx+dy*dy;
const t=l?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/l)):0;
return {t,distance:Math.hypot(p[0]-a[0]-t*dx,p[1]-a[1]-t*dy)};
}
export async function semanticRequest(worldId:string,body?:object,signal?:AbortSignal):Promise<SemanticRevision> {
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits`,{
method:body?"POST":"GET",cache:"no-store",signal,
...(body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}:{}),
});
if(!response.ok){
const error=await response.json().catch(()=>null);
throw new Error(typeof error?.detail==="string"?error.detail:"Не удалось открыть или сохранить правки.");
}
const result=await response.json() as SemanticRevision;
if(result.schema_version!=="missioncore.semantic-editor/v1")throw new Error("Неизвестная версия редактора.");
return result;
}
export interface SemanticDelivery {revision:string|null;state:string;training_eligible:false}
export async function semanticDelivery(worldId:string,signal:AbortSignal):Promise<SemanticDelivery> {
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/semantic-edits/status`,{
cache:"no-store",signal,
});
if(!response.ok)throw new Error("Не удалось обновить статус доставки.");
return await response.json() as SemanticDelivery;
}
export function semanticDeliveryLabel(state:string):string {
switch(state){
case "received":return "На Worker · в очереди подготовки";
case "building":return "Worker готовит пример";
case "draft-ready":return "Пример на Worker · ожидает проверки";
case "failed":return "Правки на Worker · подготовка не завершена";
case "unavailable":return "Правки сохранены · статус доставки недоступен";
default:return "Правки сохранены · ожидаем доставку на Worker";
}
}
@@ -0,0 +1,5 @@
import type {UrbanMapFeature} from "./urbanMap";
export const isMarking=(f:UrbanMapFeature)=>["road_marking","crosswalk_marking"].includes(f.properties.class);
/** Only explicit line classification admits vertex editing; unknown symbols stay rigid. */
export const isEditableMarking=(f:UrbanMapFeature)=>f.properties.class==="road_marking"&&f.properties.subtype==="linear_marking"&&(!f.properties.template_id||f.properties.template_id==="linear_marking")&&!f.properties.semantic_element_id;
export const isRigidMarking=(f:UrbanMapFeature)=>isMarking(f)&&!isEditableMarking(f);
@@ -0,0 +1,53 @@
import {editablePaths,knots,curvePoint} from "./semanticVector";
import {isMarking,isRigidMarking,segmentHit,type Vertex} from "./semanticEdits";
import type {UrbanMap,UrbanClassId} from "./urbanMap";
export interface SemanticHit {vertex:Vertex;distance:number;t:number;point?:number[];segment?:{a:number[];b:number[];start:number;end:number;t:number}}
export function semanticHits(map:UrbanMap,layers:UrbanClassId|readonly UrbanClassId[],at:number[],project:(v:number[])=>number[]|null,vertices:boolean,activeFeatures?:string|readonly string[]):SemanticHit[] {
const hits:SemanticHit[]=[];
const selected=new Set(typeof activeFeatures==="string"?[activeFeatures]:activeFeatures??[]);
for(const f of map.features) {
if(!(typeof layers==="string"?[layers]:layers).includes(f.properties.class as UrbanClassId)||f.properties.review_status==="rejected"||(!vertices&&isRigidMarking(f)))continue;
editablePaths(f).forEach((path,pathIndex)=>{
if(vertices&&!isRigidMarking(f)&&selected.has(f.id))path.slice(0,path.length-Number(f.geometry.type==="Polygon")).forEach((point,index)=>{
const p=project(point),distance=p?Math.hypot(p[0]-at[0],p[1]-at[1]):Infinity;
if(distance<=9)hits.push({vertex:{feature_id:f.id,path:pathIndex,index},distance,t:0,point});
});
const nodes=knots(f,pathIndex);
for(let i=0;i<path.length-1;i++) {
const n=nodes[i],next=nodes[(i+1)%nodes.length];
const steps=n.outgoing.some(Boolean)||next.incoming.some(Boolean)?16:1;
for(let j=0;j<steps;j++) {
const A=steps===1?path[i]:curvePoint(n,next,j/steps),B=steps===1?path[i+1]:curvePoint(n,next,(j+1)/steps);
const a=project(A),b=project(B);if(!a||!b)continue;
const hit=segmentHit(at,a,b);
if(hit.distance<=9)hits.push({vertex:{feature_id:f.id,path:pathIndex,index:i},distance:hit.distance,t:(j+hit.t)/steps,segment:{a:A,b:B,start:j/steps,end:(j+1)/steps,t:hit.t}});
}
}
});
// Pick the painted interior, excluding holes, for filled marking elements.
if(f.geometry.type==="Polygon") {
const inside=(ring:number[][])=>{
const p=ring.map(project);if(p.some(v=>!v))return false;
let yes=false;
for(let i=1;i<p.length;i++) {const a=p[i-1]!,b=p[i]!;
if((a[1]>at[1])!==(b[1]>at[1])&&at[0]<(b[0]-a[0])*(at[1]-a[1])/(b[1]-a[1])+a[0])yes=!yes;
}return yes;
};
if(inside(f.geometry.coordinates[0])&&!f.geometry.coordinates.slice(1).some(inside))hits.push({vertex:{feature_id:f.id,path:0,index:0},distance:0,t:0});
}
}
return hits.sort((a,b)=>Number(!!b.point)-Number(!!a.point)||a.distance-b.distance);
}
/** Preserve the gesture's grab offset. Non-selected axes never change. */
export function semanticDrag(origin:number[],start:number[],hit:number[],axis:"x"|"y"|"xy") {
return origin.map((v,k)=>k===2||(axis==="x"&&k!==0)||(axis==="y"&&k!==1)?v:v+(hit[k]-start[k]));
}
/** A body hit selects every editable knot; only a visible vertex hit selects one. */
export function semanticHitSelection(map:UrbanMap,hit:SemanticHit):Vertex[] {
const f=map.features.find(f=>f.id===hit.vertex.feature_id);
if(!f||f.properties.review_status==="rejected")return [];
if(hit.point)return [hit.vertex];
if(isMarking(f))return [{...hit.vertex,object:true}];
return editablePaths(f).flatMap((_,path)=>knots(f,path).map((_,index)=>({feature_id:f.id,path,index})));
}
@@ -0,0 +1,146 @@
import {isMarking,isRigidMarking} from "./semanticFeaturePolicy";
import type {UrbanMap,UrbanMapFeature} from "./urbanMap";
export interface Knot {point:number[]; incoming:number[]; outgoing:number[]}
export interface CurveOperation {kind:"curve";feature_id:string;path:number;index:number;incoming:number[];outgoing:number[]}
export interface GroupDelete {kind:"delete_vertices";vertices:{feature_id:string;path:number;index:number}[]}
export interface RegionOperation {kind:"region";feature_id:string;token:string;mode:"union"|"difference";brush:number[][];polygons:number[][][][]}
export type SemanticAxis="x"|"y"|"z"|"xy"|"xz"|"yz";
export type TranslateOperation = ({kind:"translate"}|{kind:"translate_vertices"}) & {feature_id:string;vertices:{feature_id:string;path:number;index:number}[];delta:number[];axis:SemanticAxis}
export interface DuplicateVertexOperation {kind:"duplicate_vertex";feature_id:string;path:number;index:number;delta:number[];axis:SemanticAxis;side?:"before"|"after"}
/** Omitted side is the immutable legacy replay contract. New gestures persist their choice. */
export const duplicateIndex=(index:number,closed:boolean,side?:"before"|"after")=>side?index+Number(side==="after"):!closed&&index===0?0:index+1;
/** Compare local arms, not world-axis signs or unequal segment lengths. */
export function duplicateSide(nodes:Knot[],index:number,closed:boolean,delta:number[]):"before"|"after" {
const node=nodes[index];
const alignment=(neighbor:Knot|undefined,handle:number[])=>{
if(!neighbor)return null;
const arm=handle.some(Boolean)?handle:neighbor.point.slice(0,2).map((v,k)=>v-node.point[k]);
const length=Math.hypot(...arm);
return length?arm.reduce((sum,v,k)=>sum+v*delta[k],0)/length:0;
};
const before=alignment(index>0?nodes[index-1]:closed?nodes.at(-1):undefined,node.incoming);
const after=alignment(index+1<nodes.length?nodes[index+1]:closed?nodes[0]:undefined,node.outgoing);
// At an open end a sideways drag continues around the corner. Insert inward
// only when movement along the existing arm dominates its perpendicular part.
// A tiny inward component must not turn an extension into a folded segment.
const inward=Math.hypot(delta[0],delta[1])/Math.SQRT2;
if(before===null)return after!==null&&after>inward?"after":"before";
if(after===null)return before>inward?"before":"after";
return before>after?"before":"after";
}
export interface DuplicateMarkingOperation {kind:"duplicate_marking";feature_id:string;new_feature_id:string;delta:number[];axis:SemanticAxis}
export type VectorOperation=DuplicateMarkingOperation|CurveOperation|GroupDelete|RegionOperation|TranslateOperation|DuplicateVertexOperation;
export const geometryPaths=(f:UrbanMapFeature):number[][][]=>f.geometry.type==="Polygon"?f.geometry.coordinates:[f.geometry.coordinates];
export function knots(f:UrbanMapFeature,path:number):Knot[] {
const saved=f.properties.editor_curves?.[String(path)];
return saved??geometryPaths(f)[path].slice(0,geometryPaths(f)[path].length-Number(f.geometry.type==="Polygon")).map(point=>({point,incoming:[0,0],outgoing:[0,0]}));
}
export const editablePaths=(f:UrbanMapFeature)=>geometryPaths(f).map((_,i)=>{
const points=knots(f,i).map(k=>k.point);return f.geometry.type==="Polygon"?[...points,points[0]]:points;
});
export function curvePoint(a:Knot,b:Knot,t:number) {
const u=1-t;
return [0,1].map(k=>u*u*u*a.point[k]+3*u*u*t*(a.point[k]+a.outgoing[k])+3*u*t*t*(b.point[k]+b.incoming[k])+t*t*t*b.point[k]).concat(a.point[2]+t*(b.point[2]-a.point[2]));
}
export function curvePath(nodes:Knot[],closed:boolean) {
const path:number[][]=[];
for(let i=0;i<nodes.length-Number(!closed);i++) {
const a=nodes[i],b=nodes[(i+1)%nodes.length];path.push(a.point);
if(a.outgoing.some(Boolean)||b.incoming.some(Boolean))for(let j=1;j<16;j++)path.push(curvePoint(a,b,j/16));
}
path.push(closed?nodes[0].point:nodes.at(-1)!.point);return path;
}
export function withKnots(f:UrbanMapFeature,path:number,nodes:Knot[]):UrbanMapFeature {
const closed=f.geometry.type==="Polygon";
if(nodes.length<(closed?3:2))throw new Error("В контуре недостаточно точек. Выберите весь контур для удаления.");
const paths=geometryPaths(f).slice();paths[path]=curvePath(nodes,closed);
return {...f,geometry:closed?{type:"Polygon",coordinates:paths}:{type:"LineString",coordinates:paths[0]},properties:{...f.properties,
editor_curves:{...f.properties.editor_curves,[String(path)]:nodes},confidence:null,confidence_status:"not-assessed",review_status:"unreviewed"}};
}
export function vectorOperation(map:UrbanMap,op:VectorOperation):UrbanMap {
let features=map.features;
if(op.kind==="duplicate_marking") {
const selected=features.find(f=>f.id===op.feature_id);
if(!selected||selected.properties.review_status==="rejected"||!isMarking(selected)||!/^user-[a-zA-Z0-9-]{16,64}$/.test(op.new_feature_id))throw new Error("Выберите элемент разметки.");
if(!["x","y","z","xy","xz","yz"].includes(op.axis)||op.delta.length!==3||op.delta.some((v,k)=>!Number.isFinite(v)||(!op.axis.includes("xyz"[k])&&v!==0)))throw new Error("Некорректное перемещение по осям.");
if(op.delta.every(v=>v===0))return map;
const group=selected.properties.semantic_element_id,members=group?features.filter(f=>f.properties.semantic_element_id===group):[selected];
const moved=vectorOperation({...map,features:members},{kind:"translate",feature_id:op.feature_id,vertices:[],axis:op.axis,delta:op.delta});
const copies=moved.features.map((f,i)=>{const q=structuredClone(f);q.id=i?`${op.new_feature_id}-${i}`:op.new_feature_id;
if(group)q.properties.semantic_element_id=op.new_feature_id;
delete q.properties.height_projection;q.properties.height_source="human-copy-unverified";return q;});
if(copies.some(q=>features.some(f=>f.id===q.id||f.properties.semantic_element_id===op.new_feature_id)))throw new Error("Элемент уже существует.");
features=[...features,...copies];
} else if(op.kind==="duplicate_vertex") {
const f=features.find(f=>f.id===op.feature_id);
if(!f||f.properties.review_status==="rejected"||isRigidMarking(f))throw new Error("Выберите точку редактируемого контура.");
if(!Number.isInteger(op.path)||!geometryPaths(f)[op.path]||!Number.isInteger(op.index))throw new Error("Точка не найдена.");
const nodes=knots(f,op.path),n=nodes[op.index];if(!n)throw new Error("Точка не найдена.");
if(!["x","y","z","xy","xz","yz"].includes(op.axis)||op.delta.length!==3||op.delta.some((v,k)=>!Number.isFinite(v)||(!op.axis.includes("xyz"[k])&&v!==0)))throw new Error("Некорректное перемещение по осям.");
if(op.delta.every(v=>v===0))return map;
if(!op.delta[0]&&!op.delta[1])throw new Error("Продолжение контура должно иметь длину в плане: используйте X, Y или плоскость.");
if(nodes.length>=4095)throw new Error("Достигнут предел числа точек контура.");
if(op.side!==undefined&&op.side!=="before"&&op.side!=="after")throw new Error("Некорректная сторона вставки.");
const next=nodes.slice(),index=duplicateIndex(op.index,f.geometry.type==="Polygon",op.side);
next.splice(index,0,{point:n.point.map((v,k)=>op.delta[k]===0?v:v+op.delta[k]),incoming:[...n.incoming],outgoing:[...n.outgoing]});
const q=withKnots(f,op.path,next);delete q.properties.height_projection;q.properties.height_source="human-vertex-extension-unverified";
features=features.map(v=>v===f?q:v);
} else if(op.kind==="translate"||op.kind==="translate_vertices") {
if(op.delta.length!==3||op.delta.some((v,k)=>!Number.isFinite(v)||(!op.axis.includes("xyz"[k])&&v!==0)))throw new Error("Некорректное перемещение по осям.");
if(op.delta.every(v=>v===0))return map;
const selected=features.find(f=>f.id===op.feature_id);if(!selected)throw new Error("Элемент не найден.");
const group=selected.properties.semantic_element_id;
const marking=op.kind==="translate"&&isMarking(selected);
if(op.kind==="translate_vertices"&&op.vertices.some(v=>{const f=features.find(f=>f.id===v.feature_id);return !f||isRigidMarking(f);}))throw new Error("Выберите вершины редактируемого контура.");
features=features.map(f=>{
if(marking&&(f.id===selected.id||(group&&f.properties.semantic_element_id===group))) {
const paths=geometryPaths(f).map(p=>p.map(v=>v.map((x,k)=>x+op.delta[k])));
const properties={...f.properties,confidence:null,confidence_status:"not-assessed" as const,review_status:"unreviewed" as const};
if(f.properties.editor_curves)properties.editor_curves=Object.fromEntries(Object.entries(f.properties.editor_curves).map(([p,nodes])=>[p,nodes.map(n=>({...n,point:n.point.map((v,k)=>v+op.delta[k])}))]));
return {...f,geometry:f.geometry.type==="Polygon"?{type:"Polygon",coordinates:paths}:{type:"LineString",coordinates:paths[0]},properties};
}
if(marking)return f;
let q=f;
geometryPaths(f).forEach((_,p)=>{const indices=new Set(op.vertices.filter(v=>v.feature_id===f.id&&v.path===p).map(v=>v.index));
if(indices.size)q=withKnots(q,p,knots(f,p).map((n,i)=>indices.has(i)?{...n,point:n.point.map((v,k)=>v+op.delta[k])}:n));
});return q;
});
} else if(op.kind==="region") {
const previous=features.find(f=>f.id===op.feature_id);
if(previous&&!['pedestrian_area','sidewalk'].includes(previous.properties.class))throw new Error("Выберите пешеходную область.");
const properties={...previous?.properties,class:previous?.properties.class??"pedestrian_area",authority:"observation-only" as const,route_permission:"unassigned" as const,confidence:null,confidence_status:"not-assessed" as const,review_status:"unreviewed" as const,editor_curves:undefined,region_origin_id:op.feature_id};
const created=op.polygons.map((coordinates,i)=>({id:i?`${op.feature_id}-${op.token}-${i}`:op.feature_id,properties,geometry:{type:"Polygon" as const,coordinates}}));
features=features.filter(f=>f!==previous);
if(created.length)features=[...features,...created];
else if(previous)features=[...features,{...previous,properties:{...properties,review_status:"rejected"}}];
} else if(op.kind==="curve") {
const f=features.find(f=>f.id===op.feature_id);if(!f)throw new Error("Контур не найден.");
if(isRigidMarking(f))throw new Error("Разметка редактируется целиком.");
const nodes=knots(f,op.path).map(k=>({...k}));
if(nodes[op.index].incoming.every((v,k)=>v===op.incoming[k])&&nodes[op.index].outgoing.every((v,k)=>v===op.outgoing[k]))return map;
nodes[op.index]={...nodes[op.index],incoming:op.incoming,outgoing:op.outgoing};
const edited=withKnots(f,op.path,nodes);features=features.map(q=>q===f?edited:q);
} else {
features=features.map(f=>{
const chosen=op.vertices.filter(v=>v.feature_id===f.id);if(!chosen.length)return f;
if(isRigidMarking(f))throw new Error("Разметка редактируется целиком.");
const paths=geometryPaths(f),all=paths.every((_,p)=>knots(f,p).every((_,i)=>chosen.some(v=>v.path===p&&v.index===i)));
if(all)return {...f,properties:{...f.properties,review_status:"rejected" as const}};
let edited=f;
paths.forEach((_,p)=>{if(!chosen.some(v=>v.path===p))return;
const nodes=knots(f,p).filter((_,i)=>!chosen.some(v=>v.path===p&&v.index===i));edited=withKnots(edited,p,nodes);
});return edited;
});
}
return {...map,schema_version:"missioncore.urban-edit/v1",features};
}
/** De Casteljau inserts an anchor without changing the physical cubic. */
export function insertKnot(nodes:Knot[],i:number,t:number,closed:boolean) {
const j=(i+1)%nodes.length;if(!closed&&j===0)throw new Error("Выберите сегмент.");
const a=nodes[i],b=nodes[j],mix=(x:number[],y:number[])=>x.map((v,k)=>v+t*(y[k]-v));
const A=a.point.slice(0,2),B=A.map((v,k)=>v+a.outgoing[k]),D=b.point.slice(0,2),C=D.map((v,k)=>v+b.incoming[k]);
const ab=mix(A,B),bc=mix(B,C),cd=mix(C,D),abc=mix(ab,bc),bcd=mix(bc,cd),point=mix(abc,bcd);
const sub=(x:number[],y:number[])=>x.map((v,k)=>v-y[k]);
const next=nodes.map(k=>({...k}));next[i]={...a,outgoing:sub(ab,A)};next[j]={...b,incoming:sub(cd,D)};
next.splice(i+1,0,{point:[...point,a.point[2]+t*(b.point[2]-a.point[2])],incoming:sub(abc,point),outgoing:sub(bcd,point)});return next;
}
@@ -0,0 +1,28 @@
import type {UrbanClassId} from "./urbanMap";
import type {EditorProjection} from "./editorProjection";
import type {SemanticAxis} from "./semanticVector";
export interface SimulationLayout {
mode:"view"|"semantic"|"planning"; projection:EditorProjection;
sceneLayers:{gaussian:boolean;collision:boolean}; infrastructure:boolean; memory:boolean;
layers:UrbanClassId[]; urbanLayers:UrbanClassId[];
visible:{model:boolean;user:boolean}; axis:SemanticAxis; areaMode:"union"|"difference";
}
const classes:UrbanClassId[]=["road_boundary","pedestrian_boundary","building_facade","curb","curb_cut","sidewalk","pedestrian_area","carriageway","service_lane","bike_lane","parking","crosswalk_area","crosswalk_marking","road_marking"];
export const DEFAULT_SIMULATION_LAYOUT:SimulationLayout={mode:"view",projection:"perspective",sceneLayers:{gaussian:true,collision:false},infrastructure:false,memory:false,layers:["road_boundary"],urbanLayers:classes,visible:{model:false,user:true},axis:"xy",areaMode:"union"};
export function normalizeSimulationLayout(raw:unknown):SimulationLayout {
const v=(raw&&typeof raw==="object"?raw:{}) as Partial<SimulationLayout>,d=DEFAULT_SIMULATION_LAYOUT;
const pick=<T extends string>(x:unknown,values:readonly T[],fallback:T):T=>values.includes(x as T)?x as T:fallback;
const bool=(x:unknown,f:boolean)=>typeof x==="boolean"?x:f;
const layers=(x:unknown,f:UrbanClassId[])=>Array.isArray(x)?Array.from(new Set(x.filter((k):k is UrbanClassId=>classes.includes(k)))):f;
return {mode:pick(v.mode,["view","semantic","planning"],d.mode),projection:pick(v.projection,["perspective","orthographic"],d.projection),
sceneLayers:{gaussian:bool(v.sceneLayers?.gaussian,true),collision:bool(v.sceneLayers?.collision,false)},infrastructure:bool(v.infrastructure,false),memory:bool(v.memory,false),
layers:layers(v.layers,d.layers),urbanLayers:layers(v.urbanLayers,d.urbanLayers),visible:{model:bool(v.visible?.model,false),user:bool(v.visible?.user,true)},
axis:pick(v.axis,["x","y","z","xy","xz","yz"],d.axis),areaMode:pick(v.areaMode,["union","difference"],d.areaMode)};
}
export interface SceneView {position:number[];quaternion:number[];anchor:number[]|null;projection:EditorProjection;span:number|null;clip:[number|null,number|null]}
export function normalizeSceneView(raw:unknown):SceneView|null {
const v=raw as SceneView|undefined;
const vec=(x:unknown,n:number)=>Array.isArray(x)&&x.length===n&&x.every(k=>typeof k==="number"&&Number.isFinite(k)&&Math.abs(k)<1e6);
if(!v||!vec(v.position,3)||!vec(v.quaternion,4)||Math.abs(Math.hypot(...v.quaternion)-1)>1e-5||v.anchor!==null&&!vec(v.anchor,3)||!["perspective","orthographic"].includes(v.projection)||v.span!==null&&!(Number.isFinite(v.span)&&v.span>0&&v.span<=5000)||!Array.isArray(v.clip)||v.clip.length!==2||v.clip.some(x=>x!==null&&!(Number.isFinite(x)&&Math.abs(x)<1e6))||(v.clip[0]??-Infinity)>(v.clip[1]??Infinity))return null;
return {position:v.position,quaternion:v.quaternion,anchor:v.anchor,projection:v.projection,span:v.span,clip:v.clip};
}
@@ -0,0 +1,34 @@
import type { UrbanMap, UrbanMapFeature } from "./urbanMap";
export interface PlaceAttempt {
id:string;xyz:number[];origin:number[];reason:string;status:"unresolved"|"revisited-successfully";
first_seen:number;last_seen:number;count:number;run_id:string;observation_id:string;
}
export interface SpatialExperience {
schema_version:"missioncore.spatial-experience/v1";
source:{world_sha256:string;collider_sha256:string;robot_sha256:string};
visits:{id:string;xyz:number[];count:number;last_seen:number}[];
attempts:PlaceAttempt[];
}
const REASONS:Record<string,string>={"no-path":"Путь не найден","no-permitted-goal":"Не найдена разрешённая поверхность","footprint":"Недостаточно места для корпуса",
"observed-unsafe-support":"Ненадёжная опора","forbidden-surface-sweep":"Запрещённая поверхность",
"detected-object-sweep":"Препятствие на пути"};
export function attemptLabel(a:PlaceAttempt) {
return `${a.status==="revisited-successfully"?"Позже проехал":"Попытка проезда"} · ${REASONS[a.reason]??a.reason} · ${a.count} · ${new Date(a.last_seen*1000).toLocaleString("ru")}`;
}
/** Cell marks and attempted direction; no invented connections between visits. */
export function experienceMap(memory:SpatialExperience):UrbanMap {
const feature=(id:string,cls:string,points:number[][]):UrbanMapFeature=>({id,
properties:{class:cls,authority:"observation-only",route_permission:"unassigned"},geometry:{type:"LineString",coordinates:points}});
return {schema_version:"missioncore.urban-map/v2",source:memory.source,coverage:{cell_m:.5,accepted_cells:memory.visits.length},features:[
...memory.visits.map(v=>feature(v.id,"visited",[[v.xyz[0]-.12,v.xyz[1],v.xyz[2]],[v.xyz[0]+.12,v.xyz[1],v.xyz[2]]])),
...memory.attempts.map(a=>feature(a.id,a.status==="unresolved"?"attempt":"revisited",[a.origin,a.xyz])),
]};
}
export async function loadExperience(worldId:string,worldSha:string,signal:AbortSignal):Promise<SpatialExperience|null> {
const response=await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/spatial-experience`,{signal,cache:"no-store"});
if(response.status===404)return null;
if(!response.ok)throw new Error("Не удалось загрузить память локации.");
const data=await response.json() as SpatialExperience;
if(data.schema_version!=="missioncore.spatial-experience/v1"||data.source.world_sha256!==worldSha)throw new Error("Память относится к другой локации.");
return data;
}
@@ -0,0 +1,62 @@
export interface UrbanMapFeature {
id: string;
properties: { subtype?:string; height_source?:string; editor_curves?:Record<string,import("./semanticVector").Knot[]>; semantic_element_id?:string; template_id?:string; class: string; authority: "observation-only"; route_permission: "unassigned"; height_projection?: {method:string;surface_sha256:string}; confidence?: number|null; confidence_status?: "not-assessed"; review_status?: "unreviewed"|"accepted"|"rejected" };
geometry: { type: "Polygon"; coordinates: number[][][] } | { type: "LineString"; coordinates: number[][] };
}
export interface UrbanMap {
schema_version: "missioncore.urban-map/v1"|"missioncore.urban-map/v2"|"missioncore.urban-map/v3"|"missioncore.urban-edit/v1";
source: { world_sha256: string; collider_sha256: string|null };
features: UrbanMapFeature[];
analysis?: {scope:"whole-scene";tiles_total:number;tiles_mapped?:number;tiles_without_ground?:number};
coverage: { accepted_cells: number; cell_m: number; kind?: "objects-only" };
}
export const URBAN_COLORS: Record<string, [number, number, number]> = {
visited: [60,220,200], attempt: [245,130,48], revisited: [245,245,245],
curb: [245,130,48], curb_cut: [255,150,80], sidewalk: [60,220,200], pedestrian_area: [60,220,200],
carriageway: [90,130,200], service_lane: [110,150,210], bike_lane: [150,110,220], parking: [140,140,150],
crosswalk_area: [255,225,35], crosswalk_marking: [255,225,35], road_marking: [245,245,245],
};
// The new contours share the existing semantic renderer palette.
URBAN_COLORS.road_boundary = URBAN_COLORS.curb;
URBAN_COLORS.pedestrian_boundary = URBAN_COLORS.pedestrian_area;
URBAN_COLORS.building_facade = URBAN_COLORS.carriageway;
URBAN_COLORS.road_marking = URBAN_COLORS.crosswalk_marking;
export const URBAN_LABELS = {
road_boundary: "Граница дороги", pedestrian_boundary: "Граница пешеходной зоны", building_facade: "Фасад",
curb: "Бордюр", curb_cut: "Съезд", sidewalk: "Тротуар", pedestrian_area: "Пешеходная зона",
carriageway: "Проезжая часть", service_lane: "Служебный проезд", bike_lane: "Велополоса", parking: "Парковка",
crosswalk_area: "Переход", crosswalk_marking: "Зебра", road_marking: "Разметка",
} as const;
export async function loadUrbanMap(worldId: string, worldSha: string, signal: AbortSignal): Promise<UrbanMap|null> {
const response = await fetch(`/api/v1/ai-polygon/worlds/${encodeURIComponent(worldId)}/urban-map`, { signal, cache: "no-store" });
if (response.status === 404) return null;
if (!response.ok) throw new Error("Не удалось загрузить карту инфраструктуры.");
const result = await response.json() as UrbanMap;
if (!["missioncore.urban-map/v1","missioncore.urban-map/v2","missioncore.urban-map/v3"].includes(result.schema_version) || result.source.world_sha256 !== worldSha) {
throw new Error("Карта относится к другой версии сцены.");
}
return result;
}
export function urbanPaths(feature: UrbanMapFeature): number[][][] {
return feature.properties.review_status === "rejected" ? [] : feature.geometry.type === "Polygon" ? feature.geometry.coordinates : [feature.geometry.coordinates];
}
export type UrbanClassId = keyof typeof URBAN_LABELS;
export const ALL_URBAN_CLASSES = Object.keys(URBAN_LABELS) as UrbanClassId[];
/** Legend choices describe the source map, even when every class is hidden. */
export function availableUrbanClasses(map:UrbanMap):UrbanClassId[] {
const present=new Set(map.features.filter(f=>f.properties.review_status!=="rejected").map(f=>f.properties.class));
return ALL_URBAN_CLASSES.filter(id=>present.has(id));
}
export function visibleUrbanMap(map:UrbanMap, selected:readonly UrbanClassId[]):UrbanMap {
return {...map,features:map.features.filter(f=>f.properties.review_status!=="rejected" && selected.includes(f.properties.class as UrbanClassId))};
}
/** Bounded framing coordinates, including polygon holes and open line ends. */
export function urbanExtent(map:UrbanMap):number[][] {
const low=[Infinity,Infinity,Infinity],high=[-Infinity,-Infinity,-Infinity];
for(const feature of map.features) for(const ring of urbanPaths(feature)) for(const point of ring)
for(let i=0;i<3;i++){low[i]=Math.min(low[i],point[i]);high[i]=Math.max(high[i],point[i]);}
return Number.isFinite(low[0])?[low,high]:[];
}
@@ -0,0 +1,13 @@
import { ShapeUtils, Vector2 } from "three";
import type { UrbanMapFeature } from "./urbanMap";
/** A coverage polygon is a surface, never a surveyed curb. Preserve its holes. */
export function urbanSurface(feature: UrbanMapFeature): { positions: number[]; indices: number[] } | null {
if (feature.properties.review_status === "rejected" || feature.properties.class !== "pedestrian_area"
|| feature.geometry.type !== "Polygon" || !feature.properties.height_projection) return null;
const rings = feature.geometry.coordinates.map(ring => ring.slice(0, -1));
if (!rings.length || rings.some(ring => ring.length < 3)) return null;
const planar = rings.map(ring => ring.map(point => new Vector2(point[0], point[1])));
const faces = ShapeUtils.triangulateShape(planar[0], planar.slice(1));
return { positions: rings.flat().flat(), indices: faces.flat() };
}
+30 -3
View File
@@ -4,6 +4,14 @@
.ai-polygon__content { min-height: 0; overflow: auto; overscroll-behavior: contain; padding-bottom: 1rem; }
.ai-polygon__head, .ai-polygon__row { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; }
.ai-polygon__actions, .ai-polygon__facts { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; }
/* Header selectors and available actions share the window action row. */
.ai-polygon__location-actions { margin-left: auto; justify-content: flex-end; }
.ai-polygon__planner-actions { justify-content: flex-end; }
.ai-polygon__mode-field { width: 15rem; min-width: 0; }
.ai-polygon__task-field { min-width: 0; }
.ai-polygon__actions:has(> .ai-polygon__mode-field) { align-items: flex-start; }
.ai-polygon__location-actions > .ai-polygon__actions:empty,
.ai-polygon__planner-actions > .ai-polygon__actions:empty { display: none; }
.ai-polygon__robot-select { width: 12rem; flex: 0 0 12rem; }
.ai-polygon__report { font-size: var(--nodedc-font-size-sm); }
.ai-polygon__report dl { margin: 0; display: grid; gap: .5rem; }
@@ -73,11 +81,20 @@
/* View controls float above the render target; there is no separate header strip. */
.ai-simulation__view-tools { max-width: calc(100% - 6rem); flex-wrap: wrap; justify-content: flex-end; position: absolute; z-index: 3; top: .5rem; right: .5rem; display: flex; align-items: center; gap: .5rem; }
.ai-simulation__view-tools > .nodedc-select-anchor { width: 10rem; }
.ai-simulation__display-tools { display: flex; align-items: center; justify-content: flex-end; gap: .5rem; }
.ai-simulation__display-tools > .nodedc-select-anchor { width: 10rem; }
.ai-simulation__view-tools--planning { flex-direction: row-reverse; justify-content: flex-start; align-items: flex-start; }
.ai-simulation__view-tools--planning .ai-simulation__display-tools { flex: 0 0 auto; max-width: 100%; }
.ai-simulation__speed { position: absolute; left: .75rem; bottom: .75rem; pointer-events: none; font-size: var(--nodedc-font-size-sm); }
/* Equal visible padding on all three sides; owner requested twice the radius-centred inset. */
.ai-local-editor .ai-route__height { --ai-clip-inset: calc(var(--nodedc-radius-panel) * 2 - var(--nodedc-control-height) * .4); top: var(--ai-clip-inset); bottom: var(--ai-clip-inset); left: var(--ai-clip-inset); right: auto; width: calc(var(--nodedc-control-height) * .4); }
.ai-local-editor__tools { display: flex; align-items: center; gap: .5rem; }
.ai-local-editor .ai-route__height { --ai-clip-inset: calc(var(--nodedc-radius-panel) * 2 - var(--nodedc-control-height) * .4); top: max(33.333%, calc(var(--planner-cube-size, 66px) + 20px)); bottom: var(--ai-clip-inset); left: var(--ai-clip-inset); right: auto; width: calc(var(--nodedc-control-height) * .4); }
.ai-local-editor__tools { display: contents; }
.ai-local-editor__tool-row { flex: 0 0 auto; display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: .5rem; max-width: 100%; }
.ai-local-editor__layers { max-width: 100%; overflow-x: auto; flex-shrink: 0; }
.ai-local-editor__legend { position: absolute; z-index: 2; bottom: .75rem; left: 50%; transform: translateX(-50%); width: max-content; max-width: calc(100% - 9rem); display: flex; flex-direction: column; align-items: center; gap: .5rem; }
.ai-local-editor__legend-controls { max-width: 100%; flex-wrap: wrap; justify-content: center; }
.ai-local-editor__legend-swatch { display: inline-block; width: .65rem; height: .65rem; flex: 0 0 .65rem; border-radius: 50%; }
.ai-local-editor > .ai-local-editor__loading { position: absolute; inset: 0; background: var(--nodedc-canvas); }
.ai-local-editor .ai-route__tools { left: 5.5rem; right: .75rem; }
/* The renderer has no perimeter; canonical controls retain their focus indicators. */
.ai-local-editor canvas { outline: none; }
@@ -171,3 +188,13 @@
@container (max-width: 32rem) {
.ai-polygon__run-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
/* Caption-bearing selectors align window actions to the control row. */
.nodedc-application-panel__actions:has(.ai-polygon__mode-field) { align-items: flex-start; }
.ai-local-editor__marking-template { flex: 0 1 12rem; width: 12rem; max-width: 100%; }
.semantic-tools__menu { display: flex; flex-direction: column; gap: .25rem; }
.ai-polygon__semantic-actions { display: contents; }
.ai-local-editor__cube { position: absolute; top: 8px; left: 4px; z-index: 5; }
@@ -305,8 +305,6 @@
}
.m4-replay-threat-visual__layer-with-settings > .nodedc-icon-button {
width: 1.75rem;
height: 1.75rem;
border: 0;
outline: 0;
box-shadow: none;
+3 -28
View File
@@ -188,24 +188,6 @@
gap: 0.4rem;
}
.polygon-rover-scene__toolbar button {
border: 1px solid rgb(255 255 255 / 0.14);
border-radius: 999px;
background: rgb(7 12 18 / 0.76);
color: var(--nodedc-text-secondary);
padding: 0.38rem 0.62rem;
font: inherit;
font-size: 0.54rem;
line-height: 1;
backdrop-filter: blur(16px);
cursor: pointer;
}
.polygon-rover-scene__toolbar button:hover {
border-color: rgb(var(--nodedc-accent-rgb) / 0.5);
color: var(--nodedc-text-primary);
}
.polygon-rover-scene__help {
bottom: 0.75rem;
left: 0.75rem;
@@ -3685,8 +3667,7 @@
}
.lidar-ground-modes button,
.lidar-ground-frame-control button,
.lidar-ground-scene__toolbar button {
.lidar-ground-frame-control button {
border: 0;
border-radius: 999px;
background: transparent;
@@ -3699,16 +3680,14 @@
.lidar-ground-modes button:hover,
.lidar-ground-modes button[data-active="true"],
.lidar-ground-frame-control button:hover:not(:disabled),
.lidar-ground-scene__toolbar button:hover {
.lidar-ground-frame-control button:hover:not(:disabled) {
background: rgb(255 255 255 / 0.11);
color: var(--nodedc-text-primary);
outline: none;
}
.lidar-ground-modes button:focus-visible,
.lidar-ground-frame-control button:focus-visible,
.lidar-ground-scene__toolbar button:focus-visible {
.lidar-ground-frame-control button:focus-visible {
background: rgb(255 255 255 / 0.14);
outline: none;
}
@@ -3766,10 +3745,6 @@
backdrop-filter: blur(14px);
}
.lidar-ground-scene__toolbar button {
background: rgb(255 255 255 / 0.06);
}
.lidar-ground-scene__error {
position: absolute;
inset: 0;
@@ -439,7 +439,7 @@ export function E30EvidencePointCloud({ detail }: E30EvidencePointCloudProps) {
<p className="e30-evidence-scene__error">{renderError}</p>
) : null}
</div>
<div className="e30-evidence-scene__toolbar">
<div className="e30-evidence-scene__toolbar nodedc-viewport-controls">
<Button
variant="secondary"
size="compact"
@@ -1,3 +1,4 @@
import { Button } from "@nodedc/ui-react";
import { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
@@ -591,8 +592,8 @@ export function LidarGroundPointCloud({
<p className="lidar-ground-scene__error">{renderError}</p>
) : null}
</div>
<div className="lidar-ground-scene__toolbar">
<button type="button" onClick={resetCamera}>Сбросить ракурс</button>
<div className="lidar-ground-scene__toolbar nodedc-viewport-controls">
<Button onClick={resetCamera}>Сбросить ракурс</Button>
<span>ЛКМ · вращение</span>
<span>Колесо · масштаб</span>
<span>ПКМ · панорама</span>
@@ -1,3 +1,4 @@
import { Button } from "@nodedc/ui-react";
import { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
@@ -355,11 +356,11 @@ export function PolygonRoverScene({
<div ref={hostRef} className="polygon-rover-scene__viewport">
{renderError ? <p className="polygon-rover-scene__error">{renderError}</p> : null}
</div>
<div className="polygon-rover-scene__toolbar">
<button type="button" onClick={() => setFollowRover((value) => !value)}>
<div className="polygon-rover-scene__toolbar nodedc-viewport-controls">
<Button onClick={() => setFollowRover((value) => !value)}>
{followRover ? "Следовать за ровером" : "Свободная камера"}
</button>
<button type="button" onClick={resetCamera}>Сбросить ракурс</button>
</Button>
<Button onClick={resetCamera}>Сбросить ракурс</Button>
</div>
<div className="polygon-rover-scene__help">
<span>ЛКМ · вращение</span>
@@ -457,7 +457,7 @@ export function WorkspaceRenderer(props: WorkspaceRendererProps) {
/>
);
case "simulations":
return <SimulationWorkspace />;
return <SimulationWorkspace headerToolsHost={props.headerToolsHost} />;
case "observatory":
return <ObservatoryWorkspace definition={props.definition} />;
case "device":
@@ -1,4 +1,7 @@
import {Button,Icon,IconButton,ResourceRow,StatusBadge,Window} from '@nodedc/ui-react';
import {useState} from 'react';
import {useBoardNetwork} from '../../core/fleet/useBoardNetwork';
import {BoardNetworkSettings} from './BoardNetworkSettings';
import {Button,Icon,IconButton,ResourceRow,StatusBadge,FeatureSettingsWindow,WindowFooterActions} from '@nodedc/ui-react';
import type {Vehicle} from '../../core/fleet/useFleet';
export const boardStatus=(item:Vehicle,available=true)=>item.enrollment==='pending'?'Подтверждаем привязку':item.enrollment==='revoked'?'Не привязан':item.enrollment==='failed'?'Привязка не завершена':item.connectivity==='online'?(available?'В сети':'Не в сети'):'Не в сети';
@@ -9,13 +12,19 @@ export function BoardComputerRow({vehicle,enabled,showingSavedDevices,onSettings
actions={<>{onAdd&&<IconButton label="Добавить устройство к БК" onClick={onAdd}><Icon name="plus"/></IconButton>}<IconButton label="Настройки бортового компьютера" onClick={onSettings}><Icon name="settings"/></IconButton><IconButton label="Мониторинг системы БК" onClick={onMonitor}><Icon name="activity"/></IconButton><IconButton label={open?'Свернуть устройства БК':'Показать устройства БК'} aria-expanded={open} onClick={onToggle}><Icon name={open?'chevron-down':'chevron-right'}/></IconButton></>}/>;
}
export function BoardComputerSettings({vehicle,enabled,onClose,onRevoke}:{vehicle:Vehicle;enabled:boolean;onClose:()=>void;onRevoke:()=>void}){
return <Window open title="Бортовой компьютер" subtitle={vehicle.host?.hostname||'Mission Core Node'} onClose={onClose}>
const [section,setSection]=useState('binding');
const network=useBoardNetwork(vehicle.id);
return <FeatureSettingsWindow open title="Бортовой компьютер" subtitle={vehicle.host?.hostname||'Mission Core Node'}
identity={{title:vehicle.host?.hostname||'Mission Core Node',subtitle:vehicle.node_id,avatarLabel:'БК'}}
sections={[{id:'binding',label:'Привязка',icon:'apps'},{id:'network',label:'Связь с Core',icon:'network'}]} activeSection={section} onSectionChange={setSection} onClose={onClose}
footer={<WindowFooterActions><Button variant="secondary" onClick={onClose}>Закрыть</Button>{section==='network'&&<Button variant="primary" disabled={!network.canSave} onClick={()=>void network.save()}>{network.applying?'Применяем…':'Сохранить'}</Button>}</WindowFooterActions>}>
{section==='network'?<BoardNetworkSettings network={network}/>:
<div className="fleet-form"><StatusBadge tone={enabled?'success':vehicle.enrollment==='pending'?'warning':'neutral'}>{boardStatus(vehicle,enabled)}</StatusBadge>
{vehicle.notice&&<p role="status">{vehicle.notice}</p>}
<dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{vehicle.node_id}</dd></div><div><dt>Последняя связь</dt><dd>{vehicle.last_seen?new Date(vehicle.last_seen*1000).toLocaleString('ru-RU'):'Соединение ещё не получено'}</dd></div>
{vehicle.host&&<><div><dt>Имя БК в системе</dt><dd>{vehicle.host.hostname}</dd></div><div><dt>Операционная система</dt><dd>{vehicle.host.os}</dd></div><div><dt>Архитектура</dt><dd>{vehicle.host.architecture}</dd></div><div><dt>Процессоры</dt><dd>{vehicle.host.cpus}</dd></div><div><dt>Память</dt><dd>{vehicle.host.memory_kib?`${(vehicle.host.memory_kib/1048576).toFixed(1)} ГиБ`:'Нет сведений'}</dd></div></>}
</dl>
{vehicle.enrollment!=='revoked'&&<Button onClick={onRevoke}>Отозвать привязку БК</Button>}
</div>
</Window>;
</div>}
</FeatureSettingsWindow>;
}
@@ -1,46 +1,42 @@
import {WorkspaceBackButton} from '../../components/WorkspaceBackButton';
import {useState} from 'react';
import {ActivityIndicator,Button,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,TextField,ToastStack} from '@nodedc/ui-react';
import {useBoardMonitor,monitorSeries,monitorValue} from '../../core/fleet/boardMonitor';
import {TelemetrySeries} from '../../components/system/TelemetrySeries';
import '../../styles/system-telemetry.css';
import {LoadingRegion,ResourceList,ResourceRow,Select,SettingsCard,StatusBadge,ToastStack} from '@nodedc/ui-react';
import {WorkspaceBackButton} from '../../components/WorkspaceBackButton';
import {useBoardMonitor,monitorValue,type BoardMonitor} from '../../core/fleet/boardMonitor';
import './board-monitor.css';
const eventLabels:Record<string,string>={'ui-error':'Ошибка интерфейса','ui-rejection':'Ошибка асинхронной операции','ui-render-error':'Ошибка представления','system-oom':'Нехватка памяти','gpu-reset':'Сброс GPU','disk-error':'Ошибка диска','usb-disconnected':'Отключение USB','usb-error':'Ошибка USB','service-failed':'Сбой службы','ui-process-exit':'Завершение процесса окна','ui-load-failed':'Ошибка загрузки окна'};
const time=(value:number)=>new Date(value*1000).toLocaleString('ru-RU');
export function BoardMonitorView({vehicle,name,back,headerToolsHost}:{vehicle:string;name:string;back:()=>void;headerToolsHost?:HTMLElement|null}) {
const [metric,setMetric]=useState('cpu.usage'),[group,setGroup]=useState('CPU'),[window,setWindow]=useState(900),[end,setEnd]=useState<number|null>(null),[mode,setMode]=useState<'min'|'max'|'mean'>('max');
const {value,error,dismissError}=useBoardMonitor(vehicle,metric,window,end);
const definitions=value?.definitions??{},definition=definitions[metric];
export function BoardMonitorReadout({name,value,error,loading}:{name:string;value:BoardMonitor|null;error:string;loading:boolean}) {
const [selectedGroup,setGroup]=useState('CPU');
const definitions=value?.definitions??{},latest=value?.latest;
const groups=[...new Set(Object.values(definitions).map(item=>item.group))];
const group=groups.includes(selectedGroup)?selectedGroup:groups[0]??'';
const metrics=Object.entries(definitions).filter(([,item])=>item.group===group);
const latest=value?.latest;
return <div className="board-monitor">
<WorkspaceBackButton label="К аппарату" onClick={back} host={headerToolsHost}/>
return <>
<SettingsCard title="Мониторинг системы БК" description={name} actions={<StatusBadge tone={value?.fresh&&!error?'success':'neutral'}>{value?.fresh&&!error?'Данные поступают':'Нет свежих данных'}</StatusBadge>}>
{latest&&<p>Измерено на БК: {time(latest.at)}. {value?.storage==='ready'?'Локальная история записывается.':'Запись локальной истории недоступна.'} {value?.backlog?'История догружается в Mission Core.':''}</p>}
{value?.database_bytes!=null&&<p>Архив на БК: {monitorValue(value.database_bytes,'bytes')} из {monitorValue(value.database_budget_bytes,'bytes')}. {value.archive_since?`Копия в Mission Core с ${time(value.archive_since)}.`:''}</p>}
{latest&&<p>Измерено на БК: {time(latest.at)}.</p>}
</SettingsCard>
{!value?<ActivityIndicator label="Получение мониторинга БК"/>:!value.available?<SettingsCard title="История БК пока не получена" description="Данные появятся после подключения бортового сборщика телеметрии."/>:<>
<SettingsCard title="История нагрузки">
<div className="board-monitor-controls">
<Select label="Ресурс" value={group} options={groups.map(label=>({value:label,label}))} onChange={next=>{setGroup(next);const first=Object.entries(definitions).find(([,item])=>item.group===next);if(first)setMetric(first[0]);}}/>
<Select label="Показатель" value={metric} options={metrics.map(([key,item])=>({value:key,label:`${item.resource} · ${item.label}`}))} onChange={setMetric}/>
<Select label="Период" value={String(window)} options={[{value:'900',label:'15 минут'},{value:'3600',label:'1 час'},{value:'21600',label:'6 часов'},{value:'86400',label:'24 часа'},{value:'604800',label:'7 дней'}]} onChange={next=>setWindow(Number(next))}/>
<Select label="Значение в интервале" value={mode} options={[{value:'max',label:'Максимум'},{value:'mean',label:'Среднее'},{value:'min',label:'Минимум'}]} onChange={next=>setMode(next as typeof mode)}/>
</div>
<div className="board-monitor-controls"><Button onClick={()=>setEnd(end===null?Date.now()/1000:null)}>{end===null?'Зафиксировать время':'В реальном времени'}</Button>{end!==null&&<TextField label="Конец периода" type="datetime-local" step="1" value={new Date((end-new Date(end*1000).getTimezoneOffset()*60)*1000).toISOString().slice(0,19)} onChange={event=>{const next=new Date(event.target.value).getTime()/1000;if(Number.isFinite(next))setEnd(next);}}/>}</div>
<TelemetrySeries label={definition?`${definition.resource} · ${definition.label}`:'Загрузка CPU'} resource="Последний интервал периода" value={monitorValue(value.series.at(-1)?.[mode],definition?.unit)} values={monitorSeries(value,mode)} ceiling={definition?.unit==='%'?100:undefined}/>
<p>{time(value.start)} — {time(value.end)} · интервал {value.bucket_seconds} с. Разрывы означают отсутствие измерений.</p>
{!value.series.length&&<p>За выбранный период измерений нет.</p>}
</SettingsCard>
<SettingsCard title={`Последние измерения · ${group}`} description={latest?time(latest.at):'Ожидание измерений'}>
<LoadingRegion loading={loading&&!value} label="Получение мониторинга БК"><div className="board-monitor-readings">
{!value?.available?<SettingsCard align="center" title={loading?'Ожидание показателей':error?'Мониторинг БК недоступен':'Нет текущих измерений'} description={error?'Обновление повторяется автоматически.':'Показатели появятся после получения свежих данных с борта.'}/>:<>
<SettingsCard title="Текущие показатели" description={latest?time(latest.at):undefined}>
{!!groups.length&&<div className="board-monitor-controls"><Select label="Ресурс" value={group} options={groups.map(label=>({value:label,label}))} onChange={setGroup}/></div>}
<ResourceList aria-label="Показатели системы">{metrics.map(([key,item])=><li key={key}><ResourceRow title={`${item.resource} · ${item.label}`} description={latest?.values[key]==null?item.reason??'Счётчик недоступен':undefined} metadata={monitorValue(latest?.values[key],item.unit)}/></li>)}</ResourceList>
{!metrics.length&&<p>Измерения для этого ресурса не поступили.</p>}
</SettingsCard>
<SettingsCard title="События системы и приложения" description="За выбранный период">
<SettingsCard title="События последнего измерения">
{value.events.length?<ResourceList aria-label="События БК">{value.events.map((event,index)=><li key={`${event.at}-${index}`}><ResourceRow title={eventLabels[event.code]??'Событие системы'} description={time(event.at)}/></li>)}</ResourceList>:<p>Событий не получено.</p>}
</SettingsCard>
</>}
</div></LoadingRegion>
</>;
}
export function BoardMonitorView({vehicle,name,back,headerToolsHost}:{vehicle:string;name:string;back:()=>void;headerToolsHost?:HTMLElement|null}) {
const {value,error,loading,dismissError}=useBoardMonitor(vehicle);
return <div className="board-monitor">
<WorkspaceBackButton label="К аппарату" onClick={back} host={headerToolsHost}/>
<BoardMonitorReadout name={name} value={value} error={error} loading={loading}/>
<ToastStack items={error?[{id:'monitor-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={dismissError}/>
</div>;
}

Some files were not shown because too many files have changed in this diff Show More