diff --git a/README.md b/README.md index 636b5a11..d4240f4e 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,12 @@ See [the Dataset Gateway plan](docs/14_LIDAR_DATASET_GATEWAY.md), ## Simulation Polygon +Current AI Polygon purpose, architecture, measured status and experiment plan: +[AI Polygon workflow](docs/AI_POLYGON_WORKFLOW.md), reconciled 2026-10-02. +It uses Isaac and shared AI modules entirely on Worker006, with operator video +on the Mac. The Gazebo/PX4 S0/S1 account below is a historical profile with its +own evidence; it must not be read as the current AI Polygon implementation. + Mission Core now has a parallel Polygon product branch for reproducible autonomy qualification. Mission Core owns scenarios, qualification-run lifecycle, authority, canonical contracts, provenance and reports; Gazebo, PX4 diff --git a/apps/control-station/package-lock.json b/apps/control-station/package-lock.json index 454cfc4f..eac33007 100644 --- a/apps/control-station/package-lock.json +++ b/apps/control-station/package-lock.json @@ -21,7 +21,8 @@ "playcanvas": "2.21.4", "react": "^19.1.0", "react-dom": "^19.1.0", - "three": "0.185.1" + "three": "0.185.1", + "three-mesh-bvh": "0.9.15" }, "devDependencies": { "@types/node": "^24.0.0", @@ -1893,6 +1894,15 @@ "integrity": "sha512-5aojFCXKwnjBRZvUnt3WFfEcvUJgkN5LlijRFN95hMy8WVkG4I0QNcJE+OuWvuJ0bOdStrbfXn0pkd6/QyiAlg==", "license": "MIT" }, + "node_modules/three-mesh-bvh": { + "version": "0.9.15", + "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.15.tgz", + "integrity": "sha512-9xdEDkCzFoT8VPFH9DznwFSdbaIEjMvM106Iqq7TJurrIheUKDcdW4prfJTCxryih4XS/UxWs0H3K4MLMRFyOQ==", + "license": "MIT", + "peerDependencies": { + "three": ">= 0.159.0" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", diff --git a/apps/control-station/package.json b/apps/control-station/package.json index 233a0f67..e4963858 100644 --- a/apps/control-station/package.json +++ b/apps/control-station/package.json @@ -25,7 +25,8 @@ "playcanvas": "2.21.4", "react": "^19.1.0", "react-dom": "^19.1.0", - "three": "0.185.1" + "three": "0.185.1", + "three-mesh-bvh": "0.9.15" }, "devDependencies": { "@types/node": "^24.0.0", diff --git a/apps/control-station/public/rover-scene/dcd006-v020-motion.glb b/apps/control-station/public/rover-scene/dcd006-v020-motion.glb new file mode 100644 index 00000000..08ceb003 --- /dev/null +++ b/apps/control-station/public/rover-scene/dcd006-v020-motion.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a3892f019b29a40b95ca302e3411053d9532da21e571ff190aeda76bf83836e +size 53447724 diff --git a/apps/control-station/public/rover-scene/dcd006-v020-motion.json b/apps/control-station/public/rover-scene/dcd006-v020-motion.json new file mode 100644 index 00000000..2a95ada9 --- /dev/null +++ b/apps/control-station/public/rover-scene/dcd006-v020-motion.json @@ -0,0 +1,174 @@ +{ + "schema_version": "missioncore.rover-motion/v1", + "source_scene": "DCD-006_rover_v020.blend", + "source_sha256": "c49a0470974bbe65b4e65b4b5c06cb887730715a1ddfa231b86426fed6de8f79", + "source_saved": false, + "visual_sha256": "4a3892f019b29a40b95ca302e3411053d9532da21e571ff190aeda76bf83836e", + "forward_axis": "+X", + "up_axis": "Y", + "track_centres_m": { + "L": 0.3425, + "R": -0.3425 + }, + "track_width_m": 0.685, + "shift_m": [ + -0.05350000038743019, + 0.0, + 0.0 + ], + "length_m": 2.222, + "pitch_m": 0.0505, + "phase_m": 0.03069696662739778, + "segments": [ + [ + "arc", + 0, + 0.060539054924808725, + [ + -0.16593354688111153, + 0.32184557191629776, + 0.0655, + 2.3390854961098873 + ] + ], + [ + "line", + 0.060539054924808725, + 0.5760464371429339, + [ + -0.15575880346026824, + 0.3865504758751169, + 0.9878611291422765, + -0.1553395942113481, + 0.15533959421134813, + 0.9878611291422766 + ] + ], + [ + "arc", + 0.6365854920677426, + 0.15172294911931034, + [ + 0.40182697, + 0.22413776, + 0.07382606110411796, + 1.4148251155784564 + ] + ], + [ + "line", + 0.7883084411870529, + 0.1629407568053742, + [ + 0.46102862009488454, + 0.18003048254840684, + -0.5974486081464921, + -0.8019072020027126, + 0.8019072020027126, + -0.5974486081464921 + ] + ], + [ + "arc", + 0.9512491979924271, + 0.06094648310379254, + [ + 0.31115497, + 0.0885, + 0.0655, + -0.6403156687217281 + ] + ], + [ + "line", + 1.0121956810962196, + 0.7185584980197575, + [ + 0.31115497, + 0.022999999999999993, + -1.0, + 0.0, + -0.0, + -1.0 + ] + ], + [ + "arc", + 1.730754179115977, + 0.15545137821999958, + [ + -0.40740352801975754, + 0.0885, + 0.0655, + -1.5707963267948966 + ] + ], + [ + "line", + 1.8862055573359766, + 0.33579444266402353, + [ + -0.45291987081346463, + 0.1356010885085021, + 0.719100587916063, + 0.6949059968504895, + -0.6949059968504895, + 0.719100587916063 + ] + ] + ], + "link_count": 44, + "wheels": [ + { + "node": "R_SPIN_rear_lower", + "radius_m": 0.0625 + }, + { + "node": "R_SPIN_middle_lower", + "radius_m": 0.0625 + }, + { + "node": "R_SPIN_rear_upper", + "radius_m": 0.0625 + }, + { + "node": "R_SPIN_front_lower", + "radius_m": 0.0625 + }, + { + "node": "R_SPIN_DRIVE", + "radius_m": 0.07233592163526643 + }, + { + "node": "L_SPIN_rear_lower", + "radius_m": 0.0625 + }, + { + "node": "L_SPIN_middle_lower", + "radius_m": 0.0625 + }, + { + "node": "L_SPIN_rear_upper", + "radius_m": 0.0625 + }, + { + "node": "L_SPIN_front_lower", + "radius_m": 0.0625 + }, + { + "node": "L_SPIN_DRIVE", + "radius_m": 0.07233592163526643 + } + ], + "dimensions_m": [ + 1.1630001068115234, + 0.9049999713897705, + 0.7378441095352173 + ], + "minimum_m": [ + -0.5814999938011169, + -0.45249998569488525, + -0.003844098187983036 + ], + "method": "44 rigid visual pitches per belt; rolling assemblies retain original CAD pivots; no track contact dynamics" +} diff --git a/apps/control-station/simulation-stream.html b/apps/control-station/simulation-stream.html new file mode 100644 index 00000000..33652857 --- /dev/null +++ b/apps/control-station/simulation-stream.html @@ -0,0 +1,4 @@ + +Worker video + + diff --git a/apps/control-station/src/components/laboratory/LaboratoryMetricEvidenceScene.tsx b/apps/control-station/src/components/laboratory/LaboratoryMetricEvidenceScene.tsx index a4bb6bd1..cd9eb57c 100644 --- a/apps/control-station/src/components/laboratory/LaboratoryMetricEvidenceScene.tsx +++ b/apps/control-station/src/components/laboratory/LaboratoryMetricEvidenceScene.tsx @@ -265,6 +265,8 @@ LaboratoryMetricEvidenceSceneHandle, showCurrentIncrement: boolean; showLocalSurface: boolean; showRollingMap: boolean; + showReferenceGeometry?: boolean; + showRenderStats?: boolean; showLowStep?: boolean; pointSemanticClassIds?: readonly (number | null)[]; semanticClasses?: readonly RecordedEvidenceSemanticClass[]; @@ -287,6 +289,8 @@ LaboratoryMetricEvidenceSceneHandle, showLocalSurface, showRollingMap, showLowStep = true, + showReferenceGeometry = true, + showRenderStats = true, pointSemanticClassIds, semanticClasses, semanticPalette, @@ -746,6 +750,7 @@ LaboratoryMetricEvidenceSceneHandle, if (!host || !content) return; clearGroup(content); + if (!showReferenceGeometry) { requestRenderRef.current(); return; } const corridorLength = rig.lengthM / 2 + corridor.forwardLengthM + corridor.rearMarginM; const corridorCenterX = (rig.lengthM / 2 + corridor.forwardLengthM - corridor.rearMarginM) / 2; const corridorMesh = new THREE.Mesh( @@ -806,6 +811,7 @@ LaboratoryMetricEvidenceSceneHandle, content.add(grid); requestRenderRef.current(); }, [ + showReferenceGeometry, corridor.forwardLengthM, corridor.halfWidthM, corridor.rearMarginM, @@ -912,7 +918,7 @@ LaboratoryMetricEvidenceSceneHandle, {renderError ?

