feat(battery-ui): integrate observatory detail, appearance controls and compact BMS hierarchy
This commit is contained in:
@@ -1,31 +1,23 @@
|
||||
import {BatteryDesignSettings} from './BatteryDesignSettings';
|
||||
import {useRef,useState} from 'react';
|
||||
import {Button,ColorField,ControlRow,Description,FeatureSettingsWindow,Icon,IconButton,RangeControl,SettingsCard} from '@nodedc/ui-react';
|
||||
import {parseBatteryAppearance,type BatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
import {parseBatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
import type {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
|
||||
type Section='markings'|'panels';
|
||||
export function BatteryAppearanceSettings({open,onClose,profile}:{open:boolean;onClose:()=>void;profile:ReturnType<typeof useBatteryAppearance>}){
|
||||
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
|
||||
import {BmsSettings} from '../../../../../plugins/jk-bms/frontend/src/BmsSettings';
|
||||
type Section='markings'|'panels'|'diagnostics'|'protection'|'control';
|
||||
export function BatteryAppearanceSettings({open,onClose,profile,sensor}:{sensor?:SensorDetailProps;open:boolean;onClose:()=>void;profile:ReturnType<typeof useBatteryAppearance>}){
|
||||
const [section,setSection]=useState<Section>('markings'),input=useRef<HTMLInputElement>(null);
|
||||
const {value,update}=profile,p=value.panels,m=value.markings;
|
||||
const panel=(patch:Partial<BatteryAppearance['panels']>)=>update({...value,panels:{...p,...patch}});
|
||||
const glass=(patch:Partial<typeof p.glass>)=>panel({glass:{...p.glass,...patch}});
|
||||
const {value,update}=profile,m=value.markings;
|
||||
const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>;
|
||||
const exportJson=()=>{const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='battery-ui.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||
return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Интерфейс батареи',subtitle:'Локальный профиль',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Плашки показаний',icon:'settings'}]} activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
headerActions={<><IconButton label="Отменить настройку батареи" disabled={!profile.canUndo} onClick={profile.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить настройку батареи" disabled={!profile.canRedo} onClick={profile.redo}><Icon name="redo"/></IconButton></>}
|
||||
footer={<><Button onClick={exportJson}>Экспорт JSON</Button><Button onClick={()=>input.current?.click()}>Импорт JSON</Button><input ref={input} type="file" accept="application/json,.json" hidden onChange={async event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(!file)return;try{if(file.size>32000)throw new Error('Файл настроек слишком большой.');update(parseBatteryAppearance(JSON.parse(await file.text())));}catch(error){profile.setError(error instanceof Error?error.message:'Не удалось прочитать профиль.');}}}/></>}>
|
||||
{section==='markings'?<SettingsCard title="Маркировка ячеек" description="Номер и напряжение на заводских площадках модели. Размер меняет надпись внутри площадки.">
|
||||
return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Батарея',subtitle:section==='markings'||section==='panels'?'Локальный профиль':'BMS',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Дизайн',icon:'settings'},...(sensor?[{id:'diagnostics' as const,label:'Диагностика BMS',icon:'activity' as const},{id:'protection' as const,label:'Параметры BMS',icon:'sliders' as const},{id:'control' as const,label:'Управление BMS',icon:'power' as const}]:[])]} activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
headerActions={(section==='markings'||section==='panels')&&<><IconButton label="Отменить настройку батареи" disabled={!profile.canUndo} onClick={profile.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить настройку батареи" disabled={!profile.canRedo} onClick={profile.redo}><Icon name="redo"/></IconButton></>}
|
||||
footer={(section==='markings'||section==='panels')&&<><Button onClick={exportJson}>Экспорт JSON</Button><Button onClick={()=>input.current?.click()}>Импорт JSON</Button><input ref={input} type="file" accept="application/json,.json" hidden onChange={async event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(!file)return;try{if(file.size>32000)throw new Error('Файл настроек слишком большой.');update(parseBatteryAppearance(JSON.parse(await file.text())));}catch(error){profile.setError(error instanceof Error?error.message:'Не удалось прочитать профиль.');}}}/></>}>
|
||||
{sensor&§ion!=='markings'&§ion!=='panels'?<BmsSettings {...sensor} section={section} open={open}/>:section==='markings'?<SettingsCard title="Маркировка ячеек" description="Номер и напряжение на заводских площадках модели. Размер меняет надпись внутри площадки.">
|
||||
<ControlRow label="Цвет маркировки"><ColorField label="Цвет маркировки" value={m.color} onChange={color=>update({...value,markings:{...m,color}})}/></ControlRow>
|
||||
{range('Размер маркировки, %',m.size,50,160,size=>update({...value,markings:{...m,size}}))}
|
||||
</SettingsCard>:<SettingsCard title="Плашки показаний" description="Общий вид верхних и нижних плашек над моделью.">
|
||||
{range('Высота плашек, px',p.height,56,160,height=>panel({height}))}
|
||||
{range('Радиус углов, px',p.radius,0,48,radius=>panel({radius}))}
|
||||
{range('Размер подписей, px',p.labelSize,10,20,labelSize=>panel({labelSize}))}
|
||||
{range('Размер значений, px',p.valueSize,12,30,valueSize=>panel({valueSize}))}
|
||||
<ControlRow label="Цвет текста"><ColorField label="Цвет текста" value={p.textColor} onChange={textColor=>panel({textColor})}/></ControlRow>
|
||||
<ControlRow label="Цвет стекла"><ColorField label="Цвет стекла" value={p.glass.tintHex} onChange={tintHex=>glass({tintHex})}/></ControlRow>
|
||||
{range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))}
|
||||
{range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))}
|
||||
</SettingsCard>}
|
||||
<Description>Сохраняется на этом компьютере для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>
|
||||
</SettingsCard>:<BatteryDesignSettings value={value} update={update}/>}
|
||||
{(section==='markings'||section==='panels')&&<Description>Сохраняется на этом компьютере для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>}
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import {useState} from 'react';
|
||||
import {ColorField,ControlRow,Description,LevelButton,RangeControl,Select,SettingsCard} from '@nodedc/ui-react';
|
||||
import {batteryIndicatorColor,type BatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
export function BatteryDesignSettings({value,update}:{value:BatteryAppearance;update:(value:BatteryAppearance)=>void}){
|
||||
const [target,setTarget]=useState<'panels'|'indicator'>('panels');
|
||||
const p=value.panels,i=value.indicator;
|
||||
const panel=(patch:Partial<typeof p>)=>update({...value,panels:{...p,...patch}});
|
||||
const glass=(patch:Partial<typeof p.glass>)=>panel({glass:{...p.glass,...patch}});
|
||||
const indicator=(patch:Partial<typeof i>)=>update({...value,indicator:{...i,...patch}});
|
||||
const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>;
|
||||
const color=(label:string,value:string,onChange:(v:string)=>void)=><ControlRow label={label}><ColorField label={label} value={value} onChange={onChange}/></ControlRow>;
|
||||
return <><Select label="Элемент дизайна" value={target} onChange={setTarget} options={[{value:'panels',label:'Плашки показаний'},{value:'indicator',label:'Индикатор в обсерватории'}]}/>
|
||||
{target==='panels'?<SettingsCard title="Плашки показаний" description="Общий вид верхних и нижних плашек над моделью.">
|
||||
{range('Высота плашек, px',p.height,56,160,height=>panel({height}))}
|
||||
{range('Радиус углов, px',p.radius,0,48,radius=>panel({radius}))}
|
||||
{range('Размер подписей, px',p.labelSize,10,20,labelSize=>panel({labelSize}))}
|
||||
{range('Размер значений, px',p.valueSize,12,30,valueSize=>panel({valueSize}))}
|
||||
{color('Цвет текста',p.textColor,textColor=>panel({textColor}))}
|
||||
{color('Цвет стекла',p.glass.tintHex,tintHex=>glass({tintHex}))}
|
||||
{range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))}
|
||||
{range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))}
|
||||
</SettingsCard>:<SettingsCard title="Индикатор в обсерватории" description="Цвет заливки и диапазоны уровня заряда для этой батареи.">
|
||||
<Select label="Режим цвета индикатора" value={i.mode} onChange={mode=>indicator({mode})} options={[{value:'ranges',label:'По уровню заряда'},{value:'mono',label:'Один цвет'}]}/>
|
||||
{i.mode==='mono'?color('Цвет индикатора',i.color,color=>indicator({color})):<>
|
||||
{range('Низкий заряд ниже, %',i.lowUntil,0,99,lowUntil=>indicator({lowUntil,middleUntil:Math.max(i.middleUntil,lowUntil+1)}))}
|
||||
{color('Низкий заряд',i.lowColor,lowColor=>indicator({lowColor}))}
|
||||
{range('Средний заряд ниже, %',i.middleUntil,i.lowUntil+1,100,middleUntil=>indicator({middleUntil}))}
|
||||
{color('Средний заряд',i.middleColor,middleColor=>indicator({middleColor}))}
|
||||
{color('Высокий заряд',i.highColor,highColor=>indicator({highColor}))}
|
||||
</>}
|
||||
<Description>Чёрный или белый текст выбирается автоматически по цвету заливки. Предпросмотр:</Description>
|
||||
<div className="observation-actions">{[10,25,80].map(soc=><LevelButton key={soc} label="Предпросмотр заряда" value={soc/100} valueText={`${soc}%`} fillColor={batteryIndicatorColor(i,soc)} disabled/>)}</div>
|
||||
</SettingsCard>}</>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type {SensorDetailProps} from '../../../../../packages/sensor-ui/src/extensions';
|
||||
import {BatteryAppearanceSettings} from './BatteryAppearanceSettings';
|
||||
import {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
|
||||
import type {BatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
@@ -6,8 +7,8 @@ import {createPortal} from 'react-dom';
|
||||
import {EditorWorkspace,Icon,IconButton,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
|
||||
import {batteryViewHeight,batteryViewHeightKey,minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
|
||||
|
||||
export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,back}:{deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){
|
||||
const full=useApplicationPanelFullscreen(),[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
|
||||
export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,back,sensor,fullscreenControl}:{sensor?:SensorDetailProps;fullscreenControl?:{fullscreen:boolean;setFullscreen:(value:boolean)=>void};deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){
|
||||
const inheritedFull=useApplicationPanelFullscreen(),full=fullscreenControl??inheritedFull,[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
|
||||
const profile=useBatteryAppearance(deviceId,settings);
|
||||
const [height,setHeight]=useState(()=>{try{return batteryViewHeight(localStorage.getItem(batteryViewHeightKey(deviceId)),window.innerHeight);}catch{return batteryViewHeight(null,window.innerHeight);}});
|
||||
const fullscreen=full?.fullscreen??false,setFullscreen=full?.setFullscreen;
|
||||
@@ -18,5 +19,5 @@ export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,ba
|
||||
};window.addEventListener('keydown',escape);return()=>window.removeEventListener('keydown',escape);},[editing,fullscreen,setFullscreen,back]);
|
||||
const commitHeight=(value:number)=>{try{localStorage.setItem(batteryViewHeightKey(deviceId),JSON.stringify({height:value}));setError('');}catch{setError('Не удалось сохранить высоту окна на этом компьютере.');}};
|
||||
const actions=<>{full&&<IconButton label={fullscreen?'Восстановить окно батареи':'Развернуть окно батареи'} onClick={()=>setFullscreen?.(!fullscreen)}><Icon name={fullscreen?'minimize':'expand'}/></IconButton>}<IconButton label={editing?'Завершить редактирование сцены':'Редактировать сцену'} aria-pressed={editing} onClick={()=>{setSettings(false);setEditing(value=>!value);}}><Icon name="edit"/></IconButton><IconButton label="Настройки батареи" aria-pressed={settings} onClick={()=>{setEditing(false);setSettings(true);}}><Icon name="settings"/></IconButton></>;
|
||||
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}{children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}<BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile}/><ToastStack items={(error||profile.error)?[{id:'battery-view-save',title:error||profile.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');}}/></>;
|
||||
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}{children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}<BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile} sensor={sensor}/><ToastStack items={(error||profile.error)?[{id:'battery-view-save',title:error||profile.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');}}/></>;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ export function ChargeGradientInspector({value,onChange}:{value:ChargeGradient;o
|
||||
<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>Материал без данных · используется, когда сохранённого заряда нет. Без свечения.</Description>
|
||||
<ControlRow label="Цвет без данных"><ColorField label="Цвет без данных" value={value.fallbackColor} onChange={fallbackColor=>patch({fallbackColor})}/></ControlRow>
|
||||
{([['fallbackMetalness','Металличность без данных'],['fallbackRoughness','Шероховатость без данных'],['fallbackReflectivity','Отражение без данных'],['fallbackOpacity','Непрозрачность без данных']] as const).map(([key,label])=><RangeControl key={key} label={label} value={value[key]} min={0} max={1} step={.01} exactValueBounds={{min:0,max:1}} onChange={v=>patch({[key]:v})}/>)}
|
||||
<Description>Ореол свечения настраивается в окружении → Bloom. При временном обрыве связи сохраняются последние цвет и яркость; движение возобновится с новыми показаниями.</Description>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import * as pc from 'playcanvas';
|
||||
import {chargePair,type ChargeGradient} from '../../../core/roverScene/chargeGradient';
|
||||
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
const surfaces=new WeakMap<pc.StandardMaterial,{known:boolean;spec:MaterialSpec;gradient:ChargeGradient}>();
|
||||
export type ChargeState={soc:number|null;fresh:boolean};
|
||||
const emission=`
|
||||
uniform vec3 chargeColorA;
|
||||
@@ -22,13 +24,24 @@ export function configureChargeMaterial(material:pc.StandardMaterial,gradient?:C
|
||||
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]];
|
||||
export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number,spec:MaterialSpec){
|
||||
const known=typeof state?.soc==='number'&&Number.isFinite(state.soc);
|
||||
const applied=surfaces.get(material);
|
||||
if(!applied||applied.known!==known||applied.spec!==spec||applied.gradient!==gradient){
|
||||
if(known)material.diffuse.set(.02,.02,.02);else material.diffuse.fromString(gradient.fallbackColor);
|
||||
material.metalness=known?spec.metalness:gradient.fallbackMetalness;
|
||||
material.gloss=known?spec.roughness:gradient.fallbackRoughness;
|
||||
material.specularityFactor=known?spec.reflectivity:gradient.fallbackReflectivity;
|
||||
material.opacity=known?spec.opacity:gradient.fallbackOpacity;
|
||||
material.blendType=material.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
|
||||
material.depthWrite=material.blendType===pc.BLEND_NONE;
|
||||
material.update();surfaces.set(material,{known,spec,gradient});
|
||||
}
|
||||
const colors=known?chargePair(gradient,state!.soc):[[0,0,0],[0,0,0]];
|
||||
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('chargeIntensity',known?gradient.intensity:0);
|
||||
material.setParameter('chargeSaturation',known?1:0);
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
|
||||
}
|
||||
}
|
||||
configureChargeMaterial(m,spec.chargeGradient);
|
||||
if(spec.chargeGradient?.enabled){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,latest.current.chargeState,0);}
|
||||
if(spec.chargeGradient?.enabled){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,latest.current.chargeState,0,spec);}
|
||||
m.update();
|
||||
}
|
||||
for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);}
|
||||
@@ -75,7 +75,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
|
||||
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);}};
|
||||
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,live.materials![id]);}};
|
||||
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();},[]);
|
||||
|
||||
Reference in New Issue
Block a user