fix: stabilize public demo and align sorter twins

Document arhipovdan.ru DNS/TLS blocker, add production smoke and GPU
perf tooling, unify twin layout, and expand visual regression coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Даня Архипов
2026-07-15 18:00:25 +00:00
parent b5985f33bb
commit 16e7930304
43 changed files with 1696 additions and 227 deletions

View File

@@ -1,16 +1,16 @@
import { TWIN_LAYOUT } from './itemMotion';
import { INDUSTRIAL_PALETTE } from '../../domain/industrialTheme';
interface Props {
stopped: boolean;
}
export default function Conveyor3D({ stopped }: Props) {
// Brighter colors for better visibility
const color = stopped ? '#7f1d1d' : '#3b5998';
const beltColor = stopped ? '#991b1b' : '#5a6577';
const accColor = stopped ? '#7f1d1d' : '#14b8a6';
const sideGuardColor = '#6b7a8f';
const rollerColor = '#8b9cb0';
const color = stopped ? INDUSTRIAL_PALETTE.fault : INDUSTRIAL_PALETTE.frame;
const beltColor = stopped ? '#991b1b' : INDUSTRIAL_PALETTE.belt;
const accColor = stopped ? INDUSTRIAL_PALETTE.fault : INDUSTRIAL_PALETTE.sensorAccent;
const sideGuardColor = INDUSTRIAL_PALETTE.metal;
const rollerColor = INDUSTRIAL_PALETTE.plastic;
return (
<group>
@@ -25,8 +25,8 @@ export default function Conveyor3D({ stopped }: Props) {
<planeGeometry args={[8.4, 0.5]} />
<meshStandardMaterial color={beltColor} roughness={0.75} />
</mesh>
{/* Conveyor side guards (borders) - brighter for visibility */}
{/* Conveyor side guards (borders) */}
<mesh position={[0, TWIN_LAYOUT.beltY + 0.06, 0.3]}>
<boxGeometry args={[8.4, 0.12, 0.04]} />
<meshStandardMaterial color={sideGuardColor} metalness={0.3} roughness={0.7} />
@@ -36,7 +36,7 @@ export default function Conveyor3D({ stopped }: Props) {
<meshStandardMaterial color={sideGuardColor} metalness={0.3} roughness={0.7} />
</mesh>
{/* Rollers (visual indication of conveyor mechanism) — spaced every 1.2m */}
{/* Rollers — spaced every 1.2m */}
{[-3.6, -2.4, -1.2, 0, 1.2].map((x) => (
<mesh key={x} position={[x, TWIN_LAYOUT.beltY - 0.08, 0]} rotation={[0, 0, Math.PI / 2]}>
<cylinderGeometry args={[0.05, 0.05, 0.52, 12]} />
@@ -44,36 +44,33 @@ export default function Conveyor3D({ stopped }: Props) {
</mesh>
))}
{/* Accumulator / buffer at end of feed conveyor — explicit raised pocket */}
{/* Accumulator / buffer at end of feed conveyor */}
<group position={[TWIN_LAYOUT.accumulatorX, TWIN_LAYOUT.beltY, 0]}>
{/* Accumulator floor (raised pocket) */}
<mesh position={[0, -0.02, 0]}>
<boxGeometry args={[1.05, 0.12, 0.82]} />
<meshStandardMaterial color={accColor} roughness={0.65} emissive={accColor} emissiveIntensity={0.15} />
</mesh>
{/* Accumulator walls — three sides (back + left + right) */}
<mesh position={[0, 0.12, 0.38]}>
<boxGeometry args={[1.05, 0.28, 0.06]} />
<meshStandardMaterial color="#14b8a6" roughness={0.7} />
<meshStandardMaterial color={INDUSTRIAL_PALETTE.sensorAccent} roughness={0.7} />
</mesh>
<mesh position={[0, 0.12, -0.38]}>
<boxGeometry args={[1.05, 0.28, 0.06]} />
<meshStandardMaterial color="#14b8a6" roughness={0.7} />
<meshStandardMaterial color={INDUSTRIAL_PALETTE.sensorAccent} roughness={0.7} />
</mesh>
<mesh position={[-0.48, 0.12, 0]}>
<boxGeometry args={[0.06, 0.28, 0.82]} />
<meshStandardMaterial color="#14b8a6" roughness={0.7} />
<meshStandardMaterial color={INDUSTRIAL_PALETTE.sensorAccent} roughness={0.7} />
</mesh>
{/* Direction arrow (subtle indication of flow) */}
<mesh position={[0.2, 0.05, 0]} rotation={[-Math.PI / 2, 0, 0]}>
<planeGeometry args={[0.3, 0.2]} />
<meshStandardMaterial
color="#5eead4"
transparent
opacity={0.4}
side={2}
<meshStandardMaterial
color={INDUSTRIAL_PALETTE.lightFill}
transparent
opacity={0.4}
side={2}
/>
</mesh>
</group>

View File

@@ -0,0 +1,143 @@
/**
* R3F performance sampler. Mount only when ?perf=1 or enabled prop.
* Exposes window.__PERF_SNAPSHOT__ (getter) and window.__PERF_RESET__.
*/
import { useFrame, useThree } from '@react-three/fiber';
import { useEffect, useRef } from 'react';
import type { WebGLRenderer } from 'three';
import {
computeFrameTimeStats,
emptyPerfSnapshot,
isHardwareAccelerated,
isPerfQueryEnabled,
roundPerfSnapshot,
type PerfSnapshot,
} from '../../domain/perfMetrics';
const MAX_SAMPLES = 600;
export interface PerfCollectorProps {
/** Force-enable even without ?perf=1 */
enabled?: boolean;
mode?: string;
shadows?: boolean;
antialias?: boolean;
}
function readRendererString(gl: WebGLRenderer): string {
try {
const ctx = gl.getContext() as WebGLRenderingContext;
const dbg = ctx.getExtension('WEBGL_debug_renderer_info');
if (dbg) {
return String(ctx.getParameter(dbg.UNMASKED_RENDERER_WEBGL) ?? 'unknown');
}
return String(ctx.getParameter(ctx.RENDERER) ?? 'unknown');
} catch {
return 'unknown';
}
}
function readHeapMb(): number {
const mem = (performance as Performance & { memory?: { usedJSHeapSize: number } }).memory;
if (!mem) return 0;
return mem.usedJSHeapSize / (1024 * 1024);
}
function PerfCollectorInner({
mode = 'demo',
shadows = false,
antialias = false,
}: Omit<PerfCollectorProps, 'enabled'>) {
const { gl } = useThree();
const frameTimes = useRef<number[]>([]);
const lastTs = useRef(0);
const meta = useRef({ mode, shadows, antialias, renderer: 'unknown' });
meta.current = { ...meta.current, mode, shadows, antialias };
const buildSnapshot = (): PerfSnapshot => {
const stats = computeFrameTimeStats(frameTimes.current);
const info = gl.info;
const renderer = meta.current.renderer || readRendererString(gl);
return roundPerfSnapshot(
emptyPerfSnapshot({
mode: meta.current.mode,
renderer,
...stats,
drawCalls: info.render.calls,
triangles: info.render.triangles,
geometries: info.memory.geometries,
textures: info.memory.textures,
programs: info.programs?.length ?? 0,
heapMb: readHeapMb(),
dpr: gl.getPixelRatio(),
shadows: meta.current.shadows,
antialias: meta.current.antialias,
hardwareAccelerated: isHardwareAccelerated(renderer),
}),
);
};
useEffect(() => {
meta.current.renderer = readRendererString(gl);
const reset = () => {
frameTimes.current = [];
lastTs.current = 0;
gl.info.reset();
};
Object.defineProperty(window, '__PERF_SNAPSHOT__', {
configurable: true,
enumerable: true,
get: () => buildSnapshot(),
});
window.__PERF_RESET__ = reset;
return () => {
reset();
try {
delete window.__PERF_SNAPSHOT__;
} catch {
/* ignore */
}
delete window.__PERF_RESET__;
};
}, [gl]);
useFrame((_state, delta) => {
// Prefer measured rAF delta; fall back to clock delta (seconds → ms)
const now = performance.now();
let dtMs: number;
if (lastTs.current > 0) {
dtMs = now - lastTs.current;
} else {
dtMs = delta * 1000;
}
lastTs.current = now;
// Ignore absurd spikes from tab backgrounding
if (dtMs <= 0 || dtMs > 500) return;
const buf = frameTimes.current;
buf.push(dtMs);
if (buf.length > MAX_SAMPLES) buf.shift();
});
return null;
}
/**
* Safe wrapper: returns null unless enabled or ?perf=1.
* Keeps demos free of sampling overhead by default.
*/
export default function PerfCollector({
enabled,
mode,
shadows,
antialias,
}: PerfCollectorProps) {
const active = enabled === true || (enabled !== false && isPerfQueryEnabled());
if (!active) return null;
return <PerfCollectorInner mode={mode} shadows={shadows} antialias={antialias} />;
}

View File

@@ -0,0 +1,91 @@
/**
* Compact FPS / GPU overlay. Visible only with ?perf=1 and outside presentation mode.
*/
import { useEffect, useState } from 'react';
import {
isPerfQueryEnabled,
type PerfSnapshot,
emptyPerfSnapshot,
} from '../../domain/perfMetrics';
const POLL_MS = 500;
export interface PerfOverlayProps {
/** Force show (still hidden in presentation mode via CSS / class check) */
enabled?: boolean;
}
export default function PerfOverlay({ enabled }: PerfOverlayProps) {
const [visible, setVisible] = useState(
() => enabled === true || (enabled !== false && isPerfQueryEnabled()),
);
const [snap, setSnap] = useState<PerfSnapshot>(() => emptyPerfSnapshot());
const [inPresentation, setInPresentation] = useState(false);
useEffect(() => {
if (enabled === false) {
setVisible(false);
return;
}
setVisible(enabled === true || isPerfQueryEnabled());
}, [enabled]);
useEffect(() => {
if (!visible) return;
const poll = () => {
const s = window.__PERF_SNAPSHOT__;
if (s) setSnap(s);
setInPresentation(!!document.querySelector('.presentation-mode'));
};
poll();
const id = window.setInterval(poll, POLL_MS);
return () => window.clearInterval(id);
}, [visible]);
if (!visible || inPresentation) return null;
const soft = !snap.hardwareAccelerated;
return (
<div
className="perf-overlay"
data-testid="perf-overlay"
aria-label="Performance metrics"
>
<div className="perf-overlay-title">PERF</div>
<div>
FPS {snap.averageFps.toFixed(0)}
<span className="perf-muted"> (min {snap.minimumFps.toFixed(0)})</span>
</div>
<div>
p95 {snap.p95FrameTimeMs.toFixed(1)}ms
<span className="perf-muted"> / p99 {snap.p99FrameTimeMs.toFixed(1)}ms</span>
</div>
<div>
draws {snap.drawCalls}
<span className="perf-muted"> · tris {snap.triangles}</span>
</div>
<div>
geo {snap.geometries}
<span className="perf-muted">
{' '}
· tex {snap.textures} · prog {snap.programs}
</span>
</div>
<div>
heap {snap.heapMb.toFixed(1)}MB
<span className="perf-muted">
{' '}
· dpr {snap.dpr} · {snap.mode}
</span>
</div>
<div className={soft ? 'perf-soft' : 'perf-hw'} title={snap.renderer}>
{soft ? 'SW' : 'GPU'} {snap.renderer.slice(0, 42)}
{snap.renderer.length > 42 ? '…' : ''}
</div>
</div>
);
}

View File

@@ -57,6 +57,7 @@ export default function SceneLabels3D({
}: Props) {
const category = currentItem?.classification.category as Category | undefined;
const cage = TWIN_LAYOUT.rollCageSize;
const beltY = TWIN_LAYOUT.beltY;
const detecting = machineState === 'DETECTING';
const atGate = machineState === 'WAITING_AT_GATE' || machineState === 'CLASSIFYING';
const routing = machineState.startsWith('ROUTE_TO_');
@@ -72,8 +73,8 @@ export default function SceneLabels3D({
{/* === CLEAN VIEW (always visible) === */}
{/* Zones A/B/C/D — always visible */}
<Badge position={[TWIN_LAYOUT.startX, 0.85, 0]} text="A" color="#38bdf8" large />
<Badge position={[TWIN_LAYOUT.zoneBX, 0.95, 0]} text="B" color={ROUTE_COLORS.B} large />
<Badge position={[TWIN_LAYOUT.startX, beltY + 0.15, 0]} text="A" color="#38bdf8" large />
<Badge position={[TWIN_LAYOUT.zoneBX, beltY + 0.25, 0]} text="B" color={ROUTE_COLORS.B} large />
<Badge
position={[TWIN_LAYOUT.gateX + 0.4, cage.y + 0.35, TWIN_LAYOUT.zoneCZ]}
text="C"
@@ -90,7 +91,7 @@ export default function SceneLabels3D({
{/* Накопитель — only in technical mode (убран из clean view) */}
{technicalLabelsEnabled && (
<Badge
position={[TWIN_LAYOUT.accumulatorX, 0.95, 0.65]}
position={[TWIN_LAYOUT.accumulatorX, beltY + 0.25, 0.65]}
text="Накопитель"
color="#5eead4"
/>
@@ -101,40 +102,40 @@ export default function SceneLabels3D({
{/* Detection: Camera/CV + Laser */}
{detecting && (
<>
<Badge position={[TWIN_LAYOUT.cameraX, 1.2, -0.55]} text="Camera CV" color="#38bdf8" />
<Badge position={[TWIN_LAYOUT.laserX, 1.2, -0.55]} text="Laser" color="#22d3ee" />
<Badge position={[TWIN_LAYOUT.cameraX, beltY + 0.5, -0.55]} text="Camera CV" color="#38bdf8" />
<Badge position={[TWIN_LAYOUT.laserX, beltY + 0.5, -0.55]} text="Laser" color="#22d3ee" />
</>
)}
{/* At gate: Stop-gate + Ultrasonic */}
{atGate && (
<>
<Badge position={[TWIN_LAYOUT.gateX, 1.15, 0]} text="Stop-gate" color="#fda4af" />
<Badge position={[TWIN_LAYOUT.gateX, beltY + 0.45, 0]} text="Stop-gate" color="#fda4af" />
</>
)}
{/* Routing: active pusher only */}
{routing && category === 'C' && (
<Badge position={[TWIN_LAYOUT.gateX - 0.1, 0.75, 0.75]} text="Pusher C" color={ROUTE_COLORS.C} />
<Badge position={[TWIN_LAYOUT.gateX - 0.1, beltY + 0.05, 0.75]} text="Pusher C" color={ROUTE_COLORS.C} />
)}
{routing && category === 'D' && (
<Badge position={[TWIN_LAYOUT.gateX - 0.1, 0.75, -0.75]} text="Pusher D" color={ROUTE_COLORS.D} />
<Badge position={[TWIN_LAYOUT.gateX - 0.1, beltY + 0.05, -0.75]} text="Pusher D" color={ROUTE_COLORS.D} />
)}
{/* Active route only (not all three routes) */}
{routing && category === 'B' && (
<Badge position={[(TWIN_LAYOUT.gateX + TWIN_LAYOUT.zoneBX) / 2, 0.55, 0]} text="→ B" color={ROUTE_COLORS.B} />
<Badge position={[(TWIN_LAYOUT.gateX + TWIN_LAYOUT.zoneBX) / 2, beltY + 0.05, 0]} text="→ B" color={ROUTE_COLORS.B} />
)}
{routing && category === 'C' && (
<Badge
position={[TWIN_LAYOUT.gateX + 0.2, 0.55, TWIN_LAYOUT.zoneCZ / 2]}
position={[TWIN_LAYOUT.gateX + 0.2, beltY + 0.05, TWIN_LAYOUT.zoneCZ / 2]}
text="→ C"
color={ROUTE_COLORS.C}
/>
)}
{routing && category === 'D' && (
<Badge
position={[TWIN_LAYOUT.gateX + 0.2, 0.55, TWIN_LAYOUT.zoneDZ / 2]}
position={[TWIN_LAYOUT.gateX + 0.2, beltY + 0.05, TWIN_LAYOUT.zoneDZ / 2]}
text="→ D"
color={ROUTE_COLORS.D}
/>
@@ -152,40 +153,40 @@ export default function SceneLabels3D({
{/* Fault / Emergency stop */}
{fault && (
<Badge position={[0, 2.5, 0]} text={machineState} color="#fb3d4e" large />
<Badge position={[0, beltY + 1.8, 0]} text={machineState} color="#fb3d4e" large />
)}
{/* === TECHNICAL LABELS (opt-in) === */}
{technicalLabelsEnabled && !cleanView && (
<>
{/* Always show all sensors when technical mode is on */}
{!detecting && <Badge position={[TWIN_LAYOUT.cameraX, 1.2, -0.55]} text="Camera CV" color="#38bdf8" />}
{!detecting && <Badge position={[TWIN_LAYOUT.laserX, 1.2, -0.55]} text="Laser" color="#22d3ee" />}
<Badge position={[TWIN_LAYOUT.ultrasonicX, 1.05, -0.55]} text="Ultrasonic" color="#67e8f9" />
{!detecting && <Badge position={[TWIN_LAYOUT.cameraX, beltY + 0.5, -0.55]} text="Camera CV" color="#38bdf8" />}
{!detecting && <Badge position={[TWIN_LAYOUT.laserX, beltY + 0.5, -0.55]} text="Laser" color="#22d3ee" />}
<Badge position={[TWIN_LAYOUT.ultrasonicX, beltY + 0.35, -0.55]} text="Ultrasonic" color="#67e8f9" />
{/* Always show all actuators */}
{!atGate && <Badge position={[TWIN_LAYOUT.gateX, 1.15, 0]} text="Stop-gate" color="#fda4af" />}
{!atGate && <Badge position={[TWIN_LAYOUT.gateX, beltY + 0.45, 0]} text="Stop-gate" color="#fda4af" />}
{!(routing && category === 'C') && (
<Badge position={[TWIN_LAYOUT.gateX - 0.1, 0.75, 0.75]} text="Pusher C" color={ROUTE_COLORS.C} />
<Badge position={[TWIN_LAYOUT.gateX - 0.1, beltY + 0.05, 0.75]} text="Pusher C" color={ROUTE_COLORS.C} />
)}
{!(routing && category === 'D') && (
<Badge position={[TWIN_LAYOUT.gateX - 0.1, 0.75, -0.75]} text="Pusher D" color={ROUTE_COLORS.D} />
<Badge position={[TWIN_LAYOUT.gateX - 0.1, beltY + 0.05, -0.75]} text="Pusher D" color={ROUTE_COLORS.D} />
)}
{/* All route beams */}
{!(routing && category === 'B') && (
<Badge position={[(TWIN_LAYOUT.gateX + TWIN_LAYOUT.zoneBX) / 2, 0.55, 0]} text="Route B" color={ROUTE_COLORS.B} />
<Badge position={[(TWIN_LAYOUT.gateX + TWIN_LAYOUT.zoneBX) / 2, beltY + 0.05, 0]} text="Route B" color={ROUTE_COLORS.B} />
)}
{!(routing && category === 'C') && (
<Badge
position={[TWIN_LAYOUT.gateX + 0.2, 0.55, TWIN_LAYOUT.zoneCZ / 2]}
position={[TWIN_LAYOUT.gateX + 0.2, beltY + 0.05, TWIN_LAYOUT.zoneCZ / 2]}
text="Route C"
color={ROUTE_COLORS.C}
/>
)}
{!(routing && category === 'D') && (
<Badge
position={[TWIN_LAYOUT.gateX + 0.2, 0.55, TWIN_LAYOUT.zoneDZ / 2]}
position={[TWIN_LAYOUT.gateX + 0.2, beltY + 0.05, TWIN_LAYOUT.zoneDZ / 2]}
text="Route D"
color={ROUTE_COLORS.D}
/>
@@ -193,7 +194,7 @@ export default function SceneLabels3D({
{/* Conveyor info */}
<Badge
position={[-3.2, 1.55, 1.4]}
position={[-3.2, beltY + 0.85, 1.4]}
text={`Conveyor ${conveyorTargetMps.toFixed(2)} m/s · min ${DIMENSION_LIMITS.min.width}×${DIMENSION_LIMITS.min.depth}×${DIMENSION_LIMITS.min.height} mm`}
color="#91a4b8"
/>

View File

@@ -50,12 +50,14 @@ function SensorPole({
export default function SensorRig3D({ sensors, machineState }: Props) {
const detecting = machineState === 'DETECTING';
const poleH = TWIN_LAYOUT.beltY + 0.45;
const ultrasonicH = TWIN_LAYOUT.beltY + 0.3;
return (
<group>
<SensorPole x={TWIN_LAYOUT.cameraX} active={sensors.camera.active || detecting} labelColor="#38bdf8" />
<SensorPole x={TWIN_LAYOUT.laserX} active={sensors.laser.active} labelColor="#22d3ee" />
<SensorPole x={TWIN_LAYOUT.ultrasonicX} active={sensors.ultrasound.active} labelColor="#67e8f9" height={0.75} />
<SensorPole x={TWIN_LAYOUT.cameraX} active={sensors.camera.active || detecting} labelColor="#38bdf8" height={poleH} />
<SensorPole x={TWIN_LAYOUT.laserX} active={sensors.laser.active} labelColor="#22d3ee" height={poleH} />
<SensorPole x={TWIN_LAYOUT.ultrasonicX} active={sensors.ultrasound.active} labelColor="#67e8f9" height={ultrasonicH} />
{/* Detection beam - more visible */}
{detecting ? (

View File

@@ -1,6 +1,6 @@
import { Canvas, useFrame } from '@react-three/fiber';
import { Grid, OrbitControls } from '@react-three/drei';
import { Suspense, useRef, useState } from 'react';
import { Suspense, useMemo, useRef, useState } from 'react';
import type { SimulationState } from '../../domain/types';
import Conveyor3D from './Conveyor3D';
import SensorRig3D from './SensorRig3D';
@@ -13,6 +13,8 @@ import { PHYSICS_ENGINE_ENABLED } from './itemMotion';
import { NOMINAL_CONVEYOR_SPEED_MPS } from '../../domain/simulation';
import { DIMENSION_LIMITS } from '../../domain/classifier';
import { INDUSTRIAL_PALETTE } from '../../domain/industrialTheme';
import PerfCollector from './PerfCollector';
import PerfOverlay from './PerfOverlay';
export interface SorterDigitalTwinProps {
simulation: SimulationState;
@@ -81,19 +83,19 @@ function TwinScene({
args={[16, 16]}
cellSize={0.5}
cellThickness={0.7}
cellColor="#2a4a6a"
cellColor={INDUSTRIAL_PALETTE.metalDark}
sectionSize={2}
sectionThickness={1.2}
sectionColor="#3a6080"
sectionColor={INDUSTRIAL_PALETTE.frame}
fadeDistance={16}
infiniteGrid={false}
position={[0, 0.001, 0]}
/>
{/* Floor with better contrast */}
{/* Floor — shared industrial tokens (dark engineering projection) */}
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0, 0]}>
<planeGeometry args={[14, 10]} />
<meshStandardMaterial color="#0f1a2a" />
<meshStandardMaterial color={INDUSTRIAL_PALETTE.backgroundDark} />
</mesh>
<Conveyor3D stopped={stopped} />
@@ -118,7 +120,7 @@ function TwinScene({
{stopped ? (
<mesh position={[0, 1.2, 0]}>
<planeGeometry args={[6, 1.2]} />
<meshStandardMaterial color="#7f1d1d" transparent opacity={0.35} />
<meshStandardMaterial color={INDUSTRIAL_PALETTE.fault} transparent opacity={0.35} />
</mesh>
) : null}
@@ -128,7 +130,7 @@ function TwinScene({
maxPolarAngle={Math.PI / 2.1}
minDistance={2.5}
maxDistance={10}
target={[0.6, 0.4, 0]}
target={[0.6, 0.55, 0]}
/>
<FpsMeter onFps={onFps} />
</>
@@ -144,6 +146,12 @@ export default function SorterDigitalTwin({
onContextLost,
}: SorterDigitalTwinProps) {
const [fps, setFps] = useState(0);
const perfEnabled = useMemo(
() =>
typeof window !== 'undefined' &&
new URLSearchParams(window.location.search).get('perf') === '1',
[],
);
const category = simulation.currentItem?.classification.category;
const command = simulation.machineState.startsWith('ROUTE_TO_')
? simulation.machineState
@@ -192,9 +200,18 @@ export default function SorterDigitalTwin({
cleanView={cleanView}
onFps={setFps}
/>
{perfEnabled ? (
<PerfCollector
enabled
mode={simplified ? 'low' : 'demo'}
shadows={false}
antialias={!simplified}
/>
) : null}
</Suspense>
</Canvas>
</div>
{perfEnabled ? <PerfOverlay enabled /> : null}
</div>
);
}

View File

@@ -55,6 +55,8 @@ import {
CAGE_FLOOR_Y,
CONVEYOR_SPEED_MPS,
} from '../../domain/physicalLayout';
import PerfCollector from './PerfCollector';
import PerfOverlay from './PerfOverlay';
export interface SorterDigitalTwinContinuousProps {
playback: ContinuousPlaybackState;
@@ -1452,6 +1454,10 @@ export default function SorterDigitalTwinContinuous({
const mode = qualityMode ?? detectQualityMode(typeof window !== 'undefined' ? window.innerWidth : 1200);
const quality = getQualitySettings(mode);
const useSimplified = simplified || mode === 'low';
const antialias = quality.antialias && !useSimplified;
const perfEnabled =
typeof window !== 'undefined' &&
new URLSearchParams(window.location.search).get('perf') === '1';
return (
<div className="digital-twin-wrap continuous-twin">
<div className="digital-twin-canvas continuous-canvas">
@@ -1459,7 +1465,7 @@ export default function SorterDigitalTwinContinuous({
camera={{ position: [4.5, 3.5, 5.0], fov: 45 }}
dpr={[1, quality.dprMax]}
shadows={quality.shadows}
gl={{ antialias: quality.antialias && !useSimplified, powerPreference: 'high-performance' }}
gl={{ antialias, powerPreference: 'high-performance' }}
onCreated={({ gl }) => {
const canvas = gl.domElement;
const handleLost = (event: Event) => {
@@ -1477,9 +1483,18 @@ export default function SorterDigitalTwinContinuous({
autoCameraEnabled={autoCameraEnabled}
viewportType={viewportType}
/>
{perfEnabled ? (
<PerfCollector
enabled
mode={mode}
shadows={quality.shadows}
antialias={antialias}
/>
) : null}
</Suspense>
</Canvas>
</div>
{perfEnabled ? <PerfOverlay enabled /> : null}
</div>
);
}

View File

@@ -119,21 +119,22 @@ function RollCage({
export default function SortingZones3D({ activeCategory, activeRoute }: Props) {
const active = activeRoute ?? activeCategory;
const cage = TWIN_LAYOUT.rollCageSize;
const beltY = TWIN_LAYOUT.beltY;
return (
<group>
{/* Zone A feed — always visible cyan */}
{/* Zone A feed — pad under belt (aligned to shared belt height) */}
<ZoneBox
position={[TWIN_LAYOUT.startX, 0.22, 0]}
size={[1.0, 0.44, 1.0]}
position={[TWIN_LAYOUT.startX, beltY / 2, 0]}
size={[1.0, beltY, 1.0]}
color="#38bdf8"
active={active === undefined}
/>
{/* Zone B main sorter — green, straight */}
<ZoneBox
position={[TWIN_LAYOUT.zoneBX, 0.28, 0]}
size={[1.2, 0.56, 1.2]}
position={[TWIN_LAYOUT.zoneBX, beltY / 2, 0]}
size={[1.2, beltY, 1.2]}
color={ROUTE_COLORS.B}
active={active === 'B'}
/>

View File

@@ -1,25 +1,19 @@
import type { Category, MachineState, SimulationState } from '../../domain/types';
import {
CATEGORY_COLORS,
DETAILS_TWIN_LAYOUT,
} from '../../domain/layout/sharedLayout';
/** Compact digital-twin coordinates (1 unit ≈ 1 m, scaled layout). */
export const TWIN_LAYOUT = {
beltY: 0.35,
startX: -4.2,
endX: 4.2,
cameraX: -1.2,
laserX: -0.2,
ultrasonicX: 1.0,
gateX: 1.6,
accumulatorX: 1.4,
zoneBX: 3.8,
zoneCZ: 2.4,
zoneDZ: -2.4,
rollCageSize: { x: 1.2, y: 0.8, z: 0.8 },
} as const;
/**
* Details-twin layout — derived from shared physical constants
* (belt height, zone X/Z, sensors, gate) so `/details` matches continuous scale.
*/
export const TWIN_LAYOUT = DETAILS_TWIN_LAYOUT;
export const ROUTE_COLORS: Record<Category, string> = {
B: '#4ade80',
C: '#f59e0b',
D: '#c084fc',
B: CATEGORY_COLORS.B,
C: CATEGORY_COLORS.C,
D: CATEGORY_COLORS.D,
};
export function progressForState(state: MachineState, elapsedMs: number): number {

View File

@@ -0,0 +1,18 @@
export {
SHARED_CONVEYOR,
SHARED_ZONES,
SHARED_SENSORS,
SHARED_GATE,
CLASS_ROUTE_DIRECTIONS,
DETAILS_TWIN_LAYOUT,
BELT_TOP_Y,
CONVEYOR_HEIGHT_M,
CONVEYOR_LENGTH_M,
CONVEYOR_SPEED_MPS,
CONVEYOR_WIDTH_M,
MAIN_BELT_WIDTH_M,
ROLL_CAGE,
ZONES,
CATEGORY_COLORS,
INDUSTRIAL_PALETTE,
} from './sharedLayout';

View File

@@ -0,0 +1,99 @@
/**
* Shared twin geometry — single source of truth for continuous (`/`) and details (`/details`).
*
* Continuous twin consumes `physicalLayout` / `conveyorNetwork` directly.
* Details twin derives `TWIN_LAYOUT` from these constants so belt height and
* zone/sensor X positions stay aligned without rewriting both scenes.
*/
import {
BELT_TOP_Y,
CONVEYOR_HEIGHT_M,
CONVEYOR_LENGTH_M,
CONVEYOR_SPEED_MPS,
CONVEYOR_WIDTH_M,
MAIN_BELT_WIDTH_M,
ROLL_CAGE,
ZONES,
} from '../physicalLayout';
import { CATEGORY_COLORS, INDUSTRIAL_PALETTE } from '../industrialTheme';
import type { Category } from '../types';
// Re-export palette + physical primitives used by both twins
export {
BELT_TOP_Y,
CONVEYOR_HEIGHT_M,
CONVEYOR_LENGTH_M,
CONVEYOR_SPEED_MPS,
CONVEYOR_WIDTH_M,
MAIN_BELT_WIDTH_M,
ROLL_CAGE,
ZONES,
};
export { CATEGORY_COLORS, INDUSTRIAL_PALETTE };
/** Conveyor dims shared across both twins. */
export const SHARED_CONVEYOR = {
widthM: CONVEYOR_WIDTH_M,
heightM: CONVEYOR_HEIGHT_M,
lengthM: CONVEYOR_LENGTH_M,
speedMps: CONVEYOR_SPEED_MPS,
beltTopY: BELT_TOP_Y,
beltWidthM: MAIN_BELT_WIDTH_M,
} as const;
/** Zone A/B/C/D positions (meters). */
export const SHARED_ZONES = {
A: { x: ZONES.A.x, z: ZONES.A.z, label: ZONES.A.label },
B: { x: ZONES.B.x, z: ZONES.B.z, label: ZONES.B.label },
C: { x: ZONES.C.x, z: ZONES.C.z, label: ZONES.C.label },
D: { x: ZONES.D.x, z: ZONES.D.z, label: ZONES.D.label },
} as const;
/** Sensor stations along the main belt. */
export const SHARED_SENSORS = {
cameraX: ZONES.CAMERA.x,
laserX: ZONES.LASER.x,
/** Details twin only — mid-span between laser and gate. */
ultrasonicX: (ZONES.LASER.x + ZONES.GATE.x) / 2,
} as const;
/** Stop-gate / diverter junction. */
export const SHARED_GATE = {
x: ZONES.GATE.x,
z: ZONES.GATE.z,
} as const;
/** Route exit directions after the gate (engineering + presentation). */
export const CLASS_ROUTE_DIRECTIONS: Record<
Category,
{ axis: 'x' | 'z'; sign: 1 | -1; color: string }
> = {
B: { axis: 'x', sign: 1, color: CATEGORY_COLORS.B },
C: { axis: 'z', sign: 1, color: CATEGORY_COLORS.C },
D: { axis: 'z', sign: -1, color: CATEGORY_COLORS.D },
};
/**
* Details-twin layout derived from physical constants.
* Keyframes still use progress ratios; only absolute meters change.
*/
export const DETAILS_TWIN_LAYOUT = {
beltY: BELT_TOP_Y,
startX: ZONES.A.x,
endX: ZONES.B.x + 0.2,
cameraX: SHARED_SENSORS.cameraX,
laserX: SHARED_SENSORS.laserX,
ultrasonicX: SHARED_SENSORS.ultrasonicX,
gateX: SHARED_GATE.x,
/** Buffer pocket just upstream of the gate. */
accumulatorX: SHARED_GATE.x - 0.1,
zoneBX: ZONES.B.x,
zoneCZ: ZONES.C.z,
zoneDZ: ZONES.D.z,
rollCageSize: {
x: ROLL_CAGE.width,
y: ROLL_CAGE.height,
z: ROLL_CAGE.depth,
},
} as const;

View File

@@ -0,0 +1,87 @@
import { describe, it, expect } from 'vitest';
import {
percentile,
computeFrameTimeStats,
isSoftwareRenderer,
isHardwareAccelerated,
isPerfQueryEnabled,
emptyPerfSnapshot,
} from './perfMetrics';
describe('perfMetrics', () => {
describe('percentile', () => {
it('returns 0 for empty input', () => {
expect(percentile([], 0.95)).toBe(0);
});
it('returns the sole value', () => {
expect(percentile([16], 0.99)).toBe(16);
});
it('interpolates p95 on a sorted series', () => {
const values = [10, 20, 30, 40, 50];
// idx = 0.95 * 4 = 3.8 → 40 * 0.2 + 50 * 0.8 = 48
expect(percentile(values, 0.95)).toBeCloseTo(48, 5);
});
it('returns endpoints at 0 and 1', () => {
const values = [1, 2, 3, 4];
expect(percentile(values, 0)).toBe(1);
expect(percentile(values, 1)).toBe(4);
});
});
describe('computeFrameTimeStats', () => {
it('derives fps and long-frame counts', () => {
const frames = [16, 16, 16, 40, 16, 60];
const s = computeFrameTimeStats(frames);
expect(s.longFramesOver33).toBe(2);
expect(s.longFramesOver50).toBe(1);
expect(s.averageFps).toBeGreaterThan(0);
expect(s.minimumFps).toBeCloseTo(1000 / 60, 5);
expect(s.p95FrameTimeMs).toBeGreaterThanOrEqual(s.p99FrameTimeMs > 0 ? 0 : 0);
});
});
describe('renderer detection', () => {
it('flags SwiftShader and llvmpipe as software', () => {
expect(isSoftwareRenderer('Google SwiftShader')).toBe(true);
expect(isSoftwareRenderer('llvmpipe (LLVM 15.0.7)')).toBe(true);
expect(isHardwareAccelerated('ANGLE (NVIDIA GeForce RTX 3080)')).toBe(true);
});
});
describe('isPerfQueryEnabled', () => {
it('reads perf=1 from a search string', () => {
expect(isPerfQueryEnabled('?perf=1')).toBe(true);
expect(isPerfQueryEnabled('?foo=1')).toBe(false);
expect(isPerfQueryEnabled('')).toBe(false);
});
});
describe('emptyPerfSnapshot', () => {
it('matches the expected JSON shape defaults', () => {
const s = emptyPerfSnapshot();
expect(s).toMatchObject({
mode: 'demo',
renderer: 'unknown',
averageFps: 0,
minimumFps: 0,
p95FrameTimeMs: 0,
p99FrameTimeMs: 0,
longFramesOver33: 0,
longFramesOver50: 0,
drawCalls: 0,
triangles: 0,
geometries: 0,
textures: 0,
programs: 0,
heapMb: 0,
dpr: 1,
shadows: false,
antialias: false,
hardwareAccelerated: true,
});
});
});
});

130
src/domain/perfMetrics.ts Normal file
View File

@@ -0,0 +1,130 @@
/**
* Pure helpers and types for Three.js performance snapshots.
* Used by PerfCollector (runtime) and unit tests — no R3F/DOM side effects here.
*/
export interface PerfSnapshot {
mode: string;
renderer: string;
averageFps: number;
minimumFps: number;
p95FrameTimeMs: number;
p99FrameTimeMs: number;
longFramesOver33: number;
longFramesOver50: number;
drawCalls: number;
triangles: number;
geometries: number;
textures: number;
programs: number;
heapMb: number;
dpr: number;
shadows: boolean;
antialias: boolean;
hardwareAccelerated: boolean;
}
export interface FrameTimeStats {
averageFps: number;
minimumFps: number;
p95FrameTimeMs: number;
p99FrameTimeMs: number;
longFramesOver33: number;
longFramesOver50: number;
}
/** Linear-interpolation percentile on a sorted ascending array. `p` in [0, 1]. */
export function percentile(sortedAsc: number[], p: number): number {
if (sortedAsc.length === 0) return 0;
if (sortedAsc.length === 1) return sortedAsc[0];
const clamped = Math.min(1, Math.max(0, p));
const idx = clamped * (sortedAsc.length - 1);
const lo = Math.floor(idx);
const hi = Math.ceil(idx);
if (lo === hi) return sortedAsc[lo];
const t = idx - lo;
return sortedAsc[lo] * (1 - t) + sortedAsc[hi] * t;
}
export function computeFrameTimeStats(frameTimesMs: number[]): FrameTimeStats {
if (frameTimesMs.length === 0) {
return {
averageFps: 0,
minimumFps: 0,
p95FrameTimeMs: 0,
p99FrameTimeMs: 0,
longFramesOver33: 0,
longFramesOver50: 0,
};
}
const sorted = [...frameTimesMs].sort((a, b) => a - b);
const avgMs = frameTimesMs.reduce((a, b) => a + b, 0) / frameTimesMs.length;
const maxMs = sorted[sorted.length - 1];
return {
averageFps: avgMs > 0 ? 1000 / avgMs : 0,
minimumFps: maxMs > 0 ? 1000 / maxMs : 0,
p95FrameTimeMs: percentile(sorted, 0.95),
p99FrameTimeMs: percentile(sorted, 0.99),
longFramesOver33: frameTimesMs.filter((t) => t > 33).length,
longFramesOver50: frameTimesMs.filter((t) => t > 50).length,
};
}
/** Detect software / CPU renderers (SwiftShader, llvmpipe, etc.). */
export function isSoftwareRenderer(renderer: string): boolean {
return /swiftshader|llvmpipe|softpipe|software|mesa offscreen|microsoft basic render/i.test(
renderer,
);
}
export function isHardwareAccelerated(renderer: string): boolean {
if (!renderer || renderer === 'unknown') return false;
return !isSoftwareRenderer(renderer);
}
export function emptyPerfSnapshot(partial?: Partial<PerfSnapshot>): PerfSnapshot {
return {
mode: 'demo',
renderer: 'unknown',
averageFps: 0,
minimumFps: 0,
p95FrameTimeMs: 0,
p99FrameTimeMs: 0,
longFramesOver33: 0,
longFramesOver50: 0,
drawCalls: 0,
triangles: 0,
geometries: 0,
textures: 0,
programs: 0,
heapMb: 0,
dpr: 1,
shadows: false,
antialias: false,
hardwareAccelerated: true,
...partial,
};
}
/** True when `?perf=1` is present in the current URL. */
export function isPerfQueryEnabled(search?: string): boolean {
const q =
search ??
(typeof window !== 'undefined' ? window.location.search : '');
return new URLSearchParams(q).get('perf') === '1';
}
export function roundPerfSnapshot(snap: PerfSnapshot, digits = 2): PerfSnapshot {
const r = (n: number) => Number(n.toFixed(digits));
return {
...snap,
averageFps: r(snap.averageFps),
minimumFps: r(snap.minimumFps),
p95FrameTimeMs: r(snap.p95FrameTimeMs),
p99FrameTimeMs: r(snap.p99FrameTimeMs),
heapMb: r(snap.heapMb),
dpr: r(snap.dpr),
};
}

View File

@@ -217,6 +217,7 @@ export const CAMERA_RIG = {
// =========================================================
// Derived constants for legacy compatibility
// Details twin layout is derived in domain/layout/sharedLayout.ts
// =========================================================
export const CONVEYOR_POSITIONS = {
spawnX: ZONES.A.x,

View File

@@ -0,0 +1,62 @@
/**
* Route consistency — playlist expectedCategory ↔ classifier ↔ playback ↔ pose.
*/
import { describe, it, expect } from 'vitest';
import { DEMO_PLAYLIST } from './demoPlaylist';
import { classifyItem } from './classifier';
import { resolveItem } from '../data/resolveItem';
import {
CASE_PHASES,
createPlaybackState,
seekToCase,
startPlayback,
} from './continuousPlayback';
import { CATEGORY_COLORS } from './industrialTheme';
import { getPhysicalItemPose } from './physicalItemMotion';
import type { Category } from './types';
/** Mid-routing elapsed time for normal CASE_PHASES timeline. */
function routingElapsedMs(): number {
let elapsed = 0;
for (const p of CASE_PHASES) {
if (p.phase === 'routing') {
return elapsed + p.durationMs / 2;
}
elapsed += p.durationMs;
}
throw new Error('CASE_PHASES missing routing phase');
}
describe('routeConsistency', () => {
const nonFaultCases = DEMO_PLAYLIST.filter((c) => !c.faultType);
it('every non-fault playlist case stays consistent across classifier, playback, colors, and pose', () => {
const midRouting = routingElapsedMs();
for (const playlistCase of nonFaultCases) {
const item = resolveItem(playlistCase.itemId);
const classification = classifyItem(item);
expect(classification.category).toBe(playlistCase.expectedCategory);
const caseIndex = DEMO_PLAYLIST.findIndex((c) => c.id === playlistCase.id);
const playback = seekToCase(startPlayback(createPlaybackState()), caseIndex);
expect(playback.targetCategory).toBe(playlistCase.expectedCategory);
expect(playback.classification?.category).toBe(playlistCase.expectedCategory);
const category = playlistCase.expectedCategory as Category;
expect(CATEGORY_COLORS[category]).toBeDefined();
expect(typeof CATEGORY_COLORS[category]).toBe('string');
const pose = getPhysicalItemPose({
caseId: playlistCase.id,
dimensionsMm: item.dimensionsMm,
targetCategory: classification.category,
elapsedMs: midRouting,
});
expect(pose.phase).toBe('routing');
expect(pose.activeRoute).toBe(category);
}
});
});

View File

@@ -107,7 +107,13 @@ export default function MainPage({
}, [playback.status, onPlay, onPause, onStop, onSeekNext, onSeekPrev, onSeekCase]);
const show3D = prefer3DByDefault(width, webgl && !contextLost);
const qualityMode = detectQualityMode(width);
const qualityOverride = useMemo(() => {
if (typeof window === 'undefined') return undefined;
const q = new URLSearchParams(window.location.search).get('quality');
if (q === 'low' || q === 'medium' || q === 'high' || q === 'demo') return q;
return undefined;
}, []);
const qualityMode = qualityOverride ?? detectQualityMode(width);
const simplified = width < 900 || qualityMode === 'low';
const viewportType: ViewportType = getViewportType(width);

View File

@@ -515,6 +515,7 @@ button:disabled {
}
.digital-twin-wrap {
position: relative;
display: flex;
flex-direction: column;
gap: 10px;
@@ -2976,6 +2977,35 @@ button:disabled {
white-space: normal;
}
/* Perf instrumentation overlay (?perf=1 only) */
.perf-overlay {
position: absolute;
top: 10px;
left: 10px;
z-index: 40;
min-width: 180px;
max-width: 280px;
padding: 8px 10px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
line-height: 1.35;
color: #e8f0f7;
background: rgba(8, 14, 22, 0.78);
border: 1px solid rgba(120, 160, 200, 0.35);
pointer-events: none;
user-select: none;
}
.perf-overlay-title {
font-weight: 700;
letter-spacing: 0.06em;
margin-bottom: 4px;
color: #9fd0ff;
}
.perf-overlay .perf-muted { color: rgba(200, 220, 240, 0.55); }
.perf-overlay .perf-soft { color: #f0b4a0; margin-top: 4px; }
.perf-overlay .perf-hw { color: #a8e0b8; margin-top: 4px; }
.main-page.presentation-mode .perf-overlay { display: none; }
.main-page.presentation-mode .main-hud,
.main-page.presentation-mode .main-progress,
.main-page.presentation-mode .auto-camera-toggle,

13
src/vite-env.d.ts vendored
View File

@@ -1 +1,14 @@
/// <reference types="vite/client" />
import type { PerfSnapshot } from './domain/perfMetrics';
declare global {
interface Window {
/** Live Three.js perf snapshot (getter) — only when ?perf=1 / PerfCollector mounted */
__PERF_SNAPSHOT__?: PerfSnapshot;
/** Clear frame-time samples and gl.info counters */
__PERF_RESET__?: () => void;
}
}
export {};