{renderError}

: null}
- {renderStats ? ( + {showRenderStats && renderStats ? ( (null); + useLayoutEffect(()=>{const host=ref.current!;host.append(element);return()=>{if(element.parentElement===host)element.remove();};},[element]); + return
; +} +export function ObservationDeck({ids,mounts,layout,onTreeChange,labels,focusedId,children}:{ + ids:string[];mounts:Map;layout:ObservationLayout;onTreeChange:(tree:DockTree)=>void; + labels:Record;focusedId?:string|null;children:ReactNode; +}){ + return ({id,label:labels[id]??id}))} + renderPanel={id=>}>{children}; +} diff --git a/apps/control-station/src/components/observation/ObservationLayoutSaveWindow.tsx b/apps/control-station/src/components/observation/ObservationLayoutSaveWindow.tsx new file mode 100644 index 00000000..a6a7a20b --- /dev/null +++ b/apps/control-station/src/components/observation/ObservationLayoutSaveWindow.tsx @@ -0,0 +1,16 @@ +import {useState} from 'react'; +import {Button,Icon,TextField,Window,WindowFooterActions} from '@nodedc/ui-react'; + +export function ObservationLayoutSaveWindow({onClose,onSave,initialName='',onRemove}:{onClose:()=>void;onSave:(name:string)=>boolean;initialName?:string;onRemove?:()=>boolean}) { + const [name,setName]=useState(initialName); + const save=()=>{if(name.trim()&&onSave(name))onClose();}; + return + {onRemove&&} + + }> + setName(event.target.value)} + onKeyDown={event=>{if(event.key==='Enter'&&!event.nativeEvent.isComposing){event.preventDefault();save();}}} + description={onRemove?undefined:'Сохраняются выбранные камеры, слои и расположение окон. Недоступные устройства появятся при подключении.'}/> + ; +} diff --git a/apps/control-station/src/components/observation/ObservationPanelHeader.tsx b/apps/control-station/src/components/observation/ObservationPanelHeader.tsx new file mode 100644 index 00000000..356dd74d --- /dev/null +++ b/apps/control-station/src/components/observation/ObservationPanelHeader.tsx @@ -0,0 +1,13 @@ +import {useLayoutEffect,useRef,type ReactNode} from 'react'; + +/** Reserve the actual overlay height for text/status content, including wrapped controls. */ +export function ObservationPanelHeader({children}:{children:ReactNode}) { + const ref=useRef(null); + useLayoutEffect(()=>{ + const header=ref.current!; + const measure=()=>header.parentElement?.style.setProperty('--observation-overlay-header-space',`${header.getBoundingClientRect().height}px`); + measure();const observer=new ResizeObserver(measure);observer.observe(header); + return()=>observer.disconnect(); + },[]); + return
{children}
; +} diff --git a/apps/control-station/src/components/observation/observation.css b/apps/control-station/src/components/observation/observation.css new file mode 100644 index 00000000..98ebb763 --- /dev/null +++ b/apps/control-station/src/components/observation/observation.css @@ -0,0 +1,54 @@ +.observation-center { display:flex; flex-direction:column; gap:var(--nodedc-space-3); padding:var(--nodedc-space-4); min-width:0; height:max(600px, calc(100dvh - 260px)); } +.observation-center--expanded { position:fixed; inset:0; z-index:var(--nodedc-layer-overlay); background:var(--nodedc-canvas); height:100dvh; box-sizing:border-box; } +.observation-toolbar, .observation-summary, .observation-actions { display:flex; align-items:center; gap:var(--nodedc-space-2); } +.observation-toolbar { justify-content:space-between; flex-wrap:wrap; } +.observation-toolbar h2, .observation-panel h3 { margin:0; } +.observation-toolbar span { color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-sm); } +.observation-actions { flex-shrink:0; } +.observation-deck { flex:1; min-height:0; min-width:0; } +.observation-layout { position:relative; height:100%; min-height:0; min-width:0; } +.observation-layout__slot { height:100%; min-height:0; } +.observation-layout__panel { position:absolute; min-height:0; min-width:0; } +.observation-layout__panel:has(.is-dragging) { z-index:var(--nodedc-layer-panel); } +.observation-mount, .observation-panel-mount, .observation-media-mount, .observation-panel, .observation-split { height:100%; min-height:0; min-width:0; } +.observation-panel__surface { display:flex; flex-direction:column; height:100%; overflow:hidden; container-type:inline-size; } +.observation-panel__surface > .observation-mount { flex:1; } +.observation-panel__surface--overlay { position:relative; --observation-overlay-header-space:62px; } +.observation-panel__surface--overlay > .observation-panel__header { position:absolute; inset:0 0 auto; z-index:1; background:transparent; pointer-events:none; } +.observation-panel__surface--overlay > .observation-panel__header > * { pointer-events:auto; } +.observation-panel__header { display:flex; align-items:center; gap:var(--nodedc-space-2); padding:var(--nodedc-space-2); flex-shrink:0; } +.observation-panel__header h3 { min-width:0; font-size:var(--nodedc-font-size-sm); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } +.observation-source { position:relative; display:flex; flex-direction:column; height:100%; min-height:0; } +.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-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; } +.observation-source__media { position:relative; flex:1; min-height:0; overflow:hidden; display:flex; align-items:center; justify-content:center; } +.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-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); } +.observation-layer > * { min-width:0; width:100%; } +.observation-layer > .nodedc-switch { text-align:left; } +.observation-empty { display:grid; place-content:center; height:100%; text-align:center; } +.observation-decoder { position:absolute; width:1px; height:1px; opacity:0; pointer-events:none; } +@media(max-width:700px) { .observation-toolbar .observation-actions { flex-wrap:wrap; } .observation-center { height:max(650px, calc(100dvh - 200px)); } .observation-center--expanded { height:100dvh; } } + +.observation-map[data-available="false"] > [data-nodedc-map-renderer] { visibility:hidden; } + +/* Transform the live panel as one item; reveal it across nested split boundaries. */ +.observation-panel-drag { position:relative; height:100%; min-height:0; } +.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) { + .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__surface--overlay .rover-telemetry { padding-top:calc(var(--observation-overlay-header-space) + var(--nodedc-space-3)); } diff --git a/apps/control-station/src/components/simulation/AiCompositionFields.tsx b/apps/control-station/src/components/simulation/AiCompositionFields.tsx index bd8e9fc1..14fe20d3 100644 --- a/apps/control-station/src/components/simulation/AiCompositionFields.tsx +++ b/apps/control-station/src/components/simulation/AiCompositionFields.tsx @@ -1,4 +1,4 @@ -import { FieldFrame, Select } from "@nodedc/ui-react"; +import { InspectorSelectField } from "@nodedc/ui-react"; import type { AiModules, AiSelection } from "../../core/simulation/aiPolygon"; const labels = { segmentation: "Поверхность", detection: "Объекты", geometry: "Рельеф", @@ -8,10 +8,13 @@ export function AiCompositionFields({ modules, selection, disabled, onChange }: modules: AiModules; selection: AiSelection; disabled: boolean; onChange: (value: AiSelection) => void; }) { return
-

Модули AI

+ {selection.selections.some(s=>s.module_id==="simulation-waypoint-mission")?<> + s.module_id==="simulation-waypoint-mission")?.parameters.environment??"park")} + options={[{value:"natural",label:"Природа · пересечённая местность"},{value:"park",label:"Парк · дорожки"},{value:"urban",label:"Город · тротуары"}]} + onChange={environment=>onChange({...selection,selections:selection.selections.map(s=>s.module_id==="simulation-waypoint-mission"?{...s,parameters:{...s.parameters,environment}}:s)})}/> + :null} {modules.catalog.groups.filter(({ modules: options }) => options.length > 0).map(({ group, modules: options }) => - - + {section === "pivot" ? <> + {range("pivot","pixels","Размер осей",50,220,5,"px")} + {range("pivot","diameter","Диаметр стержня",2,16,1,"px")} + {range("pivot","cone","Размер конусов",10,40,1,"px")} + {range("pivot","opacity","Непрозрачность",.15,1,.05,"")} + {(["x","y","z"] as const).map((axis)=>set("pivot",axis,v)}/>)} + : section === "waypoint" ? <> + {range("waypoint","diameter","Диаметр",.05,3,.05,"м")} + {range("waypoint","height","Высота",.2,50,.1,"м")} + set("waypoint","color",v)}/> + {range("waypoint","opacity","Непрозрачность",.1,1,.05,"")} + {range("waypoint","frequency","Пульсация",0,3,.1,"Гц")} + Свечение + {range("waypoint","emission","Сила эмиссии",0,5,.1,"")} + set("waypoint","emissionColor",v)}/> + : <> + Сдвиг камеры +

