feat(playcanvas): share dockable scene tools and persistent model editing

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:59 +03:00
parent 038337783f
commit 2f0a066dde
40 changed files with 3238 additions and 126 deletions
+1
View File
@@ -12,3 +12,4 @@
apps/control-station/vendor/rerun-web-viewer-0.34.1/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text apps/control-station/vendor/rerun-web-viewer-0.34.1/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text
apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text apps/control-station/vendor/rerun-web-viewer-0.36.3/re_viewer_bg.nodedc.wasm filter=lfs diff=lfs merge=lfs -text
apps/control-station/public/rover-scene/*.glb filter=lfs diff=lfs merge=lfs -text apps/control-station/public/rover-scene/*.glb filter=lfs diff=lfs merge=lfs -text
apps/control-station/public/battery-scene/*.glb filter=lfs diff=lfs merge=lfs -text
Binary file not shown.
File diff suppressed because it is too large Load Diff
+1
View File
@@ -786,6 +786,7 @@ export default function App() {
content={activeDefinition ? ( content={activeDefinition ? (
<ApplicationPanel <ApplicationPanel
key={activeDefinition.id} key={activeDefinition.id}
allowFullscreen={activeDefinition.kind === "vehicles"}
eyebrow={activeDefinition.eyebrow} eyebrow={activeDefinition.eyebrow}
title={ title={
activeDefinition.kind === "vehicles" activeDefinition.kind === "vehicles"
@@ -1,6 +1,7 @@
import {roverModelID} from '../../core/roverScene/model';
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react'; import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
import {createPortal} from 'react-dom'; import {createPortal} from 'react-dom';
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react'; import {Button,EditorWorkspace,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 {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput';
import {roverDevEvent} from '../../core/fleet/roverDevEvents'; import {roverDevEvent} from '../../core/fleet/roverDevEvents';
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput'; import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
@@ -11,7 +12,7 @@ import './rover.css';
const Scene=lazy(()=>import('./editor/RoverScene')); 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,observation}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){ export function RoverView({vehicleID,name,controller:c,header,active,observation}:{vehicleID:string;name:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
const storage=`missioncore.rover-view.v1:${vehicleID}`; 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 [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set()); const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
@@ -29,7 +30,7 @@ export function RoverView({vehicleID,controller:c,header,active,observation}:{ve
},[open,active]); },[open,active]);
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();},[c.stop,c.setInputGuard]); 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(persistableRoverSettings(settings))try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
useEffect(()=>{if(!active)stop();},[active,stop]); useEffect(()=>{if(!active){stop();setEditing(false);}},[active,stop]);
useEffect(()=>{ useEffect(()=>{
if(!c.ready||!active||open||editing||!stage.current)return; if(!c.ready||!active||open||editing||!stage.current)return;
const scope=stage.current.closest<HTMLElement>('.observation-center')??stage.current; const scope=stage.current.closest<HTMLElement>('.observation-center')??stage.current;
@@ -45,8 +46,9 @@ export function RoverView({vehicleID,controller:c,header,active,observation}:{ve
const speedValid=duty?settings.throttlePercent>=1&&settings.throttlePercent<=100:settings.maxErpm>=300&&settings.maxErpm<=3000; const speedValid=duty?settings.throttlePercent>=1&&settings.throttlePercent<=100:settings.maxErpm>=300&&settings.maxErpm<=3000;
const observing=observation??roverObservationStatus(c.state,c.connection); const observing=observation??roverObservationStatus(c.state,c.connection);
const availability=observing.label??(c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null); 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 inputBlocked=c.ready&&!active;
const status=c.recovering?'Восстанавливаем связь':preparing?'Подготовка управления':availability??c.error??(labels[c.state.snapshot.state??'']??'Наблюдение'); const tone=inputBlocked||preparing||availability?'warning':c.ready?'success':c.error||c.state.snapshot.state==='fault'?'warning':'neutral';
const status=inputBlocked?'Управление приостановлено':c.recovering?'Восстанавливаем связь':preparing?'Подготовка управления':availability??c.error??(labels[c.state.snapshot.state??'']??'Наблюдение');
const running=c.armed||c.pending||c.recovering; const running=c.armed||c.pending||c.recovering;
return <> return <>
{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(<><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)}
@@ -54,7 +56,8 @@ export function RoverView({vehicleID,controller:c,header,active,observation}:{ve
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером" <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();}}} 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();}}> 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'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}> <EditorWorkspace editing={editing&&active} title={`Ровер / ${name}`} subtitle="Редактирование сцены" onBack={()=>setEditing(false)}>
{settings.model===roverModelID?<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> <Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>} {modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>} </LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
@@ -69,10 +72,11 @@ export function RoverView({vehicleID,controller:c,header,active,observation}:{ve
</div> </div>
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span> <span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
</div>} </div>}
</EditorWorkspace>
</div> </div>
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings"> <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="Тип управления" 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}))}/> <Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
{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)}))}/>: {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="Скорость, 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)}))}/> <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)}))}/>
@@ -0,0 +1,14 @@
import {ColorField,ControlRow,Description,RangeControl,Switch} from '@nodedc/ui-react';
import type {ChargeGradient} from '../../../core/roverScene/chargeGradient';
export function ChargeGradientInspector({value,onChange}:{value:ChargeGradient;onChange:(value:ChargeGradient)=>void}){
const patch=(change:Partial<ChargeGradient>)=>onChange({...value,...change});
return <div className="rover-scene-fields">
<Switch label="Градиент по заряду" checked={value.enabled} onChange={enabled=>patch({enabled})}/>
<Description>Две пары цветов: при 0% и при 100%. Между ними — плавный переход по общему заряду батареи.</Description>
{(['lowA','lowB','highA','highB'] as const).map((key,i)=><ControlRow key={key} label={['0% · цвет A','0% · цвет B','100% · цвет A','100% · цвет B'][i]}><ColorField label={['0% · цвет A','0% · цвет B','100% · цвет A','100% · цвет B'][i]} value={value[key]} onChange={color=>patch({[key]:color})}/></ControlRow>)}
<RangeControl label="Сила свечения градиента" value={value.intensity} min={0} max={10} step={.05} exactValueBounds={{min:0,max:10}} onChange={intensity=>patch({intensity})}/>
<RangeControl label="Скорость переливания" value={value.speed} min={0} max={3} step={.01} exactValueBounds={{min:0,max:3}} onChange={speed=>patch({speed})}/>
<RangeControl label="Масштаб рисунка" value={value.scale} min={1} max={50} step={.1} exactValueBounds={{min:1,max:50}} onChange={scale=>patch({scale})}/>
<Description>Ореол свечения настраивается в окружении → Bloom. При временном обрыве связи сохраняются последние цвет и яркость; движение возобновится с новыми показаниями.</Description>
</div>;
}
@@ -1,3 +1,4 @@
import {ChargeGradientInspector} from './ChargeGradientInspector';
import {useRef,useState} from 'react'; import {useRef,useState} from 'react';
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-react'; import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-react';
import {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument'; import {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
@@ -5,8 +6,9 @@ import {textureFromFile} from '../../../core/roverScene/sceneStorage';
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'}; const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
export function MaterialInspector({material,onChange,onReset,onError}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void}){ export function MaterialInspector({material,onChange,onReset,onError}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void}){
const range=(key:keyof MaterialSpec,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>; const range=(key:keyof MaterialSpec,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>;
return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={['surface']} sections={[ return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={material.chargeGradient?['charge']:['surface']} sections={[
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields"><ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>}, ...(material.chargeGradient?[{id:'charge',label:'Градиент заряда',content:<ChargeGradientInspector value={material.chargeGradient} onChange={chargeGradient=>onChange({chargeGradient})}/>}]:[]),
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields">{!material.chargeGradient?.enabled&&<ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>}{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>}, {id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>}, {id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
]}/><Button onClick={onReset}>Исходный материал</Button></>; ]}/><Button onClick={onReset}>Исходный материал</Button></>;
@@ -0,0 +1,23 @@
import {useLayoutEffect,useRef,type CSSProperties} from 'react';
import {Button,DraggableItem,Icon,IconButton} from '@nodedc/ui-react';
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {materialTileSizes,type EditorWindowRect} from '../../../core/roverScene/editorLayout';
export function MaterialTile({material}:{material:MaterialSpec}){return <span className="rover-material-tile"><span aria-hidden="true" className="rover-material-swatch" style={{'--material-color':material.color,'--material-gloss':1-material.roughness,...(material.chargeGradient?.enabled?{background:`linear-gradient(135deg,${material.chargeGradient.highA},${material.chargeGradient.highB})`}:{})} as CSSProperties}/><span>{material.name}</span></span>;}
type Props={materials:Record<string,MaterialSpec>;selected:string|null;revealVersion:number;pick:(id:string)=>void;add:()=>void;rect?:EditorWindowRect;tileSize:number};
export function MaterialPalette({materials,selected,pick,add,revealVersion,rect,tileSize}:Props){
const grid=useRef<HTMLDivElement>(null);
useLayoutEffect(()=>{
const content=grid.current,parent=content?.closest('.nodedc-window__body'),target=content?.querySelector<HTMLElement>('[aria-pressed="true"]');
if(!parent||!target)return;
const p=parent.getBoundingClientRect(),t=target.getBoundingClientRect();
if(t.top<p.top)parent.scrollTop+=t.top-p.top;else if(t.bottom>p.bottom)parent.scrollTop+=t.bottom-p.bottom;
},[selected,revealVersion,tileSize,rect?.width,rect?.height]);
return <div ref={grid} className="rover-material-palette__items" style={{'--material-tile-width':`${tileSize}px`,'--material-swatch-size':`${38*tileSize/materialTileSizes.default}px`,'--material-tile-font':`${Math.max(10,12*tileSize/materialTileSizes.default)}px`} as CSSProperties}>
{Object.entries(materials).map(([id,m])=><DraggableItem id={id} data={{materialId:id}} key={id} className="scene-material-drag">{({activator})=><Button {...activator.attributes} {...activator.listeners} variant={selected===id?'primary':'secondary'} tone="neutral" aria-pressed={selected===id} title={m.name} onClick={()=>pick(id)}><MaterialTile material={m}/></Button>}</DraggableItem>)}
<Button aria-label="Добавить материал" title="Добавить материал" onClick={add}><span className="rover-material-tile"><Icon name="plus"/><span>Новый материал</span></span></Button>
</div>;
}
export function MaterialPaletteActions({tileSize,onTileSize}:{tileSize:number;onTileSize:(size:number)=>void}){return <>
<IconButton label="Уменьшить плитки материалов" disabled={tileSize<=materialTileSizes.min} onClick={()=>onTileSize(Math.max(materialTileSizes.min,tileSize-materialTileSizes.step))}><Icon name="minus"/></IconButton>
<IconButton label="Увеличить плитки материалов" disabled={tileSize>=materialTileSizes.max} onClick={()=>onTileSize(Math.min(materialTileSizes.max,tileSize+materialTileSizes.step))}><Icon name="plus"/></IconButton>
</>;}
@@ -1,38 +1,73 @@
import {useCallback,useEffect,useState,type CSSProperties} from 'react'; import {editorDockLayout,materialTileSizes} from '../../../core/roverScene/editorLayout';
import {Button,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,Window} from '@nodedc/ui-react'; import {roverModelURL} from '../../../core/roverScene/model';
import {assignMaterial,createMaterial,changeField,defaultScene,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument'; import {useCallback,useEffect,useRef,useState} from 'react';
import {Description,DragDropRoot,DropZone,EditorDockLayout,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,type EditorDockTool} from '@nodedc/ui-react';
import {createMaterial,changeField,defaultScene,maxSceneMaterials,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {assignObjectMaterial,findSceneObject,objectTargets,type SceneObject} from '../../../core/roverScene/sceneObjects';
import {useSceneDocument} from '../../../core/roverScene/useSceneDocument'; import {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
import PlayCanvasViewer from '../playcanvas/PlayCanvasViewer'; import PlayCanvasViewer,{type PlayCanvasViewerProps} from '../playcanvas/PlayCanvasViewer';
import type {ScenePicker,ScenePick} from '../playcanvas/useSceneMaterials';
import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector'; import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector';
import {MaterialInspector} from './MaterialInspector'; import {MaterialInspector} from './MaterialInspector';
import {MaterialPalette,MaterialPaletteActions,MaterialTile} from './MaterialPalette';
import {SceneObjectTree} from './SceneObjectTree';
import {useSceneUndo} from './useSceneUndo';
import type {ChargeState} from '../playcanvas/chargeMaterial';
import {useObjectSelection} from './useObjectSelection';
import './sceneEditor.css'; import './sceneEditor.css';
export default function RoverScene({vehicleID,editing,onModelState}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){ export default function RoverScene({vehicleID,...props}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){
const scene=useSceneDocument(vehicleID),[palette,setPalette]=useState(false),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready'); const scene=useSceneDocument(vehicleID);return <SceneEditor {...props} scene={scene}/>;
const [selectedGroup,setSelectedGroup]=useState<string|null>(null); }
const pick=useCallback((id:string,group?:string)=>{setSelected(id);if(group)setSelectedGroup(group);setMaterialOpen(true);},[]); export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,defaults=defaultScene,onSceneReady,minFitDistance,chargeState}:{scene:ReturnType<typeof useSceneDocument>;editing:boolean;onModelState:NonNullable<PlayCanvasViewerProps['onModelState']>;modelUrl?:string;defaults?:typeof defaultScene;onSceneReady?:PlayCanvasViewerProps['onSceneReady'];minFitDistance?:number;chargeState?:ChargeState}){
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=128){scene.setError('В сцене может быть не больше 128 материалов.');return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);}; useSceneUndo(scene,editing);
const patchMaterial=(id:string,patch:Partial<MaterialSpec>)=>{const next={...scene.document,materials:{...scene.document.materials,[id]:{...scene.document.materials[id],...patch}}};if(textureBytes(next)>28_000_000){scene.setError('Суммарный объём текстур превышает 20 МБ. Удалите ненужную текстуру.');return;}scene.update(doc=>({...doc,materials:{...doc.materials,[id]:{...doc.materials[id],...patch}}}));}; const layout=scene.document.editorLayout;
const docking=editorDockLayout(layout),tileSize=layout?.materialTileSize??materialTileSizes.default;
const [palette,setPalette]=useState(true),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready');
const [objectsOpen,setObjectsOpen]=useState(true),[root,setRoot]=useState<SceneObject|null>(null),[selectedObject,setSelectedObject]=useState<string|null>(null);
const [selectionVersion,setSelectionVersion]=useState(0);
const [modelPhase,setModelPhase]=useState<'loading'|'ready'|'error'>('loading');
const [sceneApi,setSceneApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null);
const picker=useRef<ScenePicker|null>(null);
const pickerReady=useCallback((value:ScenePicker|null)=>{picker.current=value;},[]);
const sceneGraph=useCallback((value:SceneObject|null)=>{setRoot(value);},[]);
const sceneReady=useCallback((api:Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0])=>{setSceneApi(api);onSceneReady?.(api);},[onSceneReady]);
const modelState=useCallback((value:'loading'|'ready'|'error')=>{setModelPhase(value);onModelState(value);},[onModelState]);
const pick=useCallback((id:string)=>{setSelected(id);setMaterialOpen(true);setObjectsOpen(true);},[]);
const objectPick=useCallback((hit:ScenePick|null)=>{setSelectionVersion(v=>v+1);if(!hit){setSelectedObject(null);setSelected(null);setMaterialOpen(false);return;}setSelectedObject(hit.objectId);setPalette(true);pick(hit.materialId);},[pick]);
const selectObject=(id:string)=>{setSelectionVersion(v=>v+1);setSelectedObject(id);const item=findSceneObject(root,id),source=item?.materialIds?.[0];const material=scene.document.objectAssignments?.[id]??(source?(scene.document.assignments[source]??source):null);if(material){setPalette(true);pick(material);}};
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=maxSceneMaterials){scene.setError(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);};
const patchMaterial=(id:string,patch:Partial<MaterialSpec>)=>{if(Object.entries(patch).every(([key,value])=>scene.document.materials[id]?.[key as keyof MaterialSpec]===value))return;const next={...scene.document,materials:{...scene.document.materials,[id]:{...scene.document.materials[id],...patch}}};if(textureBytes(next)>28_000_000){scene.setError('Суммарный объём текстур превышает 20 МБ. Удалите ненужную текстуру.');return;}scene.update(doc=>({...doc,materials:{...doc.materials,[id]:{...doc.materials[id],...patch}}}));};
useEffect(()=>{if(textureState==='error')scene.setError('Не удалось применить текстуру к сцене. Проверьте файл и загрузите его заново.');},[textureState,scene.setError]); useEffect(()=>{if(textureState==='error')scene.setError('Не удалось применить текстуру к сцене. Проверьте файл и загрузите его заново.');},[textureState,scene.setError]);
const node=findSceneObject(root,selectedObject),targets=node?objectTargets(node):[];
useObjectSelection(sceneApi,targets,editing&&modelPhase==='ready');
const material=selected?scene.document.materials[selected]:null;
const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере'; const saved=scene.saveState==='saved',status=textureState==='loading'?'Загрузка текстур':scene.saveState==='loading'?'Загрузка настроек сцены':scene.saveState==='saving'?'Сохранение сцены':scene.saveState==='error'?'Изменения не сохранены':'Сохранено на этом компьютере';
const material=selected?scene.document.materials[selected]:null; const tools:EditorDockTool[]=[
return <> {id:'objects',title:'Объекты сцены',label:'Объекты сцены',open:objectsOpen,onClose:()=>setObjectsOpen(false),className:'scene-object-window',initialRect:{left:16,top:16,width:380,height:600},content:<SceneObjectTree revealVersion={selectionVersion} root={root} selected={selectedObject} visibility={scene.document.objectVisibility} legacyVisibility={scene.document.objects} onSelect={selectObject} onVisibility={(id,value)=>scene.update(doc=>({...doc,objectVisibility:{...doc.objectVisibility,[id]:value}}))}/>},
<LoadingRegion className="rover-view__scene" style={{bottom:editing&&palette?150:0}} loading={!scene.ready} label="Загрузка настроек сцены"> {id:'palette',title:'Материалы сцены',label:'Материалы сцены',open:palette,onClose:()=>setPalette(false),className:'rover-material-palette',initialRect:{left:400,top:420,width:640,height:340},minimumSize:{width:280,height:180},
{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}/>} actions:<MaterialPaletteActions tileSize={tileSize} onTileSize={size=>scene.update(doc=>({...doc,editorLayout:{windows:{},...doc.editorLayout,materialTileSize:size}}))}/>,content:<MaterialPalette tileSize={tileSize} revealVersion={selectionVersion} materials={scene.document.materials} selected={selected} pick={pick} add={addMaterial}/>},
</LoadingRegion> {id:'environment',title:'Окружение сцены',label:'Окружение сцены',open:environment,onClose:()=>setEnvironment(false),footer:<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaults().postFx}))}/>,content:<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>},
{id:'material',title:material?.name||'Материал',label:'Материал',activationKey:`${selectionVersion}:${selected}`,subtitle:node?`Назначить: ${node.name}`:'Выберите объект в дереве',open:materialOpen&&!!material,onClose:()=>setMaterialOpen(false),
actions:<IconButton label="Назначить материал выбранному объекту" disabled={!selected||!targets.length} onClick={()=>selected&&scene.update(doc=>assignObjectMaterial(doc,targets,selected))}><Icon name="chevron-right"/></IconButton>,
content:material&&selected?<><Description>{node?`Выбран объект: ${node.name}${targets.length>1?` · деталей: ${targets.length}`:''}`:'Выберите деталь в дереве объектов. Назначение доступно стрелкой рядом с крестиком.'}</Description><MaterialInspector key={selected} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaults().materials[selected]??createMaterial(defaults(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/></>:null}
];
return <DragDropRoot renderOverlay={({data})=>{const m=scene.document.materials[String(data?.materialId)];return m?<GlassSurface padding="sm"><MaterialTile material={m}/></GlassSurface>:null;}} onDragEnd={({activeData,pointer})=>{
const id=String(activeData?.materialId??'');if(!editing||!pointer||!Object.hasOwn(scene.document.materials,id))return;
// Reject palettes/inspectors and empty sky. Only an actual visible model hit assigns.
if(!(document.elementFromPoint(pointer.x,pointer.y) instanceof HTMLCanvasElement))return;
const hit=picker.current?.pick(pointer.x,pointer.y);if(!hit)return;
setSelectedObject(hit.objectId);setSelected(id);scene.update(doc=>assignObjectMaterial(doc,[hit.objectId],id));
}}>
<EditorDockLayout value={docking} enabled={editing} tools={tools} onChange={next=>scene.update(doc=>({...doc,editorLayout:{windows:{},materialTileSize:materialTileSizes.default,...doc.editorLayout,docking:next}}))} primary={<>
<DropZone id="scene-model" className="rover-scene-drop"><LoadingRegion className="rover-view__scene" loading={!scene.ready} label="Загрузка настроек сцены">
{scene.ready&&<PlayCanvasViewer modelUrl={modelUrl} onSceneReady={sceneReady} onSceneGraph={sceneGraph} minFitDistance={minFitDistance} postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} cameraState={scene.document.camera} onCameraChange={scene.recordCamera} materials={scene.document.materials} assignments={scene.document.assignments} objectAssignments={scene.document.objectAssignments} objectVisibility={scene.document.objectVisibility} legacyObjectVisibility={scene.document.objects} editing={editing} chargeState={chargeState} onObjectPick={objectPick} onPickerReady={pickerReady} onModelState={modelState} onTextureState={setTextureState}/>}
</LoadingRegion></DropZone>
{editing&&<> {editing&&<>
<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-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Отменить изменение · Ctrl/Cmd+Z" disabled={!scene.canUndo} onClick={scene.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить изменение · Ctrl/Cmd+Shift+Z" disabled={!scene.canRedo} onClick={scene.redo}><Icon name="redo"/></IconButton><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>{setPalette(v=>!v);setObjectsOpen(true);}}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton><IconButton label="Объекты сцены" aria-pressed={objectsOpen} onClick={()=>setObjectsOpen(v=>!v)}><Icon name="list"/></IconButton></GlassSurface></div>
<div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></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>}
</>} </>}
<Window open={editing&&environment} title="Окружение сцены" placement="end" draggable onClose={()=>setEnvironment(false)} footer={<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaultScene().postFx}))}/>}> </>}/>
<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>
</Window>
<Window open={editing&&materialOpen&&!!material} title={material?.name||'Материал'} subtitle="Материал сцены" placement="end" draggable style={{position:'fixed',left:'var(--nodedc-space-4)',top:'6rem',right:'auto'}} onClose={()=>setMaterialOpen(false)}>
{material&&selected&&<>
{selectedGroup?<div className="rover-scene-fields"><p className="rover-scene-note">Выбранная группа: {defaultScene().materials[selectedGroup]?.name}</p><Button disabled={(scene.document.assignments[selectedGroup]??selectedGroup)===selected} onClick={()=>scene.update(doc=>assignMaterial(doc,selectedGroup,selected))}>Назначить выбранной группе</Button></div>:<p className="rover-scene-note">Нажмите на деталь в сцене, затем выберите материал в палитре, чтобы назначить его группе.</p>}
<MaterialInspector key={selected} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaultScene().materials[selected]??createMaterial(defaultScene(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/>
</>}
</Window>
<ToastStack items={scene.error?[{id:'rover-scene-error',tone:'error',title:'Настройки сцены',description:scene.error}]:[]} onDismiss={()=>scene.setError('')}/> <ToastStack items={scene.error?[{id:'rover-scene-error',tone:'error',title:'Настройки сцены',description:scene.error}]:[]} onDismiss={()=>scene.setError('')}/>
</>; </DragDropRoot>;
} }
@@ -0,0 +1,11 @@
import {useEffect,useMemo,useState} from 'react';
import {Tree,TextField,type TreeNode} from '@nodedc/ui-react';
import {findSceneObject,type SceneObject} from '../../../core/roverScene/sceneObjects';
const label=(name:string)=>({'ModelRoot':'Сцена','Model':'Модель','bms/labels/cells':'Надписи ячеек','bms/labels/enclosure':'Надписи корпуса','bms/labels/electronics':'Маркировка электроники'}[name]??name.replace(/^bms\/cell-display\/C(\d+)$/,'Маркировка ячейки $1').replace(/^bms\//,''));
export function SceneObjectTree({root,selected,visibility,legacyVisibility,onSelect,onVisibility,revealVersion}:{root:SceneObject|null;selected:string|null;revealVersion:number;visibility?:Record<string,boolean>;legacyVisibility?:Record<string,boolean>;onSelect:(id:string)=>void;onVisibility:(id:string,value:boolean)=>void}){
const [query,setQuery]=useState('');
useEffect(()=>{const node=findSceneObject(root,selected);if(node&&query&&!label(node.name).toLocaleLowerCase().includes(query.toLocaleLowerCase()))setQuery('');},[selected,revealVersion]);
const convert=(node:SceneObject):TreeNode=>({id:node.id,label:label(node.name),visible:visibility?.[node.id]??legacyVisibility?.[node.name]??node.enabled,children:node.children.map(convert)});
const nodes=useMemo(()=>root?[convert(root)]:[],[root,visibility,legacyVisibility]);
return <div className="scene-object-outliner"><TextField label="Найти объект" value={query} onChange={e=>setQuery(e.target.value)}/><Tree label="Дерево объектов сцены" nodes={nodes} revealKey={revealVersion} selected={selected} onSelect={onSelect} onVisibilityChange={onVisibility} query={query}/></div>;
}
@@ -2,16 +2,28 @@
.rover-scene-tools__surface,.rover-scene-actions {display:flex;align-items:center;gap:var(--nodedc-space-2);flex-wrap:wrap;} .rover-scene-tools__surface,.rover-scene-actions {display:flex;align-items:center;gap:var(--nodedc-space-2);flex-wrap:wrap;}
.rover-scene-tools__surface {padding:var(--nodedc-space-1);} .rover-scene-tools__surface {padding:var(--nodedc-space-1);}
.rover-scene-save {position:absolute;left:var(--nodedc-space-3);top:calc(var(--observation-overlay-header-space, 0px) + 3rem);pointer-events:none;} .rover-scene-save {position:absolute;left:var(--nodedc-space-3);top:calc(var(--observation-overlay-header-space, 0px) + 3rem);pointer-events:none;}
.rover-material-palette {position:absolute;bottom:var(--nodedc-space-3);left:var(--nodedc-space-3);right:var(--nodedc-space-3);padding:var(--nodedc-space-2);} .rover-material-palette .nodedc-window__body {overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;}
.rover-material-palette__header {display:flex;align-items:center;justify-content:space-between;gap:var(--nodedc-space-2);font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);} .rover-material-palette__items {display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,var(--material-tile-width)),1fr));gap:var(--nodedc-space-2);align-content:start;}
.rover-material-palette__items {display:flex;gap:var(--nodedc-space-2);overflow:auto;} .rover-material-palette__items .nodedc-button {width:100%;height:100%;min-width:0;padding:var(--nodedc-space-2);}
.rover-material-palette__items > * {flex:0 0 auto;} .rover-material-tile {display:grid;justify-items:center;align-content:center;gap:var(--nodedc-space-1);width:100%;min-width:0;white-space:normal;overflow-wrap:anywhere;font-size:var(--material-tile-font,var(--nodedc-font-size-xs));}
.rover-material-tile {display:grid;justify-items:center;gap:var(--nodedc-space-1);width:100px;white-space:normal;font-size:var(--nodedc-font-size-xs);} .rover-material-tile>span:last-child {display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;min-height:2.4em;line-height:1.2;}
/* Domain material thumbnail: a swatch, not a replacement control. */ /* Domain material thumbnail: a swatch, not a replacement control. */
.rover-material-swatch {display:block;width:38px;height:38px;border-radius:50%;background:radial-gradient(ellipse at 35% 25%,#ffffffb0,transparent 45%),radial-gradient(ellipse at 60% 75%,transparent,var(--material-color) 70%),var(--material-color);box-shadow:inset -5px -5px 12px #0008;} .rover-material-swatch {display:block;width:var(--material-swatch-size,38px);height:var(--material-swatch-size,38px);border-radius:50%;background:radial-gradient(ellipse at 35% 25%,#ffffffb0,transparent 45%),radial-gradient(ellipse at 60% 75%,transparent,var(--material-color) 70%),var(--material-color);box-shadow:inset -5px -5px 12px #0008;}
.rover-scene-fields {display:flex;flex-direction:column;gap:var(--nodedc-space-3);} .rover-scene-fields {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
.rover-scene-note {font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-secondary);} .rover-scene-note {font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-secondary);}
.rover-scene-texture__row {display:flex;gap:var(--nodedc-space-2);align-items:center;min-width:0;} .rover-scene-texture__row {display:flex;gap:var(--nodedc-space-2);align-items:center;min-width:0;}
.rover-scene-texture__row img {width:36px;height:36px;object-fit:cover;} .rover-scene-texture__row img {width:36px;height:36px;object-fit:cover;}
.rover-scene-texture__row .nodedc-button {min-width:0;overflow:hidden;} .rover-scene-texture__row .nodedc-button {min-width:0;overflow:hidden;}
@container(max-width:460px){.rover-scene-save{top:calc(var(--observation-overlay-header-space, 0px) + 4.5rem)}.rover-material-tile{width:82px}.rover-material-palette__header>span{max-width:210px}} @container(max-width:460px){.rover-scene-save{top:calc(var(--observation-overlay-header-space, 0px) + 4.5rem)}}
.rover-scene-drop{position:absolute;inset:0}
.rover-scene-drop>.rover-view__scene{position:absolute;inset:0}
.scene-object-children{margin-left:var(--nodedc-space-3)}
.scene-material-drag{display:flex;align-items:center;gap:var(--nodedc-space-1)}
.scene-object-outliner{height:100%;min-height:0;display:flex;flex-direction:column;gap:var(--nodedc-space-3)}
.scene-object-outliner .nodedc-tree{flex:1;min-height:0}
.scene-object-window .nodedc-window__body{overflow:hidden}
.scene-material-drag>.nodedc-button{touch-action:none;cursor:grab}
.scene-material-drag.is-dragging>.nodedc-button{cursor:grabbing}
.bms-editor-content{position:absolute;inset:0;height:100%;}
@@ -0,0 +1,15 @@
import {useEffect} from 'react';
import * as pc from 'playcanvas';
import {sceneObjectId} from '../playcanvas/sceneTree';
/** Renderer evidence, including an occluded part selected through the tree. */
export function useObjectSelection(api:{app:pc.Application;modelRoot:pc.Entity}|null,ids:readonly string[],enabled:boolean){
const key=ids.join('\n');
useEffect(()=>{
if(!api||!enabled||!key)return;
const selected=new Set(key.split('\n'));
const meshes=(api.modelRoot.findComponents('render') as pc.RenderComponent[]).flatMap(component=>component.meshInstances).filter(mesh=>selected.has(sceneObjectId(mesh.node)));
const color=new pc.Color(1,1,1,.8);
const draw=()=>{for(const mesh of meshes)api.app.drawWireAlignedBox(mesh.aabb.getMin(),mesh.aabb.getMax(),color,false);};
api.app.on('update',draw);return()=>{api.app.off('update',draw);};
},[api,key,enabled]);
}
@@ -0,0 +1,18 @@
import {useEffect} from 'react';
import {historyCommand} from '../../../core/roverScene/sceneHistory';
import type {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
export function useSceneUndo(scene:ReturnType<typeof useSceneDocument>,active:boolean){
const {undo,redo,beginGesture,endGesture}=scene;
useEffect(()=>{
if(!active)return;
const keydown=(event:KeyboardEvent)=>{
const command=historyCommand(event);
if(command){event.preventDefault();event.stopImmediatePropagation();if(command==='undo')undo();else redo();return;}
if(!event.repeat&&event.key.startsWith('Arrow')&&(event.target as HTMLElement)?.closest?.('[role=slider],input[type=range]'))beginGesture();
};
const keyup=(event:KeyboardEvent)=>{if(event.key.startsWith('Arrow'))endGesture();};
window.addEventListener('keydown',keydown,true);window.addEventListener('keyup',keyup,true);
window.addEventListener('pointerdown',beginGesture,true);window.addEventListener('pointerup',endGesture);window.addEventListener('pointercancel',endGesture);window.addEventListener('blur',endGesture);
return()=>{endGesture();window.removeEventListener('keydown',keydown,true);window.removeEventListener('keyup',keyup,true);window.removeEventListener('pointerdown',beginGesture,true);window.removeEventListener('pointerup',endGesture);window.removeEventListener('pointercancel',endGesture);window.removeEventListener('blur',endGesture);};
},[active,undo,redo,beginGesture,endGesture]);
}
@@ -16,8 +16,10 @@
"Original NodeDC environment preset restored by owner request; editor reset changes environment only", "Original NodeDC environment preset restored by owner request; editor reset changes environment only",
"Semantic material groups, UV texture editing, GPU surface picking and bounded texture disposal", "Semantic material groups, UV texture editing, GPU surface picking and bounded texture disposal",
"Live grid step/diameter and ambient fill added; wireframe application and LUT loading corrected", "Live grid step/diameter and ambient fill added; wireframe application and LUT loading corrected",
"Responsive scene framing and palette space without drive authority" "Responsive scene framing and palette space without drive authority",
"Approved v022 CAM R09 / K1 C22 assembly; original chassis material groups retained, authored equipment colors and 16 mounting frames exported",
"Owner finish: CAM MOLLE and K1 base/holder/cap match matte black frame; Insta360 X4 body uses dark polymer; previous v022 stored palettes migrate once"
], ],
"inspector_source_sha256": "8f1df16bd8c12fb1b8481480690ff4ed0e6b2645cb3fba527888c0f9acb59192", "inspector_source_sha256": "8f1df16bd8c12fb1b8481480690ff4ed0e6b2645cb3fba527888c0f9acb59192",
"model_revision": "dcd006-v020-materials-v2" "model_revision": "dcd006-v022-materials-v2"
} }
@@ -1,3 +1,5 @@
import {viewportFov,type CameraState} from '../../../core/roverScene/cameraState'
export type {CameraState} from '../../../core/roverScene/cameraState'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import * as pc from 'playcanvas' import * as pc from 'playcanvas'
import { buildSceneTree } from './sceneTree' import { buildSceneTree } from './sceneTree'
@@ -14,6 +16,7 @@ const PIXELFORMAT_RGBA32F = (pc as any).PIXELFORMAT_RGBA32F ?? 14
export type PlayCanvasViewerProps = SceneMaterialsProps & { export type PlayCanvasViewerProps = SceneMaterialsProps & {
modelUrl: string | null modelUrl: string | null
minFitDistance?: number
postFx?: Partial<PostFxSettings> | null postFx?: Partial<PostFxSettings> | null
viewportSize?: { width: number; height: number } viewportSize?: { width: number; height: number }
onSceneReady?: (api: { app: pc.Application; camera: pc.Entity; modelRoot: pc.Entity }) => void onSceneReady?: (api: { app: pc.Application; camera: pc.Entity; modelRoot: pc.Entity }) => void
@@ -31,13 +34,6 @@ export type PlayCanvasViewerProps = SceneMaterialsProps & {
muteLogs?: boolean muteLogs?: boolean
} }
export type CameraState = {
pivot: { x: number; y: number; z: number }
distance: number
azimuthDeg: number
elevationDeg: number
}
// ------------------------------------------------------------ // ------------------------------------------------------------
// Fallback texture handler // Fallback texture handler
class SimpleTextureHandler { class SimpleTextureHandler {
@@ -583,6 +579,7 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
cameraEntity.setPosition(x, y, z) cameraEntity.setPosition(x, y, z)
cameraEntity.lookAt(pivot) cameraEntity.lookAt(pivot)
if (autoRotate && dt > 0) emitChange(false)
} }
const onMouseDown = (e: MouseEvent) => { const onMouseDown = (e: MouseEvent) => {
@@ -615,6 +612,7 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
} }
const onMouseUp = () => { const onMouseUp = () => {
if (!dragging && !panning) return
dragging = false dragging = false
panning = false panning = false
idleTime = 0 idleTime = 0
@@ -622,9 +620,14 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
} }
const onWheel = (e: WheelEvent) => { const onWheel = (e: WheelEvent) => {
// Own wheel/pinch only on the canvas: never zoom the page and camera together.
e.preventDefault();e.stopPropagation();
idleTime = 0 idleTime = 0
const dir = Math.sign(e.deltaY) const dir = Math.sign(e.deltaY)
if (dir) targetDistance *= 1 + dir * zoomStrength if (dir) {
const delta=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?canvas.clientHeight:1);
targetDistance *= Math.exp(Math.max(-.35,Math.min(.35,delta*(e.ctrlKey ? .012 : zoomStrength/40))));
}
updateCamera(0) updateCamera(0)
emitChange(false) emitChange(false)
if (wheelCommitTimer) window.clearTimeout(wheelCommitTimer) if (wheelCommitTimer) window.clearTimeout(wheelCommitTimer)
@@ -639,7 +642,7 @@ function makeOrbitController(app: pc.Application, cameraEntity: pc.Entity, opts:
canvas.addEventListener('mousedown', onMouseDown) canvas.addEventListener('mousedown', onMouseDown)
window.addEventListener('mousemove', onMouseMove) window.addEventListener('mousemove', onMouseMove)
window.addEventListener('mouseup', onMouseUp) window.addEventListener('mouseup', onMouseUp)
canvas.addEventListener('wheel', onWheel, { passive: true }) canvas.addEventListener('wheel', onWheel, { passive: false })
canvas.addEventListener('contextmenu', onContextMenu) canvas.addEventListener('contextmenu', onContextMenu)
app.on('update', updateCamera as any) app.on('update', updateCamera as any)
@@ -877,8 +880,9 @@ function applyPostFx(
} }
export default function PlayCanvasViewer({ export default function PlayCanvasViewer({
minFitDistance = 1.8,
modelUrl, modelUrl,
materials, assignments, editing, onMaterialPick, onTextureState, materials, assignments, objectAssignments, objectVisibility, legacyObjectVisibility, editing, onObjectPick, onPickerReady, onTextureState, chargeState,
postFx, postFx,
viewportSize, viewportSize,
onSceneReady, onSceneReady,
@@ -916,7 +920,8 @@ export default function PlayCanvasViewer({
const gridMaterialRef = useRef<pc.ShaderMaterial | null>(null) const gridMaterialRef = useRef<pc.ShaderMaterial | null>(null)
const sceneMapRef = useRef<Map<string, pc.Entity>>(new Map()) const sceneMapRef = useRef<Map<string, pc.Entity>>(new Map())
const loadTokenRef = useRef(0) const loadTokenRef = useRef(0)
const cameraStateRef = useRef<CameraState | null>(null) const referenceHeightRef = useRef(cameraState?.referenceHeight ?? 0)
const cameraStateRef = useRef<CameraState | null>(cameraState ?? null)
const onCameraChangeRef = useRef<PlayCanvasViewerProps['onCameraChange']>(null) const onCameraChangeRef = useRef<PlayCanvasViewerProps['onCameraChange']>(null)
const logWarn = useCallback((...args: any[]) => { if (!muteLogs) console.warn(...args) }, [muteLogs]) const logWarn = useCallback((...args: any[]) => { if (!muteLogs) console.warn(...args) }, [muteLogs])
const logError = useCallback((...args: any[]) => { if (!muteLogs) console.error(...args) }, [muteLogs]) const logError = useCallback((...args: any[]) => { if (!muteLogs) console.error(...args) }, [muteLogs])
@@ -925,7 +930,7 @@ export default function PlayCanvasViewer({
const [skyboxVersion, setSkyboxVersion] = useState(0) const [skyboxVersion, setSkyboxVersion] = useState(0)
const [modelVersion, setModelVersion] = useState(0) const [modelVersion, setModelVersion] = useState(0)
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,editing,onMaterialPick,onTextureState}) useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState})
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx]) const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState]) const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState])
@@ -957,14 +962,10 @@ export default function PlayCanvasViewer({
// PlayCanvas writes fixed pixel CSS sizes; the hosted pane remains fluid. // PlayCanvas writes fixed pixel CSS sizes; the hosted pane remains fluid.
canvas.style.width = '100%' canvas.style.width = '100%'
canvas.style.height = '100%' canvas.style.height = '100%'
const model = inst.root.findByName('Model') as pc.Entity | null // Hold focal length in CSS pixels. Resize changes the crop, never orbit state.
const bounds = model ? computeAabb(model) : null if (!referenceHeightRef.current) referenceHeightRef.current = h
const orbit = (inst as any).__orbit as OrbitController | undefined const camera = cameraEntityRef.current?.camera
if (bounds && orbit) { if (camera) camera.fov = viewportFov(h, referenceHeightRef.current)
const vertical = (cameraEntityRef.current?.camera?.fov ?? 28) * Math.PI / 360
const horizontal = Math.atan(Math.tan(vertical) * w / h)
orbit.setDistance(Math.max(1.8, bounds.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
}
}, []) }, [])
useEffect(() => { useEffect(() => {
@@ -1082,7 +1083,7 @@ export default function PlayCanvasViewer({
inertiaFactor: cameraInertiaFactor ?? undefined, inertiaFactor: cameraInertiaFactor ?? undefined,
inertiaTime: cameraInertiaTime ?? undefined, inertiaTime: cameraInertiaTime ?? undefined,
onChange: (state, commit) => { onChange: (state, commit) => {
onCameraChangeRef.current?.(state, commit) onCameraChangeRef.current?.({...state,referenceHeight:referenceHeightRef.current || canvas.clientHeight}, commit)
}, },
}) })
@@ -1481,6 +1482,7 @@ export default function PlayCanvasViewer({
if (!modelRoot) return if (!modelRoot) return
let cancelled = false let cancelled = false
const request = new AbortController()
const loadGlb = async (url: string) => { const loadGlb = async (url: string) => {
const loadToken = ++loadTokenRef.current const loadToken = ++loadTokenRef.current
@@ -1493,7 +1495,11 @@ export default function PlayCanvasViewer({
ensureTextureHandler(app) ensureTextureHandler(app)
asset = new pc.Asset('model', 'container', { url }) const response = await fetch(url, { signal: AbortSignal.any([request.signal, AbortSignal.timeout(30000)]) })
if (!response.ok) throw new Error(`Model request failed: ${response.status}`)
const contents = await response.arrayBuffer()
if (cancelled) return
asset = new pc.Asset('model', 'container', { url, contents })
app.assets.add(asset) app.assets.add(asset)
const loadedAsset = asset const loadedAsset = asset
@@ -1535,7 +1541,8 @@ export default function PlayCanvasViewer({
const cam = cameraEntityRef.current?.camera const cam = cameraEntityRef.current?.camera
const vertical = (cam?.fov ?? 28) * Math.PI / 360 const vertical = (cam?.fov ?? 28) * Math.PI / 360
const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1)) const horizontal = Math.atan(Math.tan(vertical) * (cam?.aspectRatio ?? 1))
orbit.setDistance(Math.max(1.8, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88)) orbit.setDistance(Math.max(minFitDistance, aabb.halfExtents.length() / Math.sin(Math.min(vertical, horizontal)) * 0.88))
onCameraChangeRef.current?.({...orbit.getState(),referenceHeight:referenceHeightRef.current},true)
} }
if (exposeSceneGraph || onSceneGraph) { if (exposeSceneGraph || onSceneGraph) {
@@ -1564,6 +1571,7 @@ export default function PlayCanvasViewer({
return () => { return () => {
cancelled = true cancelled = true
request.abort()
} }
}, [resolvedUrl, exposeSceneGraph, onSceneGraph]) }, [resolvedUrl, exposeSceneGraph, onSceneGraph])
@@ -1573,7 +1581,9 @@ export default function PlayCanvasViewer({
if (!app) return if (!app) return
const orbit = (app as any).__orbit as OrbitController | undefined const orbit = (app as any).__orbit as OrbitController | undefined
if (!orbit) return if (!orbit) return
if (cameraState.referenceHeight) referenceHeightRef.current = cameraState.referenceHeight
orbit.setState(cameraState) orbit.setState(cameraState)
resizeCanvas()
}, [appReady, cameraState]) }, [appReady, cameraState])
useEffect(() => { useEffect(() => {
@@ -1622,12 +1632,15 @@ export default function PlayCanvasViewer({
const modelEntity = (modelRoot as any).findByName?.('Model') as pc.Entity | null const modelEntity = (modelRoot as any).findByName?.('Model') as pc.Entity | null
const aabb = computeAabb(modelEntity || modelRoot) const aabb = computeAabb(modelEntity || modelRoot)
if (!aabb) return if (!aabb) return
referenceHeightRef.current = canvasRef.current?.clientHeight || referenceHeightRef.current
resizeCanvas()
orbit.setState({ orbit.setState({
pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z }, pivot: { x: aabb.center.x, y: aabb.center.y, z: aabb.center.z },
distance: Math.max(1.8,aabb.halfExtents.length() / Math.sin(Math.min(14*Math.PI/180,Math.atan(Math.tan(14*Math.PI/180)*(cameraEntityRef.current?.camera?.aspectRatio??1))))*.88), distance: Math.max(minFitDistance,aabb.halfExtents.length() / Math.sin(Math.min(14*Math.PI/180,Math.atan(Math.tan(14*Math.PI/180)*(cameraEntityRef.current?.camera?.aspectRatio??1))))*.88),
azimuthDeg: 45, azimuthDeg: 45,
elevationDeg: 10, elevationDeg: 10,
}) })
onCameraChangeRef.current?.({...orbit.getState(),referenceHeight:referenceHeightRef.current},true)
}, [appReady, cameraResetToken, modelVersion]) }, [appReady, cameraResetToken, modelVersion])
useEffect(() => { useEffect(() => {
@@ -0,0 +1,34 @@
import * as pc from 'playcanvas';
import {chargePair,type ChargeGradient} from '../../../core/roverScene/chargeGradient';
export type ChargeState={soc:number|null;fresh:boolean};
const emission=`
uniform vec3 chargeColorA;
uniform vec3 chargeColorB;
uniform float chargeTime;
uniform float chargeScale;
uniform float chargeIntensity;
uniform float chargeSaturation;
void getEmission() {
vec3 p=vPositionW*chargeScale;
float wave=sin(p.x*0.77+sin(p.y*0.91+chargeTime)*1.2+chargeTime*0.43);
wave+=sin(p.z*0.71-p.y*0.48+sin(p.x*0.57-chargeTime*0.61));
float blend=smoothstep(-1.6,1.6,wave);
vec3 color=mix(chargeColorA,chargeColorB,blend);
color=mix(vec3(dot(color,vec3(0.2126,0.7152,0.0722))),color,chargeSaturation);
dEmission=color*chargeIntensity;
}`;
export function configureChargeMaterial(material:pc.StandardMaterial,gradient?:ChargeGradient){
const chunks=material.getShaderChunks(pc.SHADERLANGUAGE_GLSL);
if(gradient?.enabled){chunks.set('emissivePS',emission);material.emissive.set(1,1,1);material.emissiveIntensity=1;material.diffuse.set(.02,.02,.02);}
else chunks.delete('emissivePS');
}
export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number){
const known=state?.soc!==null&&state?.soc!==undefined;
const colors=known?chargePair(gradient,state!.soc):[[.12,.14,.16],[.18,.20,.22]];
material.setParameter('chargeColorA',colors[0].map(value=>value**2.2));
material.setParameter('chargeColorB',colors[1].map(value=>value**2.2));
material.setParameter('chargeTime',time*gradient.speed);
material.setParameter('chargeScale',gradient.scale);
material.setParameter('chargeIntensity',gradient.intensity*(known?1:.2));
material.setParameter('chargeSaturation',known?1:0);
}
@@ -1,20 +1,28 @@
import type * as pc from 'playcanvas' import type * as pc from 'playcanvas'
import type {SceneObject} from '../../../core/roverScene/sceneObjects'
export type SceneTreeNode = { export type SceneTreeNode = SceneObject
id: string
name: string /** Names and duplicate sibling ordinals survive reload; runtime GUIDs do not. */
enabled: boolean export function sceneObjectId(node:pc.GraphNode):string{
children: SceneTreeNode[] const path:string[]=[];let current:pc.GraphNode|null=node;
while(current&&current.name!=='ModelRoot'){
const siblings=current.parent?.children.filter(child=>child.name===current!.name)??[];
path.unshift(encodeURIComponent(current.name||'Entity')+(siblings.length>1?`~${siblings.indexOf(current)}`:''));current=current.parent;
}
return 'object/'+(path.join('/')||'root');
} }
export function buildSceneTree(root: pc.GraphNode, map: Map<string, pc.Entity>): SceneTreeNode { export function buildSceneTree(root: pc.GraphNode, map: Map<string, pc.Entity>): SceneTreeNode {
const id = String((root as any).getGuid?.() ?? (root as any)._guid ?? root.name) const id = sceneObjectId(root)
const children = (root.children || []).map((c) => buildSceneTree(c, map)) const children = (root.children || []).map((c) => buildSceneTree(c, map))
map.set(id, root as pc.Entity) map.set(id, root as pc.Entity)
return { return {
id, id,
name: root.name || 'Entity', name: root.name || 'Entity',
enabled: root.enabled !== false, enabled: root.enabled !== false,
renderable: !!(root as pc.Entity).render?.meshInstances.length,
materialIds: [...new Set((root as pc.Entity).render?.meshInstances.map(mi=>mi.material?.name).filter((name):name is string=>!!name)??[])],
children, children,
} }
} }
@@ -1,12 +1,18 @@
import {useEffect,useRef,type RefObject} from 'react'; import {useEffect,useRef,type RefObject} from 'react';
import * as pc from 'playcanvas'; import * as pc from 'playcanvas';
import {configureChargeMaterial,updateChargeMaterial,type ChargeState} from './chargeMaterial';
import {sceneObjectId} from './sceneTree';
export type ScenePick={objectId:string;materialId:string};
export type ScenePicker={pick:(x:number,y:number)=>ScenePick|null};
import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument'; import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument';
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;editing?:boolean;onMaterialPick?:(id:string,group:string)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void}; export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;legacyObjectVisibility?:Record<string,boolean>;editing?:boolean;onObjectPick?:(hit:ScenePick|null)=>void;chargeState?:ChargeState;onPickerReady?:(picker:ScenePicker|null)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'}; const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,editing,onMaterialPick,onTextureState}:SceneMaterialsProps){ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState}:SceneMaterialsProps){
const latest=useRef({materials,onMaterialPick,onTextureState});latest.current={materials,onMaterialPick,onTextureState}; const latest=useRef({materials,onObjectPick,onTextureState,chargeState});latest.current={materials,onObjectPick,onTextureState,chargeState};
const animated=useRef(new Map<string,pc.StandardMaterial>());
const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>()); const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>());
const generation=useRef(0); const generation=useRef(0);
const originalVisibility=useRef(new WeakMap<pc.GraphNode,boolean>());
const originalGroups=useRef(new WeakMap<pc.MeshInstance,{id:string;material:pc.StandardMaterial}>()); const originalGroups=useRef(new WeakMap<pc.MeshInstance,{id:string;material:pc.StandardMaterial}>());
const customMaterials=useRef(new Map<string,pc.StandardMaterial>()); const customMaterials=useRef(new Map<string,pc.StandardMaterial>());
useEffect(()=>{ useEffect(()=>{
@@ -23,7 +29,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
map.set(id,customMaterials.current.get(id)!); map.set(id,customMaterials.current.get(id)!);
} }
for(const component of (app.root.findByName('ModelRoot') as pc.Entity|null)?.findComponents('render')??[])for(const mi of (component as pc.RenderComponent).meshInstances){ for(const component of (app.root.findByName('ModelRoot') as pc.Entity|null)?.findComponents('render')??[])for(const mi of (component as pc.RenderComponent).meshInstances){
const source=originalGroups.current.get(mi);if(source)mi.material=map.get(assignments?.[source.id]??source.id)??source.material; const source=originalGroups.current.get(mi);if(source)mi.material=map.get(objectAssignments?.[sceneObjectId(mi.node)]??assignments?.[source.id]??source.id)??source.material;
} }
for(const [id,m] of customMaterials.current)if(!Object.hasOwn(materials,id)){m.destroy();customMaterials.current.delete(id);} for(const [id,m] of customMaterials.current)if(!Object.hasOwn(materials,id)){m.destroy();customMaterials.current.delete(id);}
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSpec)=>{ const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSpec)=>{
@@ -32,7 +38,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r'; if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
m.update(); m.update();
}; };
const used=new Set<string>(); const used=new Set<string>();animated.current.clear();
for(const [id,spec] of Object.entries(materials)){ for(const [id,spec] of Object.entries(materials)){
const m=map.get(id);if(!m)continue; const m=map.get(id);if(!m)continue;
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness; m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
@@ -58,26 +64,39 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');}); pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
} }
} }
configureChargeMaterial(m,spec.chargeGradient);
if(spec.chargeGradient?.enabled){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,latest.current.chargeState,0);}
m.update(); m.update();
} }
for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);} for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);}
onTextureState?.(pending?'loading':'ready'); onTextureState?.(pending?'loading':'ready');
return()=>{generation.current++;}; return()=>{generation.current++;};
},[materials,assignments,modelVersion,appRef,onTextureState]); },[materials,assignments,objectAssignments,modelVersion,appRef,onTextureState]);
useEffect(()=>{
const app=appRef.current;if(!app||!modelVersion)return;
let time=0;const motion=window.matchMedia('(prefers-reduced-motion: reduce)');
const update=(dt:number)=>{const live=latest.current;if(live.chargeState?.fresh&&!motion.matches)time+=Math.min(dt,.1);for(const [id,material] of animated.current){const gradient=live.materials?.[id]?.chargeGradient;if(gradient?.enabled)updateChargeMaterial(material,gradient,live.chargeState,time);}};
app.on('update',update);return()=>{app.off('update',update);};
},[appRef,modelVersion]);
useEffect(()=>()=>{generation.current=-1;for(const item of textures.current.values())item.texture?.destroy();textures.current.clear();for(const m of customMaterials.current.values())m.destroy();customMaterials.current.clear();},[]); useEffect(()=>()=>{generation.current=-1;for(const item of textures.current.values())item.texture?.destroy();textures.current.clear();for(const m of customMaterials.current.values())m.destroy();customMaterials.current.clear();},[]);
useEffect(()=>{
const root=appRef.current?.root.findByName('ModelRoot');if(!root||!modelVersion)return;
const visit=(node:pc.GraphNode)=>{if(!originalVisibility.current.has(node))originalVisibility.current.set(node,node.enabled);node.enabled=objectVisibility?.[sceneObjectId(node)]??legacyObjectVisibility?.[node.name]??originalVisibility.current.get(node)!;for(const child of node.children)visit(child);};visit(root);
},[objectVisibility,legacyObjectVisibility,modelVersion,appRef]);
useEffect(()=>{ useEffect(()=>{
const app=appRef.current,canvas=canvasRef.current,camera=cameraRef.current; const app=appRef.current,canvas=canvasRef.current,camera=cameraRef.current;
if(!editing||!app||!canvas||!camera?.camera||!modelVersion)return; if(!editing||!app||!canvas||!camera?.camera||!modelVersion){onPickerReady?.(null);return;}
const picker=new pc.Picker(app,1,1);let start:{x:number;y:number}|null=null; const picker=new pc.Picker(app,1,1);let start:{x:number;y:number}|null=null;
const down=(e:PointerEvent)=>{start=e.button===0?{x:e.clientX,y:e.clientY}:null;}; const pick=(x:number,y:number):ScenePick|null=>{
const up=(e:PointerEvent)=>{ const rect=canvas.getBoundingClientRect();if(x<rect.left||x>=rect.right||y<rect.top||y>=rect.bottom)return null;
const p=start;start=null;if(!p||Math.hypot(p.x-e.clientX,p.y-e.clientY)>4)return; picker.resize(Math.max(1,Math.floor(rect.width)),Math.max(1,Math.floor(rect.height)));picker.prepare(camera.camera!,app.scene);
const rect=canvas.getBoundingClientRect();picker.resize(Math.max(1,Math.floor(rect.width)),Math.max(1,Math.floor(rect.height))); const hit=picker.getSelection(Math.floor(x-rect.left),Math.floor(y-rect.top)).find((mi):mi is pc.MeshInstance=>mi instanceof pc.MeshInstance&&originalGroups.current.has(mi));
picker.prepare(camera.camera!,app.scene); return hit?{objectId:sceneObjectId(hit.node),materialId:hit.material.name}:null;
const hit=picker.getSelection(e.clientX-rect.left,e.clientY-rect.top).find(mi=>!!latest.current.materials?.[mi.material.name]);
if(hit instanceof pc.MeshInstance){const source=originalGroups.current.get(hit);if(source)latest.current.onMaterialPick?.(hit.material.name,source.id);}
}; };
onPickerReady?.({pick});
const down=(e:PointerEvent)=>{start=e.button===0?{x:e.clientX,y:e.clientY}:null;};
const up=(e:PointerEvent)=>{const p=start;start=null;if(!p||Math.hypot(p.x-e.clientX,p.y-e.clientY)>4)return;const hit=pick(e.clientX,e.clientY);latest.current.onObjectPick?.(hit);};
canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointerup',up); canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointerup',up);
return()=>{canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointerup',up);picker.destroy();}; return()=>{canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointerup',up);onPickerReady?.(null);picker.destroy();};
},[editing,modelVersion,appRef,cameraRef,canvasRef]); },[editing,modelVersion,appRef,cameraRef,canvasRef,onPickerReady]);
} }
@@ -1,6 +1,7 @@
.rover-view { position:relative; height:100%; min-height:200px; overflow:hidden; container-type:inline-size; } .rover-view { position:relative; height:100%; min-height:200px; overflow:hidden; container-type:inline-size; }
.rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; } .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 .rover-view__scene { position:absolute; inset:0; }
.nodedc-editor-workspace__body>.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__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__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 { 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-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); }
@@ -1,3 +1,4 @@
import {roverModelID} from '../roverScene/model';
export type RoverMode='arcade'|'tank'; export type RoverMode='arcade'|'tank';
export type Demand={left:number;right:number}; export type Demand={left:number;right:number};
export const keysFor=(mode:RoverMode)=>mode==='arcade'?['KeyW','KeyA','KeyS','KeyD']:['KeyQ','KeyE','KeyA','KeyD']; export const keysFor=(mode:RoverMode)=>mode==='arcade'?['KeyW','KeyA','KeyS','KeyD']:['KeyQ','KeyE','KeyA','KeyD'];
@@ -20,7 +21,7 @@ export function roverSettings(value:unknown):typeof defaultRoverSettings {
// ERPM has no trustworthy conversion to throttle. Migrate at 10%, never // ERPM has no trustworthy conversion to throttle. Migrate at 10%, never
// reinterpret an old saved number as a percentage or full throttle. // 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, 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:'', model:v.model==='dcd006-v020'||v.model===roverModelID?roverModelID:'',
}:{} )}; }:{} )};
} }
@@ -0,0 +1,9 @@
/** Local scene metadata. Height anchors projection so resizing crops without refitting. */
export type CameraState={pivot:{x:number;y:number;z:number};distance:number;azimuthDeg:number;elevationDeg:number;referenceHeight?:number};
export function parseCameraState(value:unknown):CameraState|undefined{
const v=value as CameraState;
if(!v||!v.pivot||![v.pivot.x,v.pivot.y,v.pivot.z,v.distance,v.azimuthDeg,v.elevationDeg].every(n=>typeof n==='number'&&Number.isFinite(n)))return;
if(v.distance<.05||v.distance>500||Math.max(...Object.values(v.pivot).map(Math.abs))>100000||Math.abs(v.azimuthDeg)>1e9||v.elevationDeg<5||v.elevationDeg>90)return;
return {pivot:{x:v.pivot.x,y:v.pivot.y,z:v.pivot.z},distance:v.distance,azimuthDeg:v.azimuthDeg,elevationDeg:v.elevationDeg,...(Number.isFinite(v.referenceHeight)&&v.referenceHeight!>=1&&v.referenceHeight!<=10000?{referenceHeight:v.referenceHeight}:{})};
}
export function viewportFov(height:number,referenceHeight:number){return 2*Math.atan(Math.max(1,height)/Math.max(1,referenceHeight)*Math.tan(14*Math.PI/180))*180/Math.PI;}
@@ -0,0 +1,17 @@
export type ChargeGradient={enabled:boolean;lowA:string;lowB:string;highA:string;highB:string;speed:number;scale:number;intensity:number};
export const defaultChargeGradient=():ChargeGradient=>({enabled:true,lowA:'#ef2815',lowB:'#ff9b23',highA:'#20db62',highB:'#6cffe0',speed:.45,scale:12,intensity:2.5});
export function parseChargeGradient(raw:unknown):ChargeGradient{
const result=defaultChargeGradient(),value=raw as Partial<ChargeGradient>|undefined;
if(!value)return result;
if(typeof value.enabled==='boolean')result.enabled=value.enabled;
for(const key of ['lowA','lowB','highA','highB'] as const)if(typeof value[key]==='string'&&/^#[0-9a-f]{6}$/i.test(value[key]))result[key]=value[key];
for(const [key,min,max] of [['speed',0,3],['scale',1,50],['intensity',0,10]] as const)if(typeof value[key]==='number'&&Number.isFinite(value[key]))result[key]=Math.max(min,Math.min(max,value[key]));
return result;
}
/** Interpolate each end of the gradient; no individual-cell SOC is inferred. */
export function chargePair(spec:ChargeGradient,soc:number|null):[number[],number[]]{
const t=Number.isFinite(soc)?Math.max(0,Math.min(100,soc!))/100:0;
const rgb=(hex:string)=>[1,3,5].map(i=>parseInt(hex.slice(i,i+2),16)/255);
const mix=(a:string,b:string)=>rgb(a).map((v,i)=>v+(rgb(b)[i]-v)*t);
return [mix(spec.lowA,spec.highA),mix(spec.lowB,spec.highB)];
}
@@ -0,0 +1,25 @@
import {decodeEditorDock,type EditorDockState} from '@nodedc/ui-core';
/** Scene-owned layout; ui-core supplies only framework-neutral split contracts. */
export type EditorWindowRect = {left:number;top:number;width:number;height:number};
export const editorWindowIds = ['objects','environment','material','palette'] as const;
export type EditorWindowId = typeof editorWindowIds[number];
export type SceneEditorLayout = {windows:Partial<Record<EditorWindowId,EditorWindowRect>>;materialTileSize:number;docking?:EditorDockState};
export const materialTileSizes = {min:84,max:224,step:20,default:144};
export function parseEditorLayout(raw:unknown):SceneEditorLayout|undefined {
if(!raw||typeof raw!=='object')return undefined;
const value=raw as Partial<SceneEditorLayout>,windows:SceneEditorLayout['windows']={};
for(const id of editorWindowIds){
const rect=value.windows?.[id];
if(!rect||!['left','top','width','height'].every(k=>typeof rect[k as keyof EditorWindowRect]==='number'&&Number.isFinite(rect[k as keyof EditorWindowRect])))continue;
if(rect.width<=0||rect.height<=0)continue;
windows[id]={left:Math.max(-16384,Math.min(16384,rect.left)),top:Math.max(-16384,Math.min(16384,rect.top)),width:Math.min(16384,rect.width),height:Math.min(16384,rect.height)};
}
const size=value.materialTileSize;
const docking=decodeEditorDock(value.docking,'viewport',editorWindowIds);
return {windows,materialTileSize:typeof size==='number'&&Number.isFinite(size)?Math.max(materialTileSizes.min,Math.min(materialTileSizes.max,size)):materialTileSizes.default,...(docking?{docking}:{})};
}
export function editorDockLayout(layout:SceneEditorLayout|undefined):EditorDockState {
if(layout?.docking)return layout.docking;
if(layout&&Object.keys(layout.windows).length)return {tree:{id:'viewport'},floating:{...layout.windows}};
return {tree:{axis:'y',ratio:74,first:{axis:'x',ratio:24,first:{id:'objects'},second:{id:'viewport'}},second:{id:'palette'}},floating:{}};
}
@@ -0,0 +1,219 @@
{
"equipment-0493091ab933": {
"name": "V2 · holder",
"color": "#2c2f31",
"metalness": 0.12,
"roughness": 0.53,
"finish": "body"
},
"equipment-0908c23514b2": {
"name": "R02 | мягкая прокладка",
"color": "#2c3538",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-11906634ee6a": {
"name": "K1 v02 optical panel",
"color": "#50565b",
"metalness": 0.5600000023841858,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-13e890e68f3f": {
"name": "R01 | X4 габаритный макет",
"color": "#24292d",
"metalness": 0,
"roughness": 0.44,
"finish": "polymer"
},
"equipment-1bbe3dad55fc": {
"name": "K1 recessed dark",
"color": "#10181b",
"metalness": 0.10000000149011612,
"roughness": 0.5,
"finish": ""
},
"equipment-1d261a8554d2": {
"name": "Graphite",
"color": "#2c2f31",
"metalness": 0.12,
"roughness": 0.53,
"finish": "body"
},
"equipment-1e00b025ef0c": {
"name": "R02 | крепёж",
"color": "#bfc8ce",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-1f5d576357b7": {
"name": "V2 · gold",
"color": "#d3ad61",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-2161878cdab8": {
"name": "V2 · dark",
"color": "#42484d",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-2383eeb9eaa4": {
"name": "K1 v02 optical pupil",
"color": "#070d14",
"metalness": 0.18000000715255737,
"roughness": 0.0949999988079071,
"finish": ""
},
"equipment-29bcad9db811": {
"name": "K1 v02 black anodized lens barrel",
"color": "#292c2e",
"metalness": 0.6200000047683716,
"roughness": 0.27000001072883606,
"finish": ""
},
"equipment-2ab952389fe9": {
"name": "V2 · base",
"color": "#2c2f31",
"metalness": 0.12,
"roughness": 0.53,
"finish": "body"
},
"equipment-34aa5bfe76d8": {
"name": "R01 | оптика",
"color": "#212c34",
"metalness": 0.44999998807907104,
"roughness": 0.15000000596046448,
"finish": ""
},
"equipment-475e36b7333a": {
"name": "K1 v02 optical coating",
"color": "#182227",
"metalness": 0.4000000059604645,
"roughness": 0.10499999672174454,
"finish": ""
},
"equipment-688e0cbe9c28": {
"name": "K1 v02 satin optical mounts",
"color": "#5b5f5f",
"metalness": 0.6200000047683716,
"roughness": 0.36000001430511475,
"finish": ""
},
"equipment-69e526e4be1d": {
"name": "V2 · cap",
"color": "#2c2f31",
"metalness": 0.12,
"roughness": 0.53,
"finish": "body"
},
"equipment-7b915b2b1e72": {
"name": "C15 · латунная вставка M3 8x4.6",
"color": "#ddaf59",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-7f03a1b05fab": {
"name": "K1 optical glass visual",
"color": "#0a1d24",
"metalness": 0.3499999940395355,
"roughness": 0.12999999523162842,
"finish": ""
},
"equipment-8ad4cd1cb790": {
"name": "K1 graphite alloy",
"color": "#555b61",
"metalness": 0.550000011920929,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-9b5cc39ebcbc": {
"name": "K1 marking",
"color": "#b5b8bc",
"metalness": 0.30000001192092896,
"roughness": 0.5,
"finish": ""
},
"equipment-a7a15ac46f69": {
"name": "K1 machined aluminium",
"color": "#aaafb5",
"metalness": 0.800000011920929,
"roughness": 0.2800000011920929,
"finish": ""
},
"equipment-a7b17ba2a0ea": {
"name": "COMMS stainless",
"color": "#aab5b8",
"metalness": 0.800000011920929,
"roughness": 0.23000000417232513,
"finish": ""
},
"equipment-aa837fc3ef7e": {
"name": "K1 v02 internal optical reflection",
"color": "#353f3d",
"metalness": 0.699999988079071,
"roughness": 0.1599999964237213,
"finish": ""
},
"equipment-ae3f1afea9c8": {
"name": "COMMS gasket",
"color": "#212423",
"metalness": 0.0,
"roughness": 0.800000011920929,
"finish": ""
},
"equipment-c080c558e87a": {
"name": "V2 · power",
"color": "#e1a659",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-c97348106414": {
"name": "COMMS black ASA",
"color": "#232728",
"metalness": 0.0,
"roughness": 0.30000001192092896,
"finish": ""
},
"equipment-dd82990a7ae2": {
"name": "C15 · винт M3",
"color": "#afb8bc",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-e1968fb48dc3": {
"name": "V2 · steel",
"color": "#b3babf",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-e5d7e970a6a9": {
"name": "K1 rubber",
"color": "#1b1e21",
"metalness": 0.0,
"roughness": 0.6600000262260437,
"finish": ""
},
"equipment-e9d38b515cd1": {
"name": "C17 · крепёж основания M4x16",
"color": "#b3b8bd",
"metalness": 0.0,
"roughness": 0.4000000059604645,
"finish": ""
},
"equipment-ffdf234220cd": {
"name": "K1 v02 charging contact gold",
"color": "#d7a252",
"metalness": 0.800000011920929,
"roughness": 0.25,
"finish": ""
}
}
@@ -0,0 +1,5 @@
export const roverModelID='dcd006-v022';
export const roverModelRevision='dcd006-v022-materials-v2';
export const roverModelURL='/rover-scene/dcd006-v022.glb?materials-v2';
export const legacyRoverModelRevision='dcd006-v020-materials-v2';
export const previousRoverModelRevision='dcd006-v022-assembly-v1';
@@ -1,5 +1,11 @@
import {parseEditorLayout,type SceneEditorLayout} from './editorLayout';
import {parseCameraState,type CameraState} from './cameraState';
import {parseChargeGradient,type ChargeGradient} from './chargeGradient';
import equipmentMaterials from './equipmentMaterials.json';
import {roverModelRevision,legacyRoverModelRevision,previousRoverModelRevision} from './model';
import {mergePostFxDefaults,type PostFxSettings} from './postFx'; import {mergePostFxDefaults,type PostFxSettings} from './postFx';
import donorFields from './environmentFields.json'; import donorFields from './environmentFields.json';
import {validObjectId} from './sceneObjects';
export type SceneField={key:string;type:string;label:string;group:string;default?:unknown;min?:number;max?:number;step?:number;options?:{label:string;value:string}[];disabledIf?:string}; export type SceneField={key:string;type:string;label:string;group:string;default?:unknown;min?:number;max?:number;step?:number;options?:{label:string;value:string}[];disabledIf?:string};
export const environmentFields:SceneField[]=[...donorFields, export const environmentFields:SceneField[]=[...donorFields,
{key:'postFx.lut.textureUrl',type:'texture',label:'Таблица LUT',group:'PostProcess/LUT'}, {key:'postFx.lut.textureUrl',type:'texture',label:'Таблица LUT',group:'PostProcess/LUT'},
@@ -9,12 +15,15 @@ export const environmentFields:SceneField[]=[...donorFields,
]; ];
export const textureSlots=['diffuse','normal','metalness','roughness','opacity','emissive','ao'] as const; export const textureSlots=['diffuse','normal','metalness','roughness','opacity','emissive','ao'] as const;
export type TextureSlot=typeof textureSlots[number]; export type TextureSlot=typeof textureSlots[number];
export type MaterialSpec={name:string;color:string;metalness:number;roughness:number;opacity:number;reflectivity:number;clearCoat:number;clearCoatRoughness:number;emissive:string;emissiveIntensity:number;normalStrength:number;doubleSided:boolean;tiling:number;textures:Partial<Record<TextureSlot,{name:string;data:string}>>}; export type MaterialSpec={chargeGradient?:ChargeGradient;name:string;color:string;metalness:number;roughness:number;opacity:number;reflectivity:number;clearCoat:number;clearCoatRoughness:number;emissive:string;emissiveIntensity:number;normalStrength:number;doubleSided:boolean;tiling:number;textures:Partial<Record<TextureSlot,{name:string;data:string}>>};
export type SceneDocument={schema:'missioncore.rover-scene/v1';model:'dcd006-v020-materials-v2';environmentVersion:2;postFx:PostFxSettings;cameraZoomStrength:number;cameraAutoRotate:boolean;materials:Record<string,MaterialSpec>;assignments:Record<string,string>}; export type SceneDocument={schema:'missioncore.rover-scene/v1'|'missioncore.battery-scene/v1';model:string;environmentVersion:2;camera?:CameraState;editorLayout?:SceneEditorLayout;postFx:PostFxSettings;cameraZoomStrength:number;cameraAutoRotate:boolean;materials:Record<string,MaterialSpec>;assignments:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;objects?:Record<string,boolean>};
// Reserve the added equipment slots without consuming the legacy custom-material budget.
export const maxSceneMaterials=128+Object.keys(equipmentMaterials).length;
const material=(name:string,color:string,metalness:number,roughness:number):MaterialSpec=>({name,color,metalness,roughness,opacity:1,reflectivity:1,clearCoat:0,clearCoatRoughness:.3,emissive:'#000000',emissiveIntensity:0,normalStrength:1,doubleSided:false,tiling:1,textures:{}}); const material=(name:string,color:string,metalness:number,roughness:number):MaterialSpec=>({name,color,metalness,roughness,opacity:1,reflectivity:1,clearCoat:0,clearCoatRoughness:.3,emissive:'#000000',emissiveIntensity:0,normalStrength:1,doubleSided:false,tiling:1,textures:{}});
export function defaultScene():SceneDocument{ export function defaultScene():SceneDocument{
const postFx=mergePostFxDefaults(); const postFx=mergePostFxDefaults();
return {schema:'missioncore.rover-scene/v1',model:'dcd006-v020-materials-v2',environmentVersion:2,postFx,cameraZoomStrength:.04,cameraAutoRotate:false,assignments:{},materials:{ return {schema:'missioncore.rover-scene/v1',model:roverModelRevision,environmentVersion:2,postFx,cameraZoomStrength:.04,cameraAutoRotate:false,assignments:{},materials:{
...Object.fromEntries(Object.entries(equipmentMaterials).map(([key,m])=>['rover/'+key,material(m.name,m.color,m.metalness,m.roughness)])),
'rover/body':material('Корпус и подвеска','#2c2f31',.12,.53), 'rover/body':material('Корпус и подвеска','#2c2f31',.12,.53),
'rover/rubber':material('Резина гусениц и катков','#202328',0,.72), 'rover/rubber':material('Резина гусениц и катков','#202328',0,.72),
'rover/track-steel':material('Нержавеющие проставки','#c4c8cd',1,.17), 'rover/track-steel':material('Нержавеющие проставки','#c4c8cd',1,.17),
@@ -27,12 +36,12 @@ export function defaultScene():SceneDocument{
}}; }};
} }
export function createMaterial(doc:SceneDocument,id:string):SceneDocument{ export function createMaterial(doc:SceneDocument,id:string):SceneDocument{
if(!/^custom\/[a-zA-Z0-9-]{1,80}$/.test(id)||Object.hasOwn(doc.materials,id)||Object.keys(doc.materials).length>=128)return doc; if(!/^custom\/[a-zA-Z0-9-]{1,80}$/.test(id)||Object.hasOwn(doc.materials,id)||Object.keys(doc.materials).length>=maxSceneMaterials)return doc;
const used=new Set(Object.values(doc.materials).map(m=>m.name));let n=1;while(used.has(`Материал ${n}`))n++; const used=new Set(Object.values(doc.materials).map(m=>m.name));let n=1;while(used.has(`Материал ${n}`))n++;
return {...doc,materials:{...doc.materials,[id]:material(`Материал ${n}`,'#808080',0,.5)}}; return {...doc,materials:{...doc.materials,[id]:material(`Материал ${n}`,'#808080',0,.5)}};
} }
export function assignMaterial(doc:SceneDocument,group:string,id:string):SceneDocument{ export function assignMaterial(doc:SceneDocument,group:string,id:string):SceneDocument{
if(!Object.hasOwn(defaultScene().materials,group)||!Object.hasOwn(doc.materials,id))return doc; if((!Object.hasOwn(doc.materials,group)||group.startsWith('custom/'))||!Object.hasOwn(doc.materials,id))return doc;
return {...doc,assignments:{...doc.assignments,[group]:id}}; return {...doc,assignments:{...doc.assignments,[group]:id}};
} }
export function fieldValue(doc:SceneDocument,key:string):unknown{return key.split('.').reduce<unknown>((v,k)=>v&&typeof v==='object'?(v as Record<string,unknown>)[k]:undefined,doc);} export function fieldValue(doc:SceneDocument,key:string):unknown{return key.split('.').reduce<unknown>((v,k)=>v&&typeof v==='object'?(v as Record<string,unknown>)[k]:undefined,doc);}
@@ -56,6 +65,7 @@ export function changeField(doc:SceneDocument,key:string,value:unknown):SceneDoc
if(!Array.isArray(value)||value.length!==2||!value.every(Number.isFinite))return doc; if(!Array.isArray(value)||value.length!==2||!value.every(Number.isFinite))return doc;
value=[Math.max(0,Math.min(100,value[0])),Math.max(0,Math.min(100,value[1]))].sort((a,b)=>a-b); value=[Math.max(0,Math.min(100,value[0])),Math.max(0,Math.min(100,value[1]))].sort((a,b)=>a-b);
} }
if(value===old)return doc;
const result={...doc,postFx:structuredClone(doc.postFx)};const parts=key.split('.');const tail=parts.pop()!; const result={...doc,postFx:structuredClone(doc.postFx)};const parts=key.split('.');const tail=parts.pop()!;
const target=parts.reduce((v,k)=>v[k],result as any);target[tail]=value; const target=parts.reduce((v,k)=>v[k],result as any);target[tail]=value;
if(key==='postFx.rendering.fogRange'){[result.postFx.rendering.fogStart,result.postFx.rendering.fogEnd]=value as [number,number];} if(key==='postFx.rendering.fogRange'){[result.postFx.rendering.fogStart,result.postFx.rendering.fogEnd]=value as [number,number];}
@@ -65,11 +75,14 @@ export function changeField(doc:SceneDocument,key:string,value:unknown):SceneDoc
} }
export const materialRanges:Record<string,[number,number]>={metalness:[0,1],roughness:[0,1],opacity:[0,1],reflectivity:[0,1],clearCoat:[0,1],clearCoatRoughness:[0,1],emissiveIntensity:[0,10],normalStrength:[0,2],tiling:[.01,20]}; export const materialRanges:Record<string,[number,number]>={metalness:[0,1],roughness:[0,1],opacity:[0,1],reflectivity:[0,1],clearCoat:[0,1],clearCoatRoughness:[0,1],emissiveIntensity:[0,10],normalStrength:[0,2],tiling:[.01,20]};
export function textureBytes(doc:SceneDocument):number{return Object.values(doc.materials).reduce((sum,m)=>sum+Object.values(m.textures).reduce((n,t)=>n+(t?.data.length??0),0),0);} export function textureBytes(doc:SceneDocument):number{return Object.values(doc.materials).reduce((sum,m)=>sum+Object.values(m.textures).reduce((n,t)=>n+(t?.data.length??0),0),0);}
export function parseScene(raw:unknown):SceneDocument{ export function parseScene(raw:unknown,defaults:()=>SceneDocument=defaultScene):SceneDocument{
const r=raw as SceneDocument;if(!r||r.schema!=='missioncore.rover-scene/v1'||r.model!=='dcd006-v020-materials-v2')throw new Error('Файл сцены не подходит к этой модели.'); const base=defaults(),r=raw as SceneDocument;const models=base.schema==='missioncore.rover-scene/v1'?[roverModelRevision,legacyRoverModelRevision,previousRoverModelRevision]:[base.model];if(!r||r.schema!==base.schema||!models.includes(r.model))throw new Error('Файл сцены не подходит к этой модели.');
let doc=defaultScene(); let doc=base;
const layout=parseEditorLayout(r.editorLayout);if(layout)doc.editorLayout=layout;
const camera=parseCameraState(r.camera);if(camera)doc.camera=camera;
if(doc.objects)for(const id of Object.keys(doc.objects)){const legacy=Object.keys(r.objects??{}).filter(key=>id===key||id.startsWith(key+'/')).sort((a,b)=>b.length-a.length)[0];if(legacy&&typeof r.objects?.[legacy]==='boolean')doc.objects[id]=r.objects[legacy];}
for(const f of environmentFields){const v=fieldValue(r,f.key);if(v!==undefined)doc=changeField(doc,f.key,v);} for(const f of environmentFields){const v=fieldValue(r,f.key);if(v!==undefined)doc=changeField(doc,f.key,v);}
if(Object.keys(r.materials??{}).length>128)throw new Error('В сцене может быть не больше 128 материалов.'); if(Object.keys(r.materials??{}).length>maxSceneMaterials)throw new Error(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);
for(const id of Object.keys(r.materials??{}))if(id.startsWith('custom/'))doc=createMaterial(doc,id); for(const id of Object.keys(r.materials??{}))if(id.startsWith('custom/'))doc=createMaterial(doc,id);
for(const [id,base] of Object.entries(doc.materials)){ for(const [id,base] of Object.entries(doc.materials)){
const m=r.materials?.[id];if(!m)continue; const m=r.materials?.[id];if(!m)continue;
@@ -77,9 +90,27 @@ export function parseScene(raw:unknown):SceneDocument{
for(const key of ['color','emissive'] as const)if(/^#[0-9a-f]{6}$/i.test(m[key]))base[key]=m[key]; for(const key of ['color','emissive'] as const)if(/^#[0-9a-f]{6}$/i.test(m[key]))base[key]=m[key];
for(const [key,[lo,hi]] of Object.entries(materialRanges)){const v=m[key as keyof MaterialSpec];if(typeof v==='number'&&Number.isFinite(v))(base as any)[key]=Math.max(lo,Math.min(hi,v));} for(const [key,[lo,hi]] of Object.entries(materialRanges)){const v=m[key as keyof MaterialSpec];if(typeof v==='number'&&Number.isFinite(v))(base as any)[key]=Math.max(lo,Math.min(hi,v));}
if(typeof m.doubleSided==='boolean')base.doubleSided=m.doubleSided; if(typeof m.doubleSided==='boolean')base.doubleSided=m.doubleSided;
if(m.chargeGradient)base.chargeGradient=parseChargeGradient(m.chargeGradient);
for(const slot of textureSlots){const t=m.textures?.[slot];if(!t)continue;if(typeof t.name!=='string'||typeof t.data!=='string'||t.data.length>12_000_000||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(t.data))throw new Error('Некорректная текстура в файле сцены.');base.textures[slot]={name:t.name.slice(0,200),data:t.data};} for(const slot of textureSlots){const t=m.textures?.[slot];if(!t)continue;if(typeof t.name!=='string'||typeof t.data!=='string'||t.data.length>12_000_000||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(t.data))throw new Error('Некорректная текстура в файле сцены.');base.textures[slot]={name:t.name.slice(0,200),data:t.data};}
} }
for(const [group,id] of Object.entries(r.assignments??{}))if(typeof id==='string')doc=assignMaterial(doc,group,id); for(const [group,id] of Object.entries(r.assignments??{}))if(typeof id==='string')doc=assignMaterial(doc,group,id);
for(const key of ['objectAssignments','objectVisibility'] as const){
const entries=Object.entries(r[key]??{});if(entries.length>4096)throw new Error('Слишком много объектов в файле сцены.');
const values=entries.filter(([id,value])=>validObjectId(id)&&(key==='objectAssignments'?typeof value==='string'&&Object.hasOwn(doc.materials,value):typeof value==='boolean'));
if(values.length)(doc as any)[key]=Object.fromEntries(values);
}
if(base.schema==='missioncore.battery-scene/v1'){
for(const parent of ['bms/labels','bms/CASE | dielectric liner']){
const oldId='object/Model/'+encodeURIComponent(parent);
for(const name of Object.keys(doc.objects??{}).filter(name=>name.startsWith(parent+'/'))){const id='object/Model/'+encodeURIComponent(name);for(const key of ['objectAssignments','objectVisibility'] as const){const values=doc[key];if(values&&values[oldId]!==undefined&&values[id]===undefined)(values as Record<string,unknown>)[id]=values[oldId];}}
}
}
if(base.schema==='missioncore.rover-scene/v1'&&r.model!==roverModelRevision)for(const [key,spec] of Object.entries(equipmentMaterials)){
if(!spec.finish)continue;
const group='rover/'+key,finish=doc.materials['rover/'+spec.finish];
doc.materials[group]={...doc.materials[group],color:finish.color,metalness:finish.metalness,roughness:finish.roughness};
delete doc.assignments[group];
}
if(textureBytes(doc)>28_000_000)throw new Error('Суммарный объём текстур превышает 20 МБ.'); if(textureBytes(doc)>28_000_000)throw new Error('Суммарный объём текстур превышает 20 МБ.');
return doc; return doc;
} }
@@ -0,0 +1,27 @@
/** Session history retains shared immutable document values, not cloned snapshots. */
export class SceneHistory<T> {
private past:T[]=[];
private future:T[]=[];
private grouping=false;
private recorded=false;
constructor(public present:T){}
get canUndo(){return this.past.length>0;}
get canRedo(){return this.future.length>0;}
begin(){this.grouping=true;this.recorded=false;}
end(){this.grouping=false;this.recorded=false;}
reset(value:T){this.present=value;this.past=[];this.future=[];this.end();}
update(value:T){
if(value===this.present)return false;
if(!this.grouping||!this.recorded)this.past.push(this.present);
this.recorded=true;this.future=[];this.present=value;return true;
}
undo(){this.end();if(!this.canUndo)return false;this.future.push(this.present);this.present=this.past.pop()!;return true;}
redo(){this.end();if(!this.canRedo)return false;this.past.push(this.present);this.present=this.future.pop()!;return true;}
}
export function historyCommand(event:{code:string;key:string;ctrlKey:boolean;metaKey:boolean;shiftKey:boolean;altKey:boolean}):'undo'|'redo'|null{
if(!(event.ctrlKey||event.metaKey)||event.altKey)return null;
const key=event.key.toLowerCase();
if(event.code==='KeyZ'||key==='z'||key==='я')return event.shiftKey?'redo':'undo';
if(event.code==='KeyY'||key==='y'||key==='н')return 'redo';
return null;
}
@@ -15,7 +15,8 @@ function withdrawnEnvironment(){
} }
export function loadStoredScene(raw:unknown):{document:SceneDocument;updated:boolean;restoredEnvironment:boolean}{ export function loadStoredScene(raw:unknown):{document:SceneDocument;updated:boolean;restoredEnvironment:boolean}{
const doc=parseScene(raw); const doc=parseScene(raw);
const updated=(raw as Partial<SceneDocument>).environmentVersion!==2; const environmentChanged=(raw as Partial<SceneDocument>).environmentVersion!==2;
const restoredEnvironment=updated&&JSON.stringify(doc.postFx)===JSON.stringify(withdrawnEnvironment()); const updated=environmentChanged||(raw as Partial<SceneDocument>).model!==doc.model;
const restoredEnvironment=environmentChanged&&JSON.stringify(doc.postFx)===JSON.stringify(withdrawnEnvironment());
return {document:restoredEnvironment?{...doc,postFx:defaultScene().postFx}:doc,updated,restoredEnvironment}; return {document:restoredEnvironment?{...doc,postFx:defaultScene().postFx}:doc,updated,restoredEnvironment};
} }
@@ -0,0 +1,15 @@
import type {SceneDocument} from './sceneDocument';
export type SceneObject={id:string;name:string;enabled:boolean;renderable:boolean;materialIds?:string[];children:SceneObject[]};
export const validObjectId=(id:string)=>id.startsWith('object/')&&id.length<=2048&&!/[\u0000-\u001f]/.test(id);
export function objectTargets(node:SceneObject):string[]{return [...(node.renderable?[node.id]:[]),...node.children.flatMap(objectTargets)];}
export function findSceneObject(node:SceneObject|null,id:string|null):SceneObject|undefined{
if(!node||!id)return;return node.id===id?node:node.children.map(child=>findSceneObject(child,id)).find(Boolean);
}
export function assignObjectMaterial(doc:SceneDocument,ids:readonly string[],material:string):SceneDocument{
if(!Object.hasOwn(doc.materials,material)||!ids.length||ids.some(id=>!validObjectId(id)))return doc;
if(ids.every(id=>doc.objectAssignments?.[id]===material))return doc;
const objectAssignments={...doc.objectAssignments};for(const id of ids)objectAssignments[id]=material;
if(Object.keys(objectAssignments).length>4096)return doc;
return {...doc,objectAssignments};
}
@@ -1,5 +1,6 @@
import type {SceneDocument} from './sceneDocument'; import type {SceneDocument} from './sceneDocument';
import {loadStoredScene} from './sceneMigration'; import {loadStoredScene} from './sceneMigration';
// Retain the original storage slot so upgrades preserve operator materials and environment.
const key=(vehicle:string)=>`${vehicle}:dcd006-v020-materials-v2`; const key=(vehicle:string)=>`${vehicle}:dcd006-v020-materials-v2`;
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-rover-scenes',1);r.onupgradeneeded=()=>r.result.createObjectStore('scenes');r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище сцены занято другим окном.'));r.onsuccess=()=>resolve(r.result);});} function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-rover-scenes',1);r.onupgradeneeded=()=>r.result.createObjectStore('scenes');r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище сцены занято другим окном.'));r.onsuccess=()=>resolve(r.result);});}
export async function readScene(vehicle:string):Promise<SceneDocument|null>{ export async function readScene(vehicle:string):Promise<SceneDocument|null>{
@@ -1,22 +1,32 @@
import type {CameraState} from './cameraState';
import {useCallback,useEffect,useRef,useState} from 'react'; import {useCallback,useEffect,useRef,useState} from 'react';
import {defaultScene,parseScene,type SceneDocument} from './sceneDocument'; import {defaultScene,parseScene,type SceneDocument} from './sceneDocument';
import {SceneHistory} from './sceneHistory';
import {readScene,saveScene} from './sceneStorage'; import {readScene,saveScene} from './sceneStorage';
let writes=Promise.resolve(); let writes=Promise.resolve();
const enqueue=(vehicle:string,doc:SceneDocument)=>{const next=writes.catch(()=>{}).then(()=>saveScene(vehicle,doc));writes=next;return next;}; const enqueue=(vehicle:string,doc:SceneDocument,write=saveScene)=>{const next=writes.catch(()=>{}).then(()=>write(vehicle,doc));writes=next;return next;};
export function useSceneDocument(vehicle:string){ export type SceneDocumentProfile={defaults:()=>SceneDocument;read:(id:string)=>Promise<SceneDocument|null>;write:typeof saveScene;filename:string};
const [document,setDocument]=useState(defaultScene),[ready,setReady]=useState(false),[revision,setRevision]=useState(0); export function useSceneDocument(vehicle:string,profile?:SceneDocumentProfile){
const defaults=profile?.defaults??defaultScene,read=profile?.read??readScene,write=profile?.write??saveScene;
const [document,setDocument]=useState(defaults),[ready,setReady]=useState(false),[revision,setRevision]=useState(0);
const [saveState,setSaveState]=useState<'loading'|'saved'|'saving'|'error'>('loading'),[error,setError]=useState(''); const [saveState,setSaveState]=useState<'loading'|'saved'|'saving'|'error'>('loading'),[error,setError]=useState('');
const latest=useRef({document,revision,vehicle});latest.current={document,revision,vehicle}; const latest=useRef({document,revision,vehicle,write});latest.current={document,revision,vehicle,write};
const savedRevision=useRef(0); const pendingCamera=useRef<CameraState|null>(null);
useEffect(()=>{let cancelled=false;readScene(vehicle).then(value=>{if(!cancelled){setDocument(value??defaultScene());setSaveState('saved');}}).catch(()=>{if(!cancelled){setError('Не удалось прочитать сохранённую сцену. Изменения можно экспортировать в JSON.');setSaveState('error');}}).finally(()=>{if(!cancelled)setReady(true);});return()=>{cancelled=true;};},[vehicle]); const savedRevision=useRef(0),history=useRef(new SceneHistory(document));
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{setDocument(d=>fn(d));setRevision(v=>v+1);setSaveState('saving');},[]); const publish=useCallback(()=>{setDocument(history.current.present);setRevision(v=>v+1);setSaveState('saving');},[]);
const undo=useCallback(()=>{pendingCamera.current=null;if(history.current.undo())publish();},[publish]);
const redo=useCallback(()=>{pendingCamera.current=null;if(history.current.redo())publish();},[publish]);
const beginGesture=useCallback(()=>history.current.begin(),[]),endGesture=useCallback(()=>history.current.end(),[]);
useEffect(()=>{let cancelled=false;read(vehicle).then(value=>{if(!cancelled){const doc=value??defaults();history.current.reset(doc);setDocument(doc);setSaveState('saved');}}).catch(()=>{if(!cancelled){setError('Не удалось прочитать сохранённую сцену. Изменения можно экспортировать в JSON.');setSaveState('error');}}).finally(()=>{if(!cancelled)setReady(true);});return()=>{cancelled=true;};},[vehicle,profile]);
const update=useCallback((fn:(doc:SceneDocument)=>SceneDocument)=>{if(history.current.update(fn(history.current.present)))publish();},[publish]);
const recordCamera=useCallback((camera:CameraState,commit=false)=>{pendingCamera.current=camera;if(commit){pendingCamera.current=null;update(doc=>JSON.stringify(doc.camera)===JSON.stringify(camera)?doc:{...doc,camera});}},[update]);
useEffect(()=>{ useEffect(()=>{
if(!ready||revision===0)return; if(!ready||revision===0)return;
let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(()=>{if(!cancelled){setSaveState('error');setError('Не удалось сохранить сцену на этом компьютере. Экспортируйте JSON, чтобы сохранить изменения.');}});},400); let cancelled=false;const timer=setTimeout(()=>{enqueue(vehicle,document,write).then(()=>{savedRevision.current=revision;if(!cancelled)setSaveState('saved');}).catch(()=>{if(!cancelled){setSaveState('error');setError('Не удалось сохранить сцену на этом компьютере. Экспортируйте JSON, чтобы сохранить изменения.');}});},400);
return()=>{cancelled=true;clearTimeout(timer);}; return()=>{cancelled=true;clearTimeout(timer);};
},[ready,revision,vehicle,document]); },[ready,revision,vehicle,document,write]);
useEffect(()=>()=>{const v=latest.current;if(v.revision>savedRevision.current)void enqueue(v.vehicle,v.document).catch(()=>{});},[]); useEffect(()=>()=>{const v=latest.current;if(pendingCamera.current||v.revision>savedRevision.current)void enqueue(v.vehicle,pendingCamera.current?{...v.document,camera:pendingCamera.current}:v.document,v.write).catch(()=>{});},[]);
const importDocument=async(file:File)=>{try{if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()));update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}}; const importDocument=async(file:File)=>{try{if(file.size>32_000_000)throw new Error('Файл сцены больше 32 МБ.');const next=parseScene(JSON.parse(await file.text()),defaults);pendingCamera.current=null;update(()=>next);}catch(e){setError(e instanceof Error?e.message:'Не удалось загрузить сцену.');}};
const exportDocument=()=>{const blob=new Blob([JSON.stringify(document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download='rover-scene.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}; const exportDocument=()=>{const blob=new Blob([JSON.stringify(pendingCamera.current?{...document,camera:pendingCamera.current}:document,null,2)],{type:'application/json'});const url=URL.createObjectURL(blob);const a=globalThis.document.createElement('a');a.href=url;a.download=profile?.filename??'rover-scene.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
return {document,ready,saveState,error,setError,update,importDocument,exportDocument}; return {document,recordCamera,ready,saveState,error,setError,update,undo,redo,canUndo:history.current.canUndo,canRedo:history.current.canRedo,beginGesture,endGesture,importDocument,exportDocument};
} }
+10 -1
View File
@@ -24,7 +24,7 @@ test('invalid stored settings never grant motion or invalid limits',()=>{
test('saved RPM never becomes full throttle during migration',()=>{ test('saved RPM never becomes full throttle during migration',()=>{
const migrated=roverSettings({version:1,maxErpm:3000,currentA:30,mode:'tank',model:'dcd006-v020',throttlePercent:100}); const migrated=roverSettings({version:1,maxErpm:3000,currentA:30,mode:'tank',model:'dcd006-v020',throttlePercent:100});
assert.equal(migrated.version,3);assert.equal(migrated.throttlePercent,10); assert.equal(migrated.version,3);assert.equal(migrated.throttlePercent,10);
assert.equal(migrated.mode,'tank');assert.equal(migrated.model,'dcd006-v020'); assert.equal(migrated.mode,'tank');assert.equal(migrated.model,'dcd006-v022');
assert.equal(roverSettings({...migrated,throttlePercent:50}).throttlePercent,50); assert.equal(roverSettings({...migrated,throttlePercent:50}).throttlePercent,50);
assert.equal(roverSettings({...migrated,throttlePercent:Infinity}).throttlePercent,10); assert.equal(roverSettings({...migrated,throttlePercent:Infinity}).throttlePercent,10);
assert.equal(roverSettings({...migrated,throttlePercent:101}).throttlePercent,100); assert.equal(roverSettings({...migrated,throttlePercent:101}).throttlePercent,100);
@@ -52,3 +52,12 @@ test('operator current above 30 A persists without silently changing it',()=>{
assert.ok(persistableRoverSettings(saved)); assert.ok(persistableRoverSettings(saved));
} }
}); });
test('model selection migrates to the accepted assembly without changing drive settings',()=>{
for(const model of ['dcd006-v020','dcd006-v022']){
const result=roverSettings({version:3,model,mode:'tank',currentA:42,throttlePercent:25,maxErpm:1200});
assert.equal(result.model,'dcd006-v022');assert.equal(result.mode,'tank');
assert.equal(result.currentA,42);assert.equal(result.throttlePercent,25);assert.equal(result.maxErpm,1200);
}
assert.equal(roverSettings({version:3,model:''}).model,'');
});
@@ -44,8 +44,15 @@ test('editing excludes drive bindings and key controls without changing arm auth
const editor=fs.readFileSync(new URL('../src/components/rover/editor/RoverScene.tsx',import.meta.url),'utf8');assert.doesNotMatch(editor,/\.arm\(|setDemand|\/api\/v1\/fleet/); const editor=fs.readFileSync(new URL('../src/components/rover/editor/RoverScene.tsx',import.meta.url),'utf8');assert.doesNotMatch(editor,/\.arm\(|setDemand|\/api\/v1\/fleet/);
}); });
test('export manifest retains complete geometry and all editable material groups',()=>{ test('export manifest retains complete geometry and all editable material groups',()=>{
const manifest=JSON.parse(fs.readFileSync(new URL('../public/rover-scene/dcd006-v020.json',import.meta.url),'utf8')); const manifest=JSON.parse(fs.readFileSync(new URL('../public/rover-scene/dcd006-v022.json',import.meta.url),'utf8'));
assert.equal(manifest.source_object_count,1426);assert.equal(manifest.render_mesh_count,9);assert.equal(manifest.source_saved,false);assert.match(manifest.uv,/cube/); assert.equal(manifest.source_object_count,1281);assert.equal(manifest.render_mesh_count,Object.keys(defaultScene().materials).length);assert.equal(manifest.source_saved,false);assert.match(manifest.uv,/cube/);
assert.equal(manifest.source_sha256,'4fae2c9928b3254475d01929f042d1604af3fbc196bb93ad39543384f15d8a86');
assert.equal(Object.keys(manifest.mount_frames.source_world_matrices).length,16);
const cam=manifest.mount_frames.source_world_matrices.FRAME_CAM_FIXED;
assert.ok(Math.abs(cam[0][3]-.173)<1e-6);assert.ok(Math.abs(cam[1][3]-.0065)<1e-6);assert.ok(Math.abs(cam[2][3]-.603940785)<1e-6);
const names=Object.values(manifest.materials).flatMap(m=>m.sourceObjects);
for(const part of ['CAM MOLLE R09 • D22 • фиксированная','K1 V2 C22 · Держатель · карман 58.8×53','K1 V2 · Съёмная крышка','K1 V2 C21 · Нижнее основание'])assert.ok(names.includes(part),part);
assert.ok(!names.some(n=>/VAN004|LANTSUN|COMMS \|/.test(n)));
assert.deepEqual(Object.keys(manifest.materials).sort(),Object.keys(defaultScene().materials).map(k=>k.replace('rover/','')).sort()); assert.deepEqual(Object.keys(manifest.materials).sort(),Object.keys(defaultScene().materials).map(k=>k.replace('rover/','')).sort());
}); });
@@ -41,3 +41,51 @@ test('already restored legacy NodeDC scene is only versioned, not altered',()=>{
const raw=defaultScene();delete raw.environmentVersion;const r=loadStoredScene(raw); const raw=defaultScene();delete raw.environmentVersion;const r=loadStoredScene(raw);
assert.equal(r.updated,true);assert.equal(r.restoredEnvironment,false);assert.deepEqual(r.document.postFx,raw.postFx); assert.equal(r.updated,true);assert.equal(r.restoredEnvironment,false);assert.deepEqual(r.document.postFx,raw.postFx);
}); });
test('v020 material work migrates to v022 while adding equipment and preserving environment',()=>{
const raw=defaultScene();raw.model='dcd006-v020-materials-v2';
for(const key of Object.keys(raw.materials))if(key.startsWith('rover/equipment-'))delete raw.materials[key];
raw.materials['rover/body'].color='#123456';
raw.materials['rover/body'].textures.diffuse={name:'retained.png',data:'data:image/png;base64,YWJj'};
raw.assignments['rover/box']='rover/body';raw.postFx.lighting.exposure=1.7;
raw.cameraAutoRotate=true;raw.cameraZoomStrength=.09;
const before=structuredClone(raw),r=loadStoredScene(raw);
assert.equal(r.updated,true);assert.equal(r.restoredEnvironment,false);
assert.equal(r.document.model,'dcd006-v022-materials-v2');
for(const [id,m] of Object.entries(raw.materials))assert.deepEqual(r.document.materials[id],m);
assert.deepEqual(r.document.assignments,raw.assignments);assert.deepEqual(r.document.postFx,raw.postFx);
assert.equal(r.document.cameraAutoRotate,true);assert.equal(r.document.cameraZoomStrength,.09);
assert.ok(Object.keys(r.document.materials).some(id=>id.startsWith('rover/equipment-')));
assert.deepEqual(raw,before);assert.equal(loadStoredScene(r.document).updated,false);
assert.deepEqual(parseScene(raw),r.document,'JSON import uses the same migration');
});
test('a full legacy palette loses no custom material when equipment groups are added',()=>{
const raw=defaultScene();raw.model='dcd006-v020-materials-v2';
for(const key of Object.keys(raw.materials))if(key.startsWith('rover/equipment-'))delete raw.materials[key];
for(let i=0;i<119;i++)raw.materials['custom/retained-'+i]={...structuredClone(raw.materials['rover/body']),name:'Saved '+i};
raw.assignments['rover/box']='custom/retained-118';
assert.equal(Object.keys(raw.materials).length,128);
const {document}=loadStoredScene(raw);
for(const [id,material] of Object.entries(raw.materials))assert.deepEqual(document.materials[id],material);
assert.equal(document.assignments['rover/box'],'custom/retained-118');
assert.deepEqual(parseScene(document),document);
});
test('first v022 pale manufacturing colors migrate once to owner-approved dark finishes',()=>{
const raw=defaultScene();raw.model='dcd006-v022-assembly-v1';
const printed=['equipment-0493091ab933','equipment-1d261a8554d2','equipment-2ab952389fe9','equipment-69e526e4be1d'];
for(const key of [...printed,'equipment-13e890e68f3f']){
raw.materials['rover/'+key].color='#ffffff';raw.materials['rover/'+key].metalness=.8;
raw.assignments['rover/'+key]='rover/motor';
}
const r=loadStoredScene(raw);assert.equal(r.updated,true);
for(const key of printed)for(const field of ['color','metalness','roughness'])assert.equal(r.document.materials['rover/'+key][field],r.document.materials['rover/body'][field]);
assert.equal(r.document.materials['rover/equipment-13e890e68f3f'].color,r.document.materials['rover/polymer'].color);
assert.equal(r.document.materials['rover/equipment-13e890e68f3f'].metalness,0);
for(const key of printed)assert.equal(r.document.assignments['rover/'+key],undefined);
assert.deepEqual(r.document.postFx,raw.postFx);
const current=r.document;current.materials['rover/equipment-0493091ab933'].color='#123456';
assert.equal(loadStoredScene(current).document.materials['rover/equipment-0493091ab933'].color,'#123456','later deliberate editing is retained');
assert.equal(loadStoredScene(current).updated,false);
});
@@ -0,0 +1,40 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const load=async path=>{const r=await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(r.outputFiles[0].contents).toString('base64'));};
const {parseEditorLayout,materialTileSizes,editorDockLayout}=await load('../src/core/roverScene/editorLayout.ts');
const {defaultScene,parseScene}=await load('../src/core/roverScene/sceneDocument.ts');
const {defaultBatteryScene}=await load('../src/core/batteryScene/profile.ts');
const {SceneHistory}=await load('../src/core/roverScene/sceneHistory.ts');
const layout={windows:{objects:{left:24,top:88,width:421,height:617},palette:{left:440,top:640,width:660,height:312},material:{left:1110,top:100,width:420,height:700},environment:{left:800,top:66,width:510,height:660}},materialTileSize:104};
test('all editor windows and palette density round trip with both scene profiles, independently of camera/materials',()=>{
for(const defaults of [defaultScene,defaultBatteryScene]){
const base=defaults(),document={...base,editorLayout:layout};
const read=parseScene(JSON.parse(JSON.stringify(document)),defaults);
assert.deepEqual(read.editorLayout,layout);assert.deepEqual(read.camera,base.camera);assert.deepEqual(read.materials,base.materials);
assert.equal(defaults().editorLayout,undefined);assert.equal(parseScene(base,defaults).editorLayout,undefined);
}
});
test('untrusted layout JSON cannot inject unknown windows, invalid rectangles or unusable tile sizes',()=>{
const read=parseEditorLayout({windows:{unknown:layout.windows.objects,objects:{left:NaN,top:0,width:Infinity,height:1},palette:{left:1e9,top:-1e9,width:1e9,height:400},material:{left:0,top:0,width:-50,height:100}},materialTileSize:-100});
assert.deepEqual(Object.keys(read.windows),['palette']);assert.equal(read.windows.palette.left,16384);assert.equal(read.windows.palette.top,-16384);assert.equal(read.windows.palette.width,16384);assert.equal(read.materialTileSize,materialTileSizes.min);
assert.equal(parseEditorLayout(null),undefined);assert.equal(parseEditorLayout({materialTileSize:Infinity}).materialTileSize,materialTileSizes.default);
});
test('window moves and tile size changes participate in scene undo/redo without mutating prior layouts',()=>{
const base={...defaultBatteryScene(),editorLayout:layout},history=new SceneHistory(base);
const moved={...base,editorLayout:{...layout,windows:{...layout.windows,objects:{...layout.windows.objects,left:100}}}};
history.update(moved);history.update({...moved,editorLayout:{...moved.editorLayout,materialTileSize:84}});
history.undo();assert.equal(history.present,moved);history.undo();assert.equal(history.present,base);assert.equal(layout.windows.objects.left,24);
history.redo();history.redo();assert.equal(history.present.editorLayout.materialTileSize,84);
});
test('docking and detached rectangles round trip for battery and rover without altering the source view',()=>{
const docking={tree:{axis:'y',ratio:73,first:{id:'viewport'},second:{axis:'x',ratio:60,first:{id:'palette'},second:{id:'objects'}}},floating:{material:layout.windows.material}};
for(const defaults of [defaultScene,defaultBatteryScene]){
const base=defaults(),next={...base,editorLayout:{...layout,docking}},read=parseScene(JSON.parse(JSON.stringify(next)),defaults);
assert.deepEqual(read.editorLayout.docking,docking);assert.deepEqual(read.camera,base.camera);
const history=new SceneHistory(base);history.update(read);history.undo();assert.equal(history.present,base);history.redo();assert.deepEqual(history.present.editorLayout.docking,docking);
}
assert.deepEqual(editorDockLayout(layout),{tree:{id:'viewport'},floating:layout.windows});
const invalid=parseEditorLayout({...layout,docking:{tree:{id:'other'},floating:{viewport:layout.windows.objects,objects:layout.windows.objects}}});
assert.deepEqual(invalid.docking.tree,{id:'viewport'});assert.deepEqual(Object.keys(invalid.docking.floating),['objects']);
});
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const load=async path=>{const r=await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(r.outputFiles[0].contents).toString('base64'));};
const {SceneHistory,historyCommand}=await load('../src/core/roverScene/sceneHistory.ts');
const {defaultChargeGradient,chargePair,parseChargeGradient}=await load('../src/core/roverScene/chargeGradient.ts');
const {defaultBatteryScene}=await load('../src/core/batteryScene/profile.ts');
const {parseScene,changeField}=await load('../src/core/roverScene/sceneDocument.ts');
test('one slider gesture is one undo step; redo, branch replacement and more than a thousand steps',()=>{
const h=new SceneHistory(0);h.begin();for(let i=1;i<=80;i++)h.update(i);h.end();h.undo();assert.equal(h.present,0);h.redo();assert.equal(h.present,80);
for(let i=81;i<=1200;i++)h.update(i);
for(let i=1199;i>=80;i--){assert.equal(h.undo(),true);assert.equal(h.present,i);}
h.undo();assert.equal(h.present,0);assert.equal(h.undo(),false);h.redo();assert.equal(h.present,80);h.update(5);assert.equal(h.canRedo,false);
});
test('history restores environment, assignments, visibility and gradient while sharing untouched textures',()=>{
const initial=defaultBatteryScene(),h=new SceneHistory(initial);
h.update(changeField(h.present,'postFx.lighting.exposure',1.9));
const lighting=h.present;h.update({...lighting,objectVisibility:{'object/Model/cell':false}});
const visibility=h.present;h.update({...visibility,objectAssignments:{'object/Model/cell':'bms/glass'}});
h.undo();assert.equal(h.present,visibility);h.undo();assert.equal(h.present,lighting);h.undo();assert.equal(h.present,initial);assert.equal(lighting.materials,initial.materials);
});
test('undo and redo accept physical keys or English/Russian key labels on Ctrl and Cmd',()=>{
for(const modifier of ['ctrlKey','metaKey'])for(const [key,code] of [['z','KeyZ'],['я','KeyZ'],['я',''],['z','']]){
const e={key,code,ctrlKey:false,metaKey:false,shiftKey:false,altKey:false,[modifier]:true};assert.equal(historyCommand(e),'undo');assert.equal(historyCommand({...e,shiftKey:true}),'redo');assert.equal(historyCommand({...e,altKey:true}),null);
}
assert.equal(historyCommand({key:'н',code:'KeyY',ctrlKey:true,metaKey:false,shiftKey:false,altKey:false}),'redo');
});
test('charge gradient interpolates both colour pairs, clamps SOC and validates JSON',()=>{
const g={...defaultChargeGradient(),lowA:'#000000',lowB:'#ff0000',highA:'#ffffff',highB:'#00ff00'};
assert.deepEqual(chargePair(g,0),[[0,0,0],[1,0,0]]);assert.deepEqual(chargePair(g,100),[[1,1,1],[0,1,0]]);assert.deepEqual(chargePair(g,50),[[.5,.5,.5],[.5,.5,0]]);assert.deepEqual(chargePair(g,200),chargePair(g,100));
const doc=defaultBatteryScene();doc.materials['bms/cells'].chargeGradient=g;
assert.deepEqual(parseScene(JSON.parse(JSON.stringify(doc)),defaultBatteryScene).materials['bms/cells'].chargeGradient,g);
assert.equal(parseChargeGradient({...g,speed:Infinity,scale:500,intensity:-10}).scale,50);assert.equal(parseChargeGradient({...g,intensity:-10}).intensity,0);
const old=defaultBatteryScene();delete old.materials['bms/cells'].chargeGradient;assert.deepEqual(parseScene(old,defaultBatteryScene).materials['bms/cells'].chargeGradient,defaultChargeGradient());
});
@@ -0,0 +1,46 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {build} from 'esbuild';
const load=async path=>{const r=await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(r.outputFiles[0].contents).toString('base64'));};
const {defaultBatteryScene}=await load('../src/core/batteryScene/profile.ts');
const {parseScene,createMaterial}=await load('../src/core/roverScene/sceneDocument.ts');
const {assignObjectMaterial,objectTargets}=await load('../src/core/roverScene/sceneObjects.ts');
const {buildSceneTree,sceneObjectId}=await load('../src/components/rover/playcanvas/sceneTree.ts');
test('material assigned to one wall survives JSON without changing sibling walls or shared material',()=>{
let doc=createMaterial(defaultBatteryScene(),'custom/glass');doc.materials['custom/glass'].opacity=.15;
const wall='object/Model/side-left',other='object/Model/side-right';
doc=assignObjectMaterial(doc,[wall],'custom/glass');doc.objectVisibility={[wall]:false};
const imported=parseScene(JSON.parse(JSON.stringify(doc)),defaultBatteryScene);
assert.equal(imported.objectAssignments[wall],'custom/glass');assert.equal(imported.objectAssignments[other],undefined);
assert.equal(imported.materials['bms/glass'].opacity,defaultBatteryScene().materials['bms/glass'].opacity);
assert.equal(imported.objectVisibility[wall],false);
assert.equal(assignObjectMaterial(doc,[wall],'missing'),doc);assert.equal(assignObjectMaterial(doc,['invalid'],'custom/glass'),doc);
});
test('scene object identity ignores random GUIDs; containment includes internal parts and duplicate names',()=>{
const make=()=>{const root={name:'ModelRoot',enabled:true,children:[]};const parent={name:'Model',parent:root,children:[],getGuid:()=>Math.random()};root.children.push(parent);for(let i=0;i<2;i++)parent.children.push({name:'part',parent,children:[],render:{meshInstances:[{}]},getGuid:()=>Math.random()});return root;};
const map=new Map(),tree=buildSceneTree(make(),map),again=buildSceneTree(make(),new Map());
assert.deepEqual(tree,again);assert.equal(objectTargets(tree).length,2);assert.notEqual(objectTargets(tree)[0],objectTargets(tree)[1]);
for(const [id,node] of map)assert.equal(sceneObjectId(node),id);
});
test('R04 GLB contains separate lid, two sides and both endplates, retaining thirteen cells',async()=>{
const raw=await readFile(new URL('../public/battery-scene/catl-r04.glb',import.meta.url));
const gltf=JSON.parse(raw.subarray(20,20+raw.readUInt32LE(12)).toString());
const names=gltf.nodes.filter(n=>n.mesh!==undefined).map(n=>n.name);
for(const name of ['CASE | removable solid top','CASE | slotted side -1','CASE | slotted side 1','CASE | front endplate','CASE | rear endplate'])assert.equal(names.filter(n=>n.endsWith('/'+name)).length,1,name);
assert.equal(names.filter(n=>/^bms\/cells\/C\d+/.test(n)).length,13);
const old={...defaultBatteryScene(),objects:{'bms/glass':false}};
const migrated=parseScene(old,defaultBatteryScene);
for(const [id,visible] of Object.entries(migrated.objects))if(id.startsWith('bms/glass/'))assert.equal(visible,false);
});
test('cell labels are independent of enclosure labels and legacy visibility/assignment migrates',async()=>{
const raw=await readFile(new URL('../public/battery-scene/catl-r04.glb',import.meta.url));
const gltf=JSON.parse(raw.subarray(20,20+raw.readUInt32LE(12)).toString());
const labels=gltf.nodes.filter(n=>n.mesh!==undefined&&n.name.startsWith('bms/labels/'));
assert.deepEqual(labels.map(n=>n.name).sort(),['bms/labels/cells','bms/labels/electronics','bms/labels/enclosure']);
const old=defaultBatteryScene(),oldId='object/Model/'+encodeURIComponent('bms/labels');
old.objectAssignments={[oldId]:'bms/glass'};old.objectVisibility={[oldId]:false};
const doc=parseScene(old,defaultBatteryScene);
for(const part of labels){const id='object/Model/'+encodeURIComponent(part.name);assert.equal(doc.objectAssignments[id],'bms/glass');assert.equal(doc.objectVisibility[id],false);}
});
+34
View File
@@ -0,0 +1,34 @@
DCD-006 v022 — PlayCanvas visual assembly
Source: DCD-006_rover_v022_CAM_R09_K1_C22_REVIEW.blend
SHA-256: 4fae2c9928b3254475d01929f042d1604af3fbc196bb93ad39543384f15d8a86
Approved for PlayCanvas integration by the owner on 2026-10-31.
From the canonical Mission Core repository root:
/Applications/Blender.app/Contents/MacOS/Blender --background --disable-autoexec <source.blend> --python tools/rover-scene/export_rover.py -- --revision v022 --equipment-collection '04 ОБОРУДОВАНИЕ • актуальная сборка'
Outputs:
- apps/control-station/public/rover-scene/dcd006-v022.glb
- apps/control-station/public/rover-scene/dcd006-v022.json
- apps/control-station/src/core/roverScene/equipmentMaterials.json
The export evaluates the source geometry, keeps 1281 visible geometry instances,
and batches them into 40 editable material meshes (3,246,371 triangles).
It does not decimate geometry or save the source Blend. Review lights, cameras,
reference images, hidden Boolean tools and empty anchors are not rendered.
The nine existing chassis/case material groups preserve operator edits. The 31
equipment material groups retain authored PBR values except owner-approved finishes:
CAM MOLLE and K1 base/holder/cap match the matte black frame; X4 is dark polymer.
The previous v022 pale palette migrates once. CAD pieces whose shader
was untouched default gray use their authored Blender viewport color instead.
Legacy v020 scene documents and model selections migrate to v022; environment,
textures, custom materials and assignments remain. The historical IndexedDB
slot stays stable. The motion GLB and simulation/physics profiles stay v020.
The manifest includes all 16 original engineering world matrices in metres and
an explicit source-to-GLTF matrix for the viewer's centering and Y-up transform.
CAM remains at (0.173, 0.0065, 0.603940785) m; K1 follows the C22 CAD assembly.
These are mounting references, not calibrated camera or LiDAR extrinsics.
Insta360 X4 remains an envelope; its tripod/hinge and antenna placement are
approximate from IMG_2844. No commercial model was acquired.
+44
View File
@@ -0,0 +1,44 @@
"""Carry v022 equipment PBR and authored CAD viewport colors into editable groups."""
import hashlib
import re
import bpy
from materials import specs
PRINTED_MATERIALS={"V2 · base", "V2 · holder", "V2 · cap", "Graphite"}
DARK_PLASTIC_MATERIALS={"R01 | X4 габаритный макет"}
def equipment_material(source):
name = re.sub(r'\.\d{3}$', '', source.name)
key = 'equipment-' + hashlib.sha256(name.encode()).hexdigest()[:12]
node = source.node_tree.nodes.get('Principled BSDF') if source.use_nodes else None
color = list(node.inputs['Base Color'].default_value) if node else list(source.diffuse_color)
# Several manufacturing parts only set diffuse_color; their untouched node
# still has Blender's default 0.8 gray. Do not export those parts as white.
viewport = list(source.diffuse_color)
fallback = node is not None and all(abs(v - .8) < 1e-6 for v in color[:3]) and any(abs(v - .8) > 1e-6 for v in viewport[:3])
if fallback:
color = viewport
metal = float(source.metallic if fallback or node is None else node.inputs['Metallic'].default_value)
rough = float(source.roughness if fallback or node is None else node.inputs['Roughness'].default_value)
color_source = 'viewport' if fallback else 'shader'
# Owner's physical finish: printed CAM/K1 parts match the frame; X4 is dark plastic.
finish = 'body' if name in PRINTED_MATERIALS else 'polymer' if name in DARK_PLASTIC_MATERIALS else None
if finish:
_, rgb, metal, rough = specs[finish]
color = [*rgb, 1]
color_source = 'owner/' + finish
material = bpy.data.materials.new('rover/' + key)
material.use_nodes = True
bs = material.node_tree.nodes.get('Principled BSDF')
bs.inputs['Base Color'].default_value = color
bs.inputs['Metallic'].default_value = metal
bs.inputs['Roughness'].default_value = rough
return key, (name, tuple(color[:3]), metal, rough), material, color_source
def srgb_hex(color):
def channel(c):
v = 12.92 * c if c <= .0031308 else 1.055 * c ** (1 / 2.4) - .055
return round(max(0, min(1, v)) * 255)
return '#' + ''.join(f'{channel(c):02x}' for c in color)
+35 -7
View File
@@ -1,5 +1,9 @@
"""Evaluated v020 geometry, semantic PBR groups and UVs; never saves the source.""" """Evaluated geometry and editable PBR groups; never saves the source.
import bpy, json, hashlib
Blender -b <source.blend> --python tools/rover-scene/export_rover.py -- \
--revision v022 --equipment-collection "04 ОБОРУДОВАНИЕ • актуальная сборка"
"""
import bpy, json, hashlib, argparse
from collections import defaultdict from collections import defaultdict
from pathlib import Path from pathlib import Path
from mathutils import Vector, Matrix from mathutils import Vector, Matrix
@@ -7,6 +11,16 @@ root=Path.cwd();source=Path(bpy.data.filepath)
import sys import sys
sys.path.insert(0,str(Path(__file__).resolve().parent)) sys.path.insert(0,str(Path(__file__).resolve().parent))
from materials import specs, materials, classify from materials import specs, materials, classify
from equipment_materials import equipment_material, srgb_hex
parser=argparse.ArgumentParser()
parser.add_argument('--revision',default='v020')
parser.add_argument('--equipment-collection')
args=parser.parse_args(sys.argv[sys.argv.index('--')+1:] if '--' in sys.argv else [])
if args.revision not in {'v020','v022'}:parser.error('Unsupported rover revision')
equipment=set(bpy.data.collections[args.equipment_collection].all_objects) if args.equipment_collection else set()
bpy.context.view_layer.update()
equipment_cache={};color_sources={};frames={o.name:[list(row) for row in o.matrix_world] for o in bpy.context.scene.objects if o.name.startswith('FRAME_') and o.type=='EMPTY'}
bpy.context.scene.frame_set(1);dg=bpy.context.evaluated_depsgraph_get();instances=[];assignment=defaultdict(set) bpy.context.scene.frame_set(1);dg=bpy.context.evaluated_depsgraph_get();instances=[];assignment=defaultdict(set)
for inst in dg.object_instances: for inst in dg.object_instances:
@@ -16,7 +30,14 @@ for inst in dg.object_instances:
if not inst.is_instance and not src.visible_get():continue if not inst.is_instance and not src.visible_get():continue
mesh=bpy.data.meshes.new_from_object(o,preserve_all_data_layers=True,depsgraph=dg) mesh=bpy.data.meshes.new_from_object(o,preserve_all_data_layers=True,depsgraph=dg)
for idx in range(len(mesh.materials)): for idx in range(len(mesh.materials)):
name=mesh.materials[idx].name if mesh.materials[idx] else '';key=classify(name,src.name) source_material=mesh.materials[idx]
name=source_material.name if source_material else ''
if src in equipment and source_material:
if name not in equipment_cache:
key,spec,mat,color_source=equipment_material(source_material)
equipment_cache[name]=key;specs[key]=spec;materials[key]=mat;color_sources[key]=color_source
key=equipment_cache[name]
else:key=classify(name,src.name)
mesh.materials[idx]=materials[key];assignment[key].add(src.name) mesh.materials[idx]=materials[key];assignment[key].add(src.name)
if not mesh.materials:mesh.materials.append(materials['body']);assignment['body'].add(src.name) if not mesh.materials:mesh.materials.append(materials['body']);assignment['body'].add(src.name)
instances.append((src.name,mesh,inst.matrix_world.copy())) instances.append((src.name,mesh,inst.matrix_world.copy()))
@@ -30,7 +51,7 @@ shift=Vector((-(lo.x+hi.x)/2,-(lo.y+hi.y)/2,-lo.z))
for o in objects:o.matrix_world=Matrix.Translation(shift)@o.matrix_world for o in objects:o.matrix_world=Matrix.Translation(shift)@o.matrix_world
count=len(objects) count=len(objects)
bpy.ops.object.select_all(action='SELECT');bpy.context.view_layer.objects.active=objects[0];bpy.ops.object.join() bpy.ops.object.select_all(action='SELECT');bpy.context.view_layer.objects.active=objects[0];bpy.ops.object.join()
# Separate by material keeps picking exact while avoiding 1,426 draw calls. # Batch by material to keep exact surface picking with a bounded draw-call count.
bpy.ops.object.mode_set(mode='EDIT');bpy.ops.mesh.select_all(action='SELECT');bpy.ops.mesh.separate(type='MATERIAL');bpy.ops.object.mode_set(mode='OBJECT') bpy.ops.object.mode_set(mode='EDIT');bpy.ops.mesh.select_all(action='SELECT');bpy.ops.mesh.separate(type='MATERIAL');bpy.ops.object.mode_set(mode='OBJECT')
for o in list(scene.objects): for o in list(scene.objects):
bpy.ops.object.select_all(action='DESELECT');o.select_set(True);bpy.context.view_layer.objects.active=o bpy.ops.object.select_all(action='DESELECT');o.select_set(True);bpy.context.view_layer.objects.active=o
@@ -38,8 +59,15 @@ for o in list(scene.objects):
for uv in list(o.data.uv_layers):o.data.uv_layers.remove(uv) for uv in list(o.data.uv_layers):o.data.uv_layers.remove(uv)
bpy.ops.object.mode_set(mode='EDIT');bpy.ops.mesh.select_all(action='SELECT');bpy.ops.uv.cube_project(cube_size=.2);bpy.ops.object.mode_set(mode='OBJECT') bpy.ops.object.mode_set(mode='EDIT');bpy.ops.mesh.select_all(action='SELECT');bpy.ops.uv.cube_project(cube_size=.2);bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='SELECT') bpy.ops.object.select_all(action='SELECT')
out=root/'apps/control-station/public/rover-scene/dcd006-v020.glb' out=root/f'apps/control-station/public/rover-scene/dcd006-{args.revision}.glb'
bpy.ops.export_scene.gltf(filepath=str(out),export_format='GLB',use_selection=True,use_active_scene=True,export_animations=False,export_cameras=False,export_lights=False,export_extras=False,export_yup=True,export_apply=False,export_texcoords=True,export_attributes=False,export_vertex_color='NONE') bpy.ops.export_scene.gltf(filepath=str(out),export_format='GLB',use_selection=True,use_active_scene=True,export_animations=False,export_cameras=False,export_lights=False,export_extras=False,export_yup=True,export_apply=False,export_texcoords=True,export_attributes=False,export_vertex_color='NONE')
manifest={'source':source.name,'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'model':'DCD-006 v020 complete rover','revision':'materials-v2','source_object_count':count,'render_mesh_count':len(scene.objects),'original_bounds':[list(lo),list(hi)],'dimensions_m':list(hi-lo),'translation_m':list(shift),'glb_bytes':out.stat().st_size,'glb_sha256':hashlib.sha256(out.read_bytes()).hexdigest(),'source_saved':False,'uv':'cube projection, 0.2 m','materials':{k:{'name':v[0],'baseColorLinear':v[1],'metalness':v[2],'roughness':v[3],'sourceObjects':sorted(assignment[k])} for k,v in specs.items()}} manifest={'source':source.name,'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'model':f'DCD-006 {args.revision} complete rover','revision':'materials-v2' if args.revision=='v022' else 'materials-v2','source_object_count':count,'render_mesh_count':len(scene.objects),'original_bounds':[list(lo),list(hi)],'dimensions_m':list(hi-lo),'translation_m':list(shift),'glb_bytes':out.stat().st_size,'glb_sha256':hashlib.sha256(out.read_bytes()).hexdigest(),'source_saved':False,'uv':'cube projection, 0.2 m','materials':{k:{'name':v[0],'baseColorLinear':v[1],'metalness':v[2],'roughness':v[3],'sourceObjects':sorted(assignment[k])} for k,v in specs.items()}}
(out.parent/'dcd006-v020.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n') # Source anchors remain in engineering coordinates. The explicit transform maps
# each original Blender point to the centered Y-up GLB without losing placement.
manifest['mount_frames']={'units':'metres','source_axes':'+X forward, +Z up','source_world_matrices':frames,'source_to_gltf_matrix':[[1,0,0,shift.x],[0,0,1,shift.z],[0,-1,0,-shift.y],[0,0,0,1]]}
manifest['equipment_color_sources']=color_sources
if equipment:
equipment_defaults={key:{'name':specs[key][0],'color':srgb_hex(specs[key][1]),'metalness':specs[key][2],'roughness':specs[key][3],'finish':color_sources[key].removeprefix('owner/') if color_sources[key].startswith('owner/') else ''} for key in sorted(color_sources)}
(root/'apps/control-station/src/core/roverScene/equipmentMaterials.json').write_text(json.dumps(equipment_defaults,ensure_ascii=False,indent=2)+'\n')
(out.with_suffix('.json')).write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n')
print('ROVER EXPORT',out.stat().st_size,'bytes;',len(scene.objects),'material groups') print('ROVER EXPORT',out.stat().st_size,'bytes;',len(scene.objects),'material groups')