Расстояние до поверхности под курсором. Чувствительность плавно меняется между двумя границами.

+ {range("navigation","nearDistance","Ближнее расстояние",.5,50,.5,"м")} + {range("navigation","nearPan","Чувствительность вблизи",.1,5,.1,"×")} + {range("navigation","farDistance","Дальнее расстояние",Math.max(2,value.navigation.nearDistance+1),500,1,"м")} + {range("navigation","farPan","Чувствительность вдали",.1,5,.1,"×")} + Зум + {range("navigation","zoom","Скорость зума",.1,3,.1,"×")} + Центр вращения +

Шарик появляется в точке нажатия на время вращения.

+ {range("navigation","centroidPixels","Размер центра на экране",6,64,1,"px")} + set("navigation","centroidColor",v)}/> + {range("navigation","centroidOpacity","Непрозрачность центра",.1,1,.05,"")} + } + {error?setError(null)}/>:null} +
+ ; +} diff --git a/apps/control-station/src/components/simulation/PlayCanvasRuntime.ts b/apps/control-station/src/components/simulation/PlayCanvasRuntime.ts index 52f1bb3b..d9e68e46 100644 --- a/apps/control-station/src/components/simulation/PlayCanvasRuntime.ts +++ b/apps/control-station/src/components/simulation/PlayCanvasRuntime.ts @@ -1,3 +1,4 @@ +import { QUALITY_PROFILES } from "../../core/simulation/gaussianQuality"; import { Application, Asset, @@ -18,6 +19,7 @@ import { type ModelComponent, type ScriptType, } from "playcanvas"; +import type { AiRobot } from "../../core/simulation/aiPolygon"; import { CameraControls } from "playcanvas/scripts/esm/camera-controls.mjs"; import { @@ -76,24 +78,10 @@ const HOME_POSITION = new Vec3(0, 1, 0); const HOME_FOCUS = new Vec3(1, 1, 0); const DRACO_DECODER_ROOT = "/vendor/playcanvas/draco/1.5.7"; -const QUALITY_PROFILES: Record = { - low: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 3, lodRangeMax: 5, pixelRatio: 0.75, splatBudget: 350_000, targetFps: 30 }, - medium: { lodBaseDistance: 5, lodMultiplier: 2, lodRangeMin: 2, lodRangeMax: 5, pixelRatio: 1, splatBudget: 700_000, targetFps: 45 }, - high: { lodBaseDistance: 5, lodMultiplier: 3, lodRangeMin: 1, lodRangeMax: 5, pixelRatio: 1.25, splatBudget: 1_200_000, targetFps: 60 }, - ultra: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 1.5, splatBudget: 2_500_000, targetFps: 60 }, - maximum: { lodBaseDistance: 7, lodMultiplier: 3, lodRangeMin: 0, lodRangeMax: 5, pixelRatio: 2, splatBudget: 4_000_000, targetFps: 60 }, -}; export class PlayCanvasRuntime implements SimulationRuntime { private app: Application | null = null; + private robotAsset: Asset | null = null; private canvas: HTMLCanvasElement | null = null; private camera: Entity | null = null; private cameraController: CameraController | null = null; @@ -155,7 +143,7 @@ export class PlayCanvasRuntime implements SimulationRuntime { antialias: true, alpha: false, preserveDrawingBuffer: false, - powerPreference: "high-performance", + powerPreference: "default", }, }); this.app = app; @@ -306,6 +294,27 @@ export class PlayCanvasRuntime implements SimulationRuntime { } } + async setRobot(robot: AiRobot, ground: number[], headingDegrees: number, maxSpeedMps = .5): Promise { + const app = this.requiredApp(); + const publicRoot = "apps/control-station/public/"; + if (!robot.visual.source.startsWith(publicRoot)) throw new Error("Модель ровера недоступна."); + const asset = new Asset(robot.name,"container",{ url: "/"+robot.visual.source.slice(publicRoot.length) }); + this.robotAsset = asset; app.assets.add(asset); + await new Promise((resolve,reject) => { + asset.ready(()=>resolve()); asset.once("error",()=>reject(new Error("Модель ровера не загрузилась."))); + app.assets.load(asset); + }); + if (this.disposed) { asset.unload(); return; } + const resource = asset.resource as ContainerResource; + this.setUgvPreset({ presetName: robot.name, massKg: robot.physics.mass_kg, + dimensionsMeters: { length:robot.physics.length_m, width:robot.physics.width_m, + height:robot.physics.height_m, groundClearance: .15 }, + maxSpeedMetersPerSecond: maxSpeedMps, maxTurnRateDegrees: 45, invertSteering: false }); + this.ugvController!.setRobot(()=>resource.instantiateRenderEntity(),new Vec3(...ground),headingDegrees,robot.visual.motion); + } + + get speed(): number { return this.ugvController?.speed ?? 0; } + setQuality(quality: SimulationQuality): void { this.quality = quality; this.applyQuality(); @@ -380,6 +389,7 @@ export class PlayCanvasRuntime implements SimulationRuntime { this.unloadWorld(); this.ugvController?.dispose(); this.ugvController = null; + this.robotAsset?.unload(); this.robotAsset = null; if (this.app) { this.app.autoRender = false; this.app.renderNextFrame = false; diff --git a/apps/control-station/src/components/simulation/RoverSettingsWindow.tsx b/apps/control-station/src/components/simulation/RoverSettingsWindow.tsx new file mode 100644 index 00000000..67e23a2e --- /dev/null +++ b/apps/control-station/src/components/simulation/RoverSettingsWindow.tsx @@ -0,0 +1,33 @@ +import { useState } from "react"; +import { Button, TextField, Window, WindowFooterActions } from "@nodedc/ui-react"; +import type { AiRobot } from "../../core/simulation/aiPolygon"; +import { defaultRoverSettings, validRoverSettings, type RoverSettings } from "../../core/simulation/roverSettings"; + +export function RoverSettingsWindow({robot,value,manual,onApply,onClose}:{ + robot:AiRobot; value:RoverSettings; manual:boolean; + onApply:(value:RoverSettings)=>void; onClose:()=>void; +}) { + const [draft,setDraft] = useState(value); + const field = (key:Exclude, label:string, min:number, max:number|undefined, step:number) => + setDraft({...draft,[key]:e.target.value===""?NaN:Number(e.target.value)})}/>; + const valid=validRoverSettings(draft,robot); + return + + + }> +
+ {field("max_speed_mps","Скорость до, м/с",.05,undefined,.01)} + {field("base_mass_kg","Масса ровера без груза, кг",10,1000,1)} + {field("payload_mass_kg","Дополнительный груз, кг",0,500,1)} + {field("payload_height_m","Высота центра груза над грунтом, м",.1,3,.01)} +

Общая масса: {Number.isFinite(draft.base_mass_kg+draft.payload_mass_kg)?draft.base_mass_kg+draft.payload_mass_kg:"—"} кг.

+

Груз расположен по центру ровера. Масса и высота влияют на центр тяжести и инерцию; мощность моторов остаётся прежней.

+ {manual?

В ручном режиме учитываются скорость и общая масса. Высота груза применяется в заезде на Worker.

:null} +

Изменения применяются к следующему заезду. Его результат сохраняет использованные настройки.

+ {!valid?

Допустимо: конечная скорость от 0.05 м/с, масса 10–1000 кг, груз 0–500 кг, высота 0.1–3 м.

:null} +
+
; +} diff --git a/apps/control-station/src/components/simulation/RoverTrackMotion.ts b/apps/control-station/src/components/simulation/RoverTrackMotion.ts new file mode 100644 index 00000000..d31b4667 --- /dev/null +++ b/apps/control-station/src/components/simulation/RoverTrackMotion.ts @@ -0,0 +1,36 @@ +import { Entity } from "playcanvas"; +import { beltPose, type RoverMotion } from "../../core/simulation/roverMotion"; + +export class RoverTrackMotion { + private distance = { L:0, R:0 }; + private links: { node:Entity; side:"L"|"R"; index:number }[] = []; + private wheels: { node:Entity; side:"L"|"R"; radius:number; angle:number }[] = []; + constructor(root: Entity, private motion: RoverMotion) { + const requireNode = (name: string) => { + const node = root.findByName(name) as Entity | null; + if (!node) throw new Error(`В модели отсутствует узел анимации ${name}`); + return node; + }; + for (const side of ["L","R"] as const) { + for (let index=0;index ({node:requireNode(w.node),side:w.node[0] as "L"|"R",radius:w.radius_m,angle:0})); + } + update(dt: number, forwardSpeed: number, yawRate: number) { + // Local controller uses +Z forward, +Y up: positive yaw turns right. + const speed={L:forwardSpeed+yawRate*this.motion.track_width_m/2,R:forwardSpeed-yawRate*this.motion.track_width_m/2}; + const step=Math.min(.1,Math.max(0,dt)); + for (const side of ["L","R"] as const) this.distance[side]=(this.distance[side]+speed[side]*step)%this.motion.length_m; + for (const w of this.wheels) { + w.angle=(w.angle-speed[w.side]*step/w.radius)%(2*Math.PI); + w.node.setLocalEulerAngles(0,0,w.angle*180/Math.PI); + } + for (const link of this.links) { + const pose=beltPose(this.motion,this.distance[link.side],link.side,link.index); + link.node.setLocalPosition(pose.position[0],pose.position[1],pose.position[2]); + link.node.setLocalEulerAngles(0,0,pose.angle*180/Math.PI); + } + } +} diff --git a/apps/control-station/src/components/simulation/SimulationObservationDeck.tsx b/apps/control-station/src/components/simulation/SimulationObservationDeck.tsx new file mode 100644 index 00000000..609293fc --- /dev/null +++ b/apps/control-station/src/components/simulation/SimulationObservationDeck.tsx @@ -0,0 +1,56 @@ +import {useEffect,useRef,useState,type ReactNode} from 'react'; +import {createPortal} from 'react-dom'; +import {Button,Checker,DockHandle,Dropdown,GlassSurface,Icon,IconButton,Select,ToastStack} from '@nodedc/ui-react'; +import {withObservationTree,orderedObservationIDs,observationTree} from '../../core/fleet/observationLayout'; +import {useObservationPresets} from '../../core/fleet/useObservationPresets'; +import {observationArrangements,retainDormantObservationTree} from '../../core/fleet/observationPresets'; +import {ObservationLayoutSaveWindow} from '../observation/ObservationLayoutSaveWindow'; +import {ObservationDeck} from '../observation/ObservationDeck'; +import {ObservationPanelHeader} from '../observation/ObservationPanelHeader'; +import {AiInferencePreview,type InferencePreview} from './AiInferencePreview'; +import '../observation/observation.css'; + +const storageKey='missioncore.simulation.observation.v1'; +export function SimulationObservationDeck({video,videoActions,toolbar,preview}:{video:ReactNode;videoActions:ReactNode;toolbar:ReactNode;preview:null|InferencePreview}){ + const presets=useObservationPresets('missioncore.simulation.observation-presets.v1',storageKey); + const {layout,setLayout}=presets; + const [saving,setSaving]=useState(false); + const [editing,setEditing]=useState(null); + const edited=presets.presets.find(p=>p.id===editing); + const [full,setFull]=useState(null); + const mounts=useRef(new Map()); + const sources=[{id:'video',label:'Симуляция'},...(preview?.layers??[])]; + for(const source of sources)if(!mounts.current.has(source.id)){const element=document.createElement('div');element.className='observation-panel-mount';mounts.current.set(source.id,element);} + const ids=orderedObservationIDs(layout,sources.map(source=>source.id)); + const visible=ids.filter(id=>!layout.hidden.includes(id)&&(id==='video'||layout.catalogVisible?.includes(id))); + const effectiveFull=full&&visible.includes(full)?full:null; + 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
+
+ {effectiveFull&&} + }> + {({close})=>
+ {try {update({...prefs,quality});}catch{setError("Не удалось сохранить качество.");}}}/> + setHelp(true)}> + {planning?setSettings(true)}>:null} + +
+ {settings?setSettings(false)}/>:null} + setHelp(false)} title="Управление сценой"> +
{planning?<> +

ЛКМ — вращение вокруг точки нажатия. ПКМ или клик двумя пальцами с движением — сдвиг.

+

Прокрутка — зум к курсору, в том числе в режиме добавления точек.

+

WASD / стрелки — перемещение. Q / E — вниз / вверх. Shift — быстрее.

+

Waypoint по клику — установка точки на поверхности. Выберите точку и перемещайте её за стрелки X, Y, Z. Delete — удалить, Ctrl/Cmd+Z — отменить. Клик по пустому месту в обзоре снимает выделение.

+ :<>

WASD / стрелки — движение. Пробел — тормоз. R — к старту.

Мышь — обзор.

}
+
+ {error?setError(null)}/>:null} + ; +} diff --git a/apps/control-station/src/components/simulation/WorkerVideo.tsx b/apps/control-station/src/components/simulation/WorkerVideo.tsx new file mode 100644 index 00000000..f3d59722 --- /dev/null +++ b/apps/control-station/src/components/simulation/WorkerVideo.tsx @@ -0,0 +1,29 @@ +import { useEffect, useRef, useState } from "react"; +import type { AiStreamEndpoint } from "../../core/simulation/aiPolygon"; +import { streamRecovery } from "../../core/simulation/streamRecovery"; +export type WorkerVideoState="connecting"|"live"|"failed"; +export function WorkerVideo({endpoint,onState}:{endpoint:AiStreamEndpoint;onState:(state:WorkerVideoState,fps:number|null)=>void}){ + const frame=useRef(null),callback=useRef(onState);callback.current=onState; + const [attempt,setAttempt]=useState(0); + useEffect(()=>{ + const started=performance.now();let lastFrame:number|null=null,failedAt:number|null=null,finished=false; + callback.current("connecting",null); + const receive=(e:MessageEvent)=>{ + if(finished||e.origin!==location.origin||e.source!==frame.current?.contentWindow||e.data?.type!=="missioncore-worker-video")return; + if(e.data.state==="live"&&Number.isFinite(e.data.fps)){ + lastFrame=performance.now();failedAt=null;callback.current("live",e.data.fps); + }else if(e.data.state==="failed")failedAt??=performance.now(); + }; + const timer=setInterval(()=>{ + const action=streamRecovery(performance.now(),started,lastFrame,failedAt,attempt); + if(finished||action==="wait")return; + finished=true; + if(action==="retry")setAttempt(n=>n+1);else callback.current("failed",null); + },500); + window.addEventListener("message",receive); + return ()=>{finished=true;clearInterval(timer);window.removeEventListener("message",receive);}; + },[attempt]); + return