chore: consolidate documentation and clean repository

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Даня Архипов
2026-08-01 18:29:15 +00:00
parent 4413f01ce4
commit 13ce16bedc
596 changed files with 501 additions and 45214 deletions

View File

@@ -1,26 +0,0 @@
interface CPriorityExplanationProps {
onShowCPriority: () => void;
}
export default function CPriorityExplanation({ onShowCPriority }: CPriorityExplanationProps) {
return (
<section className="c-priority-section" aria-labelledby="c-priority-title">
<div className="c-priority-card">
<div className="c-priority-icon" aria-hidden="true">
C
</div>
<div className="c-priority-content">
<h3 id="c-priority-title">Почему C имеет приоритет?</h3>
<p>
Если товар одновременно негабаритный и имеет круг в сечении, он направляется в C.
Сначала проверяются габариты, и только если они проходят — форма.
Это предотвращает попадание негабаритных объектов в основной сортировщик.
</p>
<button type="button" className="btn-primary" onClick={onShowCPriority}>
Показать C-priority
</button>
</div>
</div>
</section>
);
}

View File

@@ -1,48 +0,0 @@
import { DIMENSION_LIMITS, OFFICIAL_RULE_LABELS } from '../domain/classifier';
import type { SimulationState } from '../domain/types';
function Verdict({ pass, skipped = false }: { pass?: boolean; skipped?: boolean }) {
if (skipped) {
return <span className="verdict skipped">SKIPPED</span>;
}
if (pass === undefined) {
return <span className="verdict pending">PENDING</span>;
}
return <span className={pass ? 'verdict pass' : 'verdict fail'}>{pass ? 'PASS' : 'FAIL'}</span>;
}
export default function ClassificationPanel({ simulation }: { simulation: SimulationState }) {
const current = simulation.currentItem;
const result = current?.classification;
const item = current?.item;
const dimensions = item?.dimensionsMm;
const isOversizedAndRound = Boolean(result && !result.dimensionsPass && !result.roundnessPass);
const lowConfidence = Boolean(item && item.confidence < 0.65);
return (
<section className="panel compact-panel classification-panel">
<div className="panel-heading">
<p className="eyebrow">Classification rules</p>
<h2>Decision proof</h2>
</div>
<div className="rule-stack">
<div className="rule-card">
<div><strong>Step 1: Dimensions check</strong><Verdict pass={result?.dimensionsPass} /></div>
<p>Allowed: {OFFICIAL_RULE_LABELS.boundsSummary} (exclusive official bounds).</p>
<p>Actual: {dimensions ? `${dimensions.width} x ${dimensions.depth} x ${dimensions.height} mm` : 'waiting for item'}</p>
</div>
<div className="rule-card">
<div><strong>Step 2: Roundness check</strong><Verdict pass={result?.roundnessPass} skipped={result ? !result.dimensionsPass : false} /></div>
<p>Roundness for D: {OFFICIAL_RULE_LABELS.roundnessDisplay} (threshold {DIMENSION_LIMITS.roundnessThreshold}).</p>
<p>Actual roundness: {item ? item.roundness.toFixed(2) : 'waiting for item'}</p>
</div>
<div className="rule-card">
<div><strong>Step 3: Category decision</strong><span className={result ? `decision-badge category-${result.category}` : 'decision-badge'}>{result ? result.category : '-'}</span></div>
<p>{result ? result.reason : 'Run a scenario to classify the current item.'}</p>
{isOversizedAndRound ? <p className="warning-note">Приоритет: C, потому что габариты проверяются первыми.</p> : null}
{lowConfidence ? <p className="warning-note">CV confidence низкий, решение подтверждено rule-based fallback.</p> : null}
</div>
</div>
</section>
);
}

View File

@@ -1,129 +0,0 @@
import type { ScenarioId } from '../domain/types';
import { OFFICIAL_RULE_LABELS } from '../domain/classifier';
interface CriteriaCard {
id: string;
title: string;
evidence: string;
status: 'covered' | 'demo';
linkedScenario: ScenarioId;
linkedLabel: string;
}
const PRODUCT_CRITERIA: CriteriaCard[] = [
{
id: 'classification',
title: 'Классификация',
evidence: 'Rule-based дерево решений выдаёт категорию B/C/D для каждого SKU.',
status: 'covered',
linkedScenario: 'normal_flow',
linkedLabel: 'Обычный товар',
},
{
id: 'dimensions',
title: 'Габариты',
evidence: 'Проверка min/max размеров до анализа формы.',
status: 'covered',
linkedScenario: 'oversized_item',
linkedLabel: 'Негабарит',
},
{
id: 'round-section',
title: 'Круг в сечении',
evidence: `${OFFICIAL_RULE_LABELS.roundnessDisplay} направляет товар в зону D.`,
status: 'covered',
linkedScenario: 'round_object',
linkedLabel: 'Круглый объект',
},
{
id: 'rule-priority',
title: 'Приоритет правил',
evidence: 'Сначала габариты (C), затем форма (D). Негабарит + круглый → только C.',
status: 'covered',
linkedScenario: 'c_priority',
linkedLabel: 'C-priority',
},
{
id: 'routing',
title: 'Маршрутизация B/C/D',
evidence: 'Категория превращается в команду ROUTE_TO_* и физический маршрут.',
status: 'covered',
linkedScenario: 'normal_flow',
linkedLabel: 'Обычный товар',
},
{
id: 'cycle-time',
title: 'Cycle time',
evidence: 'Метрики показывают длительность цикла и throughput.',
status: 'covered',
linkedScenario: 'close_items',
linkedLabel: 'Очередь товаров',
},
{
id: 'faults',
title: 'Нештатные ситуации',
evidence: 'Jam переводит систему в FAULT и останавливает конвейер.',
status: 'demo',
linkedScenario: 'jam',
linkedLabel: 'Застревание',
},
{
id: 'safety',
title: 'Безопасность',
evidence: 'Emergency stop замораживает линию до Reset.',
status: 'demo',
linkedScenario: 'emergency_stop',
linkedLabel: 'Аварийная остановка',
},
{
id: 'reproducibility',
title: 'Воспроизводимость',
evidence: 'Сценарии, тесты и docs позволяют повторить демо жюри.',
status: 'covered',
linkedScenario: 'low_confidence',
linkedLabel: 'Низкая уверенность CV',
},
];
interface Props {
onLinkedScenario?: (id: ScenarioId) => void;
}
export default function CriteriaCards({ onLinkedScenario }: Props) {
return (
<section className="criteria-cards-section" id="criteria" aria-labelledby="criteria-title">
<div className="section-header">
<h2 id="criteria-title">Критерии OZON</h2>
<p>Каждый критерий хакатона закрыт сценарием, симуляцией и тестами.</p>
</div>
<div className="criteria-grid">
{PRODUCT_CRITERIA.map((criterion) => (
<article key={criterion.id} className="criteria-card">
<div className="criteria-card-header">
<h3>{criterion.title}</h3>
<span className={`status-badge status-${criterion.status}`}>
{criterion.status === 'covered' ? 'Covered' : 'Demo'}
</span>
</div>
<p className="criteria-evidence">{criterion.evidence}</p>
<div className="criteria-footer">
<span>Сценарий:</span>
{onLinkedScenario ? (
<button
type="button"
className="criteria-link"
onClick={() => onLinkedScenario(criterion.linkedScenario)}
>
{criterion.linkedLabel}
</button>
) : (
<strong>{criterion.linkedLabel}</strong>
)}
</div>
</article>
))}
</div>
</section>
);
}

View File

@@ -1,41 +0,0 @@
import type { SimulationState } from '../domain/types';
export default function CurrentItemPanel({ simulation }: { simulation: SimulationState }) {
const current = simulation.currentItem;
const camera = simulation.sensors.camera;
const laser = simulation.sensors.laser;
return (
<section className="panel compact-panel">
<div className="panel-heading">
<p className="eyebrow">Current item</p>
<h2>{current?.item.id ?? 'No active item'}</h2>
</div>
{current ? (
<>
<div className="kv-grid">
<span>Name</span><strong>{current.item.name}</strong>
<span>Dimensions</span><strong>{current.item.dimensionsMm.width} x {current.item.dimensionsMm.depth} x {current.item.dimensionsMm.height} mm</strong>
<span>Shape</span><strong>{current.item.shape}</strong>
<span>Roundness</span><strong>{current.item.roundness.toFixed(2)}</strong>
<span>Confidence</span><strong>{Math.round(current.item.confidence * 100)}%</strong>
<span>Category</span><strong className={`category-${current.classification.category}`}>{current.classification.category} / {current.classification.label}</strong>
<span>Reason</span><strong>{current.classification.reason}</strong>
</div>
<div className="pseudo-cv-block">
<h3>Pseudo-CV / sensor packet</h3>
<div className="kv-grid compact-kv">
<span>bbox</span><strong>{camera.bbox ? `${camera.bbox.width} x ${camera.bbox.height} mm` : 'pending'}</strong>
<span>confidence</span><strong>{camera.confidence ? `${Math.round(camera.confidence * 100)}%` : 'pending'}</strong>
<span>cv latency</span><strong>{camera.cvLatencyMs} ms</strong>
<span>detected dimensions</span><strong>{current.item.dimensionsMm.width} x {current.item.dimensionsMm.depth} x {current.item.dimensionsMm.height} mm</strong>
<span>measured height</span><strong>{laser.measuredHeightMm ?? current.item.dimensionsMm.height} mm</strong>
</div>
</div>
</>
) : (
<p className="muted">Start or step the simulation to feed an item into zone A.</p>
)}
</section>
);
}

View File

@@ -1,130 +0,0 @@
import { OFFICIAL_RULE_LABELS } from '../domain/classifier';
import { NOMINAL_CONVEYOR_SPEED_MPS } from '../domain/simulation';
import type { SimulationState } from '../domain/types';
export default function CurrentProofCard({ simulation }: { simulation: SimulationState }) {
const current = simulation.currentItem;
const result = current?.classification;
const item = current?.item;
const dimensions = item?.dimensionsMm;
const lowConfidence = Boolean(item && item.confidence < 0.65);
const stopped = simulation.machineState === 'FAULT' || simulation.machineState === 'EMERGENCY_STOP';
const command = simulation.machineState.startsWith('ROUTE_TO_')
? simulation.machineState
: result
? `ROUTE_TO_${result.category}`
: 'WAITING';
const isCPriority = Boolean(result && !result.dimensionsPass && !result.roundnessPass);
if (!current) {
return (
<div className="proof-card proof-card-empty">
<div className="proof-card-inner">
<p className="eyebrow">Ожидание цикла</p>
<h3>Готово к демонстрации</h3>
<p>Нажмите Start demo — товар пройдёт Detection → Classification → Command → Routing.</p>
<p className="proof-limits">
Limits: {OFFICIAL_RULE_LABELS.boundsSummary} · {OFFICIAL_RULE_LABELS.roundnessDisplay} ·
conveyor {NOMINAL_CONVEYOR_SPEED_MPS.toFixed(2)} m/s
</p>
</div>
</div>
);
}
return (
<div className={`proof-card ${stopped ? 'proof-card-stopped' : ''}`}>
<div className="proof-card-header">
<p className="eyebrow">Результат классификации</p>
<h3>{item?.name}</h3>
</div>
<div className="proof-summary">
<div className="summary-row">
<span className="summary-label">Category:</span>
<strong className={`category-${result?.category ?? 'default'}`}>{result?.category ?? '—'}</strong>
</div>
<div className="summary-row">
<span className="summary-label">Command:</span>
<strong>{command}</strong>
</div>
<div className="summary-row">
<span className="summary-label">Target:</span>
<strong>{result?.category ? `Zone ${result.category}` : '—'}</strong>
</div>
<div className="summary-row">
<span className="summary-label">Why:</span>
<em>
{isCPriority
? `dimensions failed, so C has priority even though K = ${item?.roundness.toFixed(2)}`
: result?.dimensionsPass === false
? 'dimensions failed (oversized or undersized)'
: result?.roundnessPass === false
? `dimensions pass, but K = ${item?.roundness.toFixed(2)} > 0.8`
: 'dimensions pass and round section is not detected'}
</em>
</div>
</div>
<div className="proof-grid">
<div className="proof-item">
<span className="proof-label">Dimensions</span>
<strong className={result?.dimensionsPass === false ? 'fail-text' : 'pass-text'}>
{result?.dimensionsPass ? 'PASS' : 'FAIL'}
</strong>
<em>
{dimensions?.width}×{dimensions?.depth}×{dimensions?.height} мм
</em>
</div>
<div className="proof-item">
<span className="proof-label">Roundness K</span>
<strong className={result?.roundnessPass === false && result?.dimensionsPass ? 'fail-text' : 'pass-text'}>
{item?.roundness.toFixed(2)}
</strong>
<em>{result?.roundnessPass ? 'PASS' : 'DETECTED (>0.8)'}</em>
</div>
<div className="proof-item">
<span className="proof-label">Category</span>
<strong className={`category-${result?.category ?? 'default'}`}>{result?.category ?? '—'}</strong>
</div>
<div className="proof-item">
<span className="proof-label">Target zone</span>
<strong>{result?.category ? `Zone ${result.category}` : '—'}</strong>
</div>
<div className="proof-item proof-item-wide">
<span className="proof-label">Command</span>
<strong>{command}</strong>
</div>
</div>
<div className="proof-details">
<div className="detail-row">
<span>Official limits</span>
<strong>
{OFFICIAL_RULE_LABELS.minDisplay} · {OFFICIAL_RULE_LABELS.maxDisplay}
</strong>
</div>
<div className="detail-row">
<span>Conveyor target</span>
<strong>{NOMINAL_CONVEYOR_SPEED_MPS.toFixed(2)} m/s</strong>
</div>
</div>
<div className="proof-reason">
<strong>Причина решения</strong>
<p>{result?.reason}</p>
{isCPriority ? (
<p className="warning-note">C-priority: негабарит + круглый → только C (габариты важнее формы)</p>
) : null}
{lowConfidence ? (
<p className="warning-note">Низкая уверенность измерения — rule-based fallback, класс только B/C/D</p>
) : null}
{simulation.machineState === 'FAULT' ? <p className="error-note">FAULT: конвейер остановлен</p> : null}
{simulation.machineState === 'EMERGENCY_STOP' ? (
<p className="error-note">EMERGENCY_STOP: аварийная остановка</p>
) : null}
{simulation.metrics.queueLength > 1 ? <p className="warning-note">Очередь товаров</p> : null}
</div>
</div>
);
}

View File

@@ -1,115 +0,0 @@
import { forwardRef, lazy, Suspense, useImperativeHandle, useState } from 'react';
import StateMachinePanel from './StateMachinePanel';
import TimelinePanel from './TimelinePanel';
import PidPanel from './PidPanel';
import EventLog from './EventLog';
import MetricsPanel from './MetricsPanel';
import SensorPanel from './SensorPanel';
import ScenarioPanel from './ScenarioPanel';
import OzonCriteriaPanel from './OzonCriteriaPanel';
import SorterScene from './SorterScene';
import { DEMO_STEPS } from '../data/demoSteps';
import { SCENARIOS } from '../data/scenarios';
import type { ScenarioId, SimulationState } from '../domain/types';
const ThreeCapabilityCheck = lazy(() => import('./ThreeD/ThreeCapabilityCheck'));
export interface EngineeringDetailsHandle {
open: () => void;
}
interface Props {
simulation: SimulationState;
onScenarioChange: (id: ScenarioId) => void;
}
const EngineeringDetails = forwardRef<EngineeringDetailsHandle, Props>(
function EngineeringDetails({ simulation, onScenarioChange }, ref) {
const [isOpen, setIsOpen] = useState(false);
const currentStep =
DEMO_STEPS.find((step) => step.scenarioId === simulation.scenario.id) ?? DEMO_STEPS[0];
useImperativeHandle(ref, () => ({
open: () => {
setIsOpen(true);
requestAnimationFrame(() => {
document.getElementById('engineering')?.scrollIntoView({ behavior: 'smooth' });
});
},
}));
return (
<section className="engineering-details-section" id="engineering" aria-labelledby="engineering-title">
<div className="engineering-toggle">
<div>
<p className="section-eyebrow">For experts</p>
<h2 id="engineering-title">Engineering Details</h2>
<p className="engineering-lead">
Полные технические панели: state machine, sensors, PID, timeline, event log и критерии.
</p>
</div>
<button
type="button"
className="btn-secondary"
onClick={() => setIsOpen((value) => !value)}
aria-expanded={isOpen}
aria-controls="engineering-content"
>
{isOpen ? 'Свернуть' : 'Открыть инженерный режим'}
</button>
</div>
{isOpen ? (
<div className="engineering-content" id="engineering-content">
<div className="eng-panel eng-panel-wide">
<SorterScene simulation={simulation} variant="full" />
</div>
<div className="eng-panel eng-panel-wide">
<Suspense fallback={<p className="three-loading">Loading 3D capability check…</p>}>
<ThreeCapabilityCheck />
</Suspense>
</div>
<div className="engineering-grid">
<div className="eng-panel">
<StateMachinePanel currentState={simulation.machineState} />
</div>
<div className="eng-panel">
<MetricsPanel metrics={simulation.metrics} />
</div>
<div className="eng-panel">
<SensorPanel simulation={simulation} />
</div>
<div className="eng-panel">
<TimelinePanel simulation={simulation} />
</div>
<div className="eng-panel">
<PidPanel
pid={simulation.pid}
metrics={simulation.metrics}
status={simulation.systemStatus}
/>
</div>
<div className="eng-panel">
<ScenarioPanel
scenarios={SCENARIOS}
activeScenarioId={simulation.scenario.id}
onScenarioChange={onScenarioChange}
/>
</div>
<div className="eng-panel eng-panel-wide">
<EventLog events={simulation.events} />
</div>
<div className="eng-panel eng-panel-wide">
<OzonCriteriaPanel currentStep={currentStep} />
</div>
</div>
</div>
) : null}
</section>
);
},
);
export default EngineeringDetails;

View File

@@ -1,67 +0,0 @@
import { useMemo, useState } from 'react';
import type { EventLogEntry } from '../domain/types';
type LogFilter = 'all' | 'sensor' | 'classification' | 'actuator' | 'warning' | 'error' | 'success';
const filters: LogFilter[] = ['all', 'sensor', 'classification', 'actuator', 'warning', 'error', 'success'];
function formatTime(ms: number): string {
return `t+${(ms / 1000).toFixed(1)}s`;
}
function matchesFilter(entry: EventLogEntry, filter: LogFilter): boolean {
if (filter === 'all') {
return true;
}
if (filter === 'error' || filter === 'success' || filter === 'warning') {
return entry.status === filter;
}
return entry.type === filter;
}
export default function EventLog({ events }: { events: EventLogEntry[] }) {
const [filter, setFilter] = useState<LogFilter>('all');
const [copied, setCopied] = useState(false);
const visibleEvents = useMemo(() => events.filter((entry) => matchesFilter(entry, filter)), [events, filter]);
const copyJson = async () => {
await navigator.clipboard.writeText(JSON.stringify(events, null, 2));
setCopied(true);
window.setTimeout(() => setCopied(false), 1200);
};
return (
<section className="panel event-panel">
<div className="panel-heading">
<div>
<p className="eyebrow">Event log</p>
<h2>Cycle trace</h2>
</div>
<button className="small-button" onClick={() => void copyJson()}>{copied ? 'Copied' : 'Copy JSON'}</button>
</div>
<div className="log-filters">
{filters.map((item) => (
<button key={item} className={filter === item ? 'active' : ''} onClick={() => setFilter(item)}>{item}</button>
))}
</div>
<div className="event-table" role="table">
<div className="event-row event-head" role="row">
<span>time</span><span>item</span><span>state</span><span>type</span><span>command/category</span><span>message</span><span>status</span>
</div>
{visibleEvents.length === 0 ? (
<div className="empty-log">No events for this filter.</div>
) : visibleEvents.map((entry) => (
<div className={`event-row ${entry.status}`} role="row" key={entry.id}>
<span>{formatTime(entry.timestampMs)}</span>
<span>{entry.itemId ?? '-'}</span>
<span>{entry.state ?? '-'}</span>
<span>{entry.type}</span>
<span>{entry.command ?? entry.category ?? '-'}</span>
<span>{entry.message}</span>
<span>{entry.status}</span>
</div>
))}
</div>
</section>
);
}

View File

@@ -1,51 +0,0 @@
import type { SimulationState } from '../domain/types';
interface HeaderProps {
simulation: SimulationState;
onReset: () => void;
onOpenDemo: () => void;
onOpenScenarios: () => void;
onOpenEngineering: () => void;
}
export default function Header({
simulation,
onReset,
onOpenDemo,
onOpenScenarios,
onOpenEngineering,
}: HeaderProps) {
return (
<header className="site-header">
<div className="header-logo">
<span className="logo-icon" aria-hidden="true">
O
</span>
<div className="logo-text">
<span className="logo-title">OZON Tech Sorter</span>
<span className="logo-subtitle">Product Demo</span>
</div>
</div>
<nav className="header-nav" aria-label="Основная навигация">
<button type="button" className="nav-link" onClick={onOpenDemo}>
Демо
</button>
<button type="button" className="nav-link" onClick={onOpenScenarios}>
Сценарии
</button>
<button type="button" className="nav-link" onClick={onOpenEngineering}>
Инженерный режим
</button>
<button type="button" className="nav-link nav-reset" onClick={onReset}>
Reset
</button>
</nav>
<div className="header-status-compact" aria-live="polite">
<span className={`status-dot ${simulation.systemStatus.toLowerCase()}`} aria-hidden="true" />
<span>{simulation.systemStatus}</span>
</div>
</header>
);
}

View File

@@ -1,74 +0,0 @@
import { OFFICIAL_RULE_LABELS } from '../domain/classifier';
interface HeroSectionProps {
onStartDemo: () => void;
onShowScenarios: () => void;
onOpenEngineering: () => void;
}
export default function HeroSection({
onStartDemo,
onShowScenarios,
onOpenEngineering,
}: HeroSectionProps) {
return (
<section className="hero-section" aria-labelledby="hero-title">
<div className="hero-content">
<p className="hero-eyebrow">OZON Tech · Product Demo</p>
<h1 id="hero-title" className="hero-title">
Интеллектуальная система предварительной сортировки товаров
</h1>
<p className="hero-subtitle">
Цифровой стенд показывает полный цикл: тестовые измерения → rule-based классификация B/C/D → команда ROUTE_TO_* → маршрутизация в digital twin.
</p>
<div className="hero-badges" aria-label="Параметры системы">
<span className="hero-badge">Конвейер 1 м/с</span>
<span className="hero-badge">{OFFICIAL_RULE_LABELS.minDisplay}</span>
<span className="hero-badge">{OFFICIAL_RULE_LABELS.maxDisplay}</span>
<span className="hero-badge">{OFFICIAL_RULE_LABELS.roundnessDisplay} → D</span>
<span className="hero-badge">C priority</span>
</div>
<div className="hero-actions">
<button type="button" className="btn-primary" onClick={onStartDemo}>
Запустить демо
</button>
<button type="button" className="btn-secondary" onClick={onShowScenarios}>
Показать сценарии
</button>
<button type="button" className="btn-secondary" onClick={onOpenEngineering}>
Инженерный режим
</button>
</div>
</div>
<div className="hero-visual" aria-hidden="true">
<div className="hero-chain">
<div className="chain-step">
<div className="chain-icon">1</div>
<span>Detection</span>
</div>
<div className="chain-arrow" />
<div className="chain-step">
<div className="chain-icon">2</div>
<span>Classification</span>
</div>
<div className="chain-arrow" />
<div className="chain-step">
<div className="chain-icon">3</div>
<span>Command</span>
</div>
<div className="chain-arrow" />
<div className="chain-step">
<div className="chain-icon">4</div>
<span>Routing</span>
</div>
</div>
<p className="hero-chain-caption">
Detection → Classification → ROUTE_TO_* → Actuator → B/C/D
</p>
</div>
</section>
);
}

View File

@@ -1,36 +0,0 @@
import type { Metrics } from '../domain/types';
const metricLabels: Array<[keyof Metrics, string, string]> = [
['processedCount', 'Processed', 'items'],
['successCount', 'Success', 'items'],
['errorCount', 'Errors', 'items'],
['avgCycleTimeMs', 'Avg cycle', 'ms'],
['throughputItemsPerMin', 'Throughput', 'items/min'],
['cvLatencyMs', 'CV latency', 'ms'],
['actuatorLatencyMs', 'Actuator latency', 'ms'],
['queueLength', 'Queue length', 'items'],
['queueDelayMs', 'Queue delay', 'ms'],
['conveyorSpeedMps', 'Conveyor speed', 'm/s'],
['pidTargetSpeedMps', 'PID target', 'm/s'],
['pidActualSpeedMps', 'PID actual', 'm/s'],
];
export default function MetricsPanel({ metrics }: { metrics: Metrics }) {
return (
<section className="panel metrics-panel">
<div className="panel-heading">
<p className="eyebrow">Metrics</p>
<h2>Line telemetry</h2>
</div>
<div className="metric-grid">
{metricLabels.map(([key, label, unit]) => (
<div className="metric-card" key={key}>
<span>{label}</span>
<strong>{metrics[key]}</strong>
<em>{unit}</em>
</div>
))}
</div>
</section>
);
}

View File

@@ -1,45 +0,0 @@
import { useMemo, useState } from 'react';
import { OZON_CRITERIA } from '../data/criteria';
import type { CriteriaStatus, DemoStep } from '../domain/types';
type CriteriaFilter = 'all' | CriteriaStatus;
const filters: CriteriaFilter[] = ['all', 'covered', 'partially covered', 'demo step available'];
export default function OzonCriteriaPanel({ currentStep }: { currentStep: DemoStep }) {
const [filter, setFilter] = useState<CriteriaFilter>('all');
const visibleCriteria = useMemo(
() => OZON_CRITERIA.filter((criterion) => filter === 'all' || criterion.status === filter),
[filter],
);
const related = new Set(currentStep.relatedCriteria);
return (
<section className="panel criteria-panel">
<div className="panel-heading">
<div>
<p className="eyebrow">OZON criteria coverage</p>
<h2>Evidence checklist</h2>
</div>
<span className="criteria-count">{visibleCriteria.length}/{OZON_CRITERIA.length}</span>
</div>
<div className="criteria-filters">
{filters.map((item) => (
<button key={item} className={filter === item ? 'active' : ''} onClick={() => setFilter(item)}>{item}</button>
))}
</div>
<div className="criteria-list">
{visibleCriteria.map((criterion) => (
<article key={criterion.id} className={related.has(criterion.id) ? 'criterion-card related' : 'criterion-card'}>
<div>
<strong>{criterion.title}</strong>
<span className={`criterion-status status-${criterion.status.replaceAll(' ', '-')}`}>{criterion.status}</span>
</div>
<p>{criterion.evidence}</p>
<em>{criterion.relatedScenarioIds.join(', ')} / {criterion.relatedDoc}</em>
</article>
))}
</div>
</section>
);
}

View File

@@ -1,58 +0,0 @@
import type { Metrics, PidState, SystemStatus } from '../domain/types';
interface PidPanelProps {
pid: PidState;
metrics: Metrics;
status: SystemStatus;
}
function pidState(pid: PidState, status: SystemStatus): string {
if (status === 'EMERGENCY_STOP') {
return 'emergency stop';
}
if (status === 'FAULT') {
return 'stopped by fault';
}
if (Math.abs(pid.pidError) <= 0.03 && pid.actualSpeedMps > 0) {
return 'stable';
}
return 'stabilizing';
}
function sparkline(history: number[]): string {
const values = history.length > 1 ? history : [0, 0];
const max = Math.max(...values, 0.5);
return values
.map((value, index) => {
const x = (index / Math.max(values.length - 1, 1)) * 220;
const y = 58 - (value / max) * 48;
return `${x.toFixed(1)},${y.toFixed(1)}`;
})
.join(' ');
}
export default function PidPanel({ pid, status }: PidPanelProps) {
const fill = Math.min((pid.actualSpeedMps / Math.max(pid.targetSpeedMps, 0.01)) * 100, 100);
const state = pidState(pid, status);
return (
<section className="panel pid-panel">
<div className="panel-heading">
<p className="eyebrow">Conveyor control loop</p>
<h2>{state}</h2>
</div>
<div className="pid-bars">
<div><span>target speed</span><strong>{pid.targetSpeedMps.toFixed(2)} m/s</strong></div>
<div><span>actual speed</span><strong>{pid.actualSpeedMps.toFixed(2)} m/s</strong></div>
<div><span>error</span><strong>{pid.pidError.toFixed(2)}</strong></div>
<div><span>correction</span><strong>{pid.correction.toFixed(2)}</strong></div>
</div>
<div className="speed-track"><div style={{ width: `${fill}%` }} /></div>
<svg className="pid-sparkline" viewBox="0 0 220 64" role="img" aria-label="PID speed history">
<path d="M0 58 H220" />
<polyline points={sparkline(pid.speedHistoryMps)} />
</svg>
<p className="muted">PID shown as simplified control-loop simulation for conveyor speed stabilization.</p>
</section>
);
}

View File

@@ -1,232 +0,0 @@
import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
import CurrentProofCard from './CurrentProofCard';
import ThreeFallback from './ThreeD/ThreeFallback';
import ThreeErrorBoundary from './ThreeD/ThreeErrorBoundary';
import { prefer3DByDefault, useWebGLSupport } from './ThreeD/useWebGL';
import type { SimulationState } from '../domain/types';
import type { DemoDirectorState } from '../domain/demoDirector';
import type { ContinuousPlaybackState } from '../domain/continuousPlayback';
// Stage 2B §7/§20: /details reuses the SAME CAD-derived machine assembly and
// live playback as the main page — no second procedural conveyor.
const SorterDigitalTwinContinuous = lazy(() => import('./ThreeD/SorterDigitalTwinContinuous'));
type ViewMode = '3d' | '2d';
interface Props {
playback: ContinuousPlaybackState;
simulation: SimulationState;
demoStepTitle: string;
demoDirector: DemoDirectorState;
onStartDemo: () => void;
onNext: () => void;
onReset: () => void;
onOpenEngineering: () => void;
onStartAutoDemo: () => void;
onToggleAutoDemo: () => void;
onStopAutoDemo: () => void;
}
export default function ProductDemoSection({
playback,
simulation,
demoStepTitle,
demoDirector,
onStartDemo,
onNext,
onReset,
onOpenEngineering,
onStartAutoDemo,
onToggleAutoDemo,
onStopAutoDemo,
}: Props) {
const webgl = useWebGLSupport();
const [width, setWidth] = useState(() => (typeof window === 'undefined' ? 1200 : window.innerWidth));
const [viewMode, setViewMode] = useState<ViewMode>('3d');
const [contextLost, setContextLost] = useState(false);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);
useEffect(() => {
setViewMode(prefer3DByDefault(width, webgl && !contextLost) ? '3d' : '2d');
}, [webgl, width, contextLost]);
const item = simulation.currentItem;
const category = item?.classification.category;
const command = simulation.machineState.startsWith('ROUTE_TO_')
? simulation.machineState
: item?.classification
? `ROUTE_TO_${item.classification.category}`
: '—';
const fallbackReason = useMemo(() => {
if (!webgl || contextLost) return 'webgl' as const;
if (width < 640) return 'mobile' as const;
return 'user' as const;
}, [webgl, contextLost, width]);
const show3D = viewMode === '3d' && webgl && !contextLost;
const simplified = width < 900;
return (
<section className="product-demo-section" id="demo" aria-labelledby="demo-title">
<div className="demo-header">
<div>
<p className="section-eyebrow">Live product demo</p>
<h2 id="demo-title">Главное демо</h2>
<p className="demo-lead">
3D digital twin показывает физическую маршрутизацию: A → конвейер → CV → накопитель → gate → B/C/D.
Справа — товар, категория, причина и команда ROUTE_TO_*.
</p>
</div>
<div className="demo-status">
<span>Шаг:</span>
<strong>{demoStepTitle}</strong>
<span className={`status-dot ${simulation.systemStatus.toLowerCase()}`} aria-hidden="true" />
<span className="demo-status-text">{simulation.systemStatus}</span>
</div>
</div>
<div className="view-mode-toggle" role="group" aria-label="Режим сцены">
<button
type="button"
className={show3D ? 'btn-primary' : 'btn-secondary'}
onClick={() => {
setContextLost(false);
setViewMode('3d');
}}
disabled={!webgl}
>
3D Digital Twin
</button>
<button
type="button"
className={!show3D ? 'btn-primary' : 'btn-secondary'}
onClick={() => setViewMode('2d')}
>
2D fallback
</button>
</div>
<div className="demo-layout">
<div className="demo-scene-column">
<p className="demo-mobile-hint">
Товар проходит камеру, накопитель и gate, затем уходит в зону B, C или D.
</p>
<div className="demo-scene-container demo-scene-3d">
{show3D ? (
<ThreeErrorBoundary
onError={(error) => {
console.error('3D Canvas failed:', error);
setContextLost(true);
setViewMode('2d');
}}
onUse2D={() => {
setContextLost(true);
setViewMode('2d');
}}
>
<Suspense fallback={<div className="three-loading">Загрузка 3D digital twin…</div>}>
<SorterDigitalTwinContinuous
playback={playback}
simplified={simplified}
autoCameraEnabled
onContextLost={() => {
setContextLost(true);
setViewMode('2d');
}}
/>
</Suspense>
</ThreeErrorBoundary>
) : (
<ThreeFallback simulation={simulation} reason={fallbackReason} />
)}
</div>
</div>
<aside className="demo-result-column" aria-label="Результат классификации">
<CurrentProofCard simulation={simulation} />
<div className="demo-result-summary">
<div className="summary-item">
<span>Товар</span>
<strong>{item?.item.name ?? 'Ожидание'}</strong>
</div>
<div className="summary-item">
<span>Dimensions</span>
<strong className={item?.classification.dimensionsPass === false ? 'fail-text' : 'pass-text'}>
{item ? (item.classification.dimensionsPass ? 'PASS' : 'FAIL') : '—'}
</strong>
</div>
<div className="summary-item">
<span>Roundness K</span>
<strong>{item ? item.item.roundness.toFixed(2) : '—'}</strong>
</div>
<div className="summary-item">
<span>Category</span>
<strong className={category ? `category-${category}` : ''}>{category ?? '—'}</strong>
</div>
<div className="summary-item">
<span>Command</span>
<strong>{command}</strong>
</div>
<div className="summary-item">
<span>Target zone</span>
<strong>{category ? `Zone ${category}` : '—'}</strong>
</div>
</div>
<div className="demo-controls">
{/* Auto Demo Controls */}
{!demoDirector.isAutoDemoRunning ? (
<button type="button" className="btn-primary" onClick={onStartAutoDemo}>
🎬 Запустить автодемо
</button>
) : (
<>
<button type="button" className="btn-primary" onClick={onToggleAutoDemo}>
{demoDirector.paused ? '▶ Продолжить' : '⏸ Пауза'}
</button>
<button type="button" className="btn-secondary" onClick={onStopAutoDemo}>
⏹ Остановить
</button>
</>
)}
{/* Manual Controls (secondary when auto demo not running) */}
{!demoDirector.isAutoDemoRunning && (
<>
<button type="button" className="btn-secondary" onClick={onStartDemo}>
Start demo (manual)
</button>
<button type="button" className="btn-secondary" onClick={onNext}>
Next step
</button>
</>
)}
<button type="button" className="btn-secondary" onClick={onReset}>
Reset
</button>
<button type="button" className="btn-secondary" onClick={onOpenEngineering}>
Engineering details
</button>
</div>
{/* Auto Demo Status */}
{demoDirector.isAutoDemoRunning && (
<div className="auto-demo-status">
<span>Auto Demo: </span>
<strong>{demoDirector.currentStep.replace(/_/g, ' ')}</strong>
<span> ({demoDirector.paused ? 'Paused' : 'Running'})</span>
</div>
)}
</aside>
</div>
</section>
);
}

View File

@@ -1,109 +0,0 @@
import type { Scenario, ScenarioId } from '../domain/types';
interface Props {
scenarios: Scenario[];
activeScenarioId: ScenarioId;
onScenarioChange: (id: ScenarioId) => void;
}
const SCENARIO_UI: Record<
ScenarioId,
{ title: string; summary: string; badge: string; badgeTone: 'b' | 'c' | 'd' | 'mixed' | 'fault' }
> = {
normal_flow: {
title: 'Обычный товар',
summary: 'Стандартный поток с маршрутизацией в B, C и D.',
badge: 'B / C / D',
badgeTone: 'mixed',
},
oversized_item: {
title: 'Негабарит',
summary: 'Габариты превышают лимит — приоритет зоны C.',
badge: 'Зона C',
badgeTone: 'c',
},
round_object: {
title: 'Круглый объект',
summary: 'Габариты проходят, но круглое сечение ведёт в D.',
badge: 'Зона D',
badgeTone: 'd',
},
c_priority: {
title: 'C-priority',
summary: 'Негабарит + круглый: габариты важнее формы, маршрут только в C.',
badge: 'C priority',
badgeTone: 'c',
},
boundary_dimensions: {
title: 'Пограничные размеры',
summary: 'Проверка строгих min/max границ габаритов.',
badge: 'B / C',
badgeTone: 'mixed',
},
low_confidence: {
title: 'Низкая уверенность CV',
summary: 'Предупреждение CV и rule-based fallback.',
badge: 'Fallback',
badgeTone: 'b',
},
close_items: {
title: 'Очередь товаров',
summary: 'Близкие товары обрабатываются по одному циклу.',
badge: 'Queue',
badgeTone: 'mixed',
},
jam: {
title: 'Застревание',
summary: 'Jam у gate переводит линию в FAULT.',
badge: 'FAULT',
badgeTone: 'fault',
},
emergency_stop: {
title: 'Аварийная остановка',
summary: 'EMERGENCY_STOP останавливает движение до Reset.',
badge: 'E-STOP',
badgeTone: 'fault',
},
};
export default function ScenarioCards({ scenarios, activeScenarioId, onScenarioChange }: Props) {
return (
<section className="scenario-cards-section" id="scenarios" aria-labelledby="scenarios-title">
<div className="section-header">
<h2 id="scenarios-title">Сценарии</h2>
<p>Выберите кейс жюри: обычный поток, негабарит, круглое сечение, очередь или авария.</p>
</div>
<div className="scenario-grid">
{scenarios.map((scenario) => {
const ui = SCENARIO_UI[scenario.id];
const active = scenario.id === activeScenarioId;
return (
<article
key={scenario.id}
className={`scenario-card ${active ? 'active' : ''}`}
>
<div className="scenario-card-header">
<h3>{ui.title}</h3>
<span className={`result-badge tone-${ui.badgeTone}`}>{ui.badge}</span>
</div>
<p className="scenario-desc">{ui.summary}</p>
<p className="scenario-expected">
<span>Ожидаемый результат</span>
<strong>{scenario.expectedCategorySummary}</strong>
</p>
<button
type="button"
className={active ? 'btn-primary' : 'btn-secondary'}
onClick={() => onScenarioChange(scenario.id)}
>
{active ? 'Выбран' : 'Показать'}
</button>
</article>
);
})}
</div>
</section>
);
}

View File

@@ -1,33 +0,0 @@
import type { Scenario, ScenarioId } from '../domain/types';
interface ScenarioPanelProps {
scenarios: Scenario[];
activeScenarioId: ScenarioId;
onScenarioChange: (scenarioId: ScenarioId) => void;
}
export default function ScenarioPanel({ scenarios, activeScenarioId, onScenarioChange }: ScenarioPanelProps) {
return (
<section className="panel scenario-panel">
<div className="panel-heading">
<p className="eyebrow">Scenario panel</p>
<h2>Jury test cases</h2>
</div>
<div className="scenario-buttons">
{scenarios.map((scenario) => (
<button
key={scenario.id}
className={scenario.id === activeScenarioId ? 'active' : ''}
onClick={() => onScenarioChange(scenario.id)}
>
<strong>{scenario.name}</strong>
<span>{scenario.description}</span>
<em>Goal: {scenario.goal}</em>
<em>Expected: {scenario.expectedCategorySummary}</em>
<em>Shows: {scenario.demonstrates}</em>
</button>
))}
</div>
</section>
);
}

View File

@@ -1,37 +0,0 @@
import type { SensorState, SimulationState } from '../domain/types';
function SensorRow({ sensor }: { sensor: SensorState }) {
return (
<div className={sensor.active ? 'sensor-row active' : 'sensor-row'}>
<div>
<strong>{sensor.label}</strong>
<span>{sensor.lastValue}</span>
</div>
<div className="sensor-meta">
<span>{sensor.latencyMs} ms</span>
<span>t+{(sensor.lastEventTimestampMs / 1000).toFixed(1)}s</span>
</div>
</div>
);
}
export default function SensorPanel({ simulation }: { simulation: SimulationState }) {
return (
<section className="panel compact-panel">
<div className="panel-heading">
<p className="eyebrow">Sensors and actuators</p>
<h2>Live I/O</h2>
</div>
<div className="sensor-stack">
<SensorRow sensor={simulation.sensors.camera} />
<SensorRow sensor={simulation.sensors.laser} />
<SensorRow sensor={simulation.sensors.ultrasound} />
</div>
<div className="actuator-grid">
<div><span>Stop-gate</span><strong>{simulation.gate.open ? 'open' : 'closed'}</strong></div>
<div><span>Pusher C</span><strong>{simulation.actuators.pusherC}</strong></div>
<div><span>Pusher D</span><strong>{simulation.actuators.pusherD}</strong></div>
</div>
</section>
);
}

View File

@@ -1,35 +0,0 @@
import type { MachineState } from '../domain/types';
const states: MachineState[] = [
'IDLE',
'MOVING_TO_CAMERA',
'DETECTING',
'MOVING_TO_GATE',
'WAITING_AT_GATE',
'CLASSIFYING',
'ROUTE_TO_B',
'ROUTE_TO_C',
'ROUTE_TO_D',
'RETURN_HOME',
'FAULT',
'EMERGENCY_STOP',
];
export default function StateMachinePanel({ currentState }: { currentState: MachineState }) {
return (
<section className="panel compact-panel">
<div className="panel-heading">
<p className="eyebrow">State machine</p>
<h2>{currentState}</h2>
</div>
<div className="state-list">
{states.map((state) => (
<div key={state} className={state === currentState ? 'state active' : 'state'}>
<span />
{state}
</div>
))}
</div>
</section>
);
}

View File

@@ -1,76 +0,0 @@
import type { MachineState, SimulationState } from '../domain/types';
type StepKey = 'detection' | 'classification' | 'decision' | 'command' | 'routing';
type StepStatus = 'active' | 'completed' | 'pending';
const STEPS: Array<{ key: StepKey; number: number; label: string; description: string }> = [
{ key: 'detection', number: 1, label: 'Detection', description: 'Камера и датчики снимают габариты' },
{ key: 'classification', number: 2, label: 'Classification', description: 'Правила проверяют размеры и форму' },
{ key: 'decision', number: 3, label: 'Decision', description: 'Система выбирает категорию B/C/D' },
{ key: 'command', number: 4, label: 'Command', description: 'Формируется команда ROUTE_TO_*' },
{ key: 'routing', number: 5, label: 'Routing', description: 'Товар уходит в целевую зону' },
];
function activeStep(state: MachineState): StepKey | null {
if (state === 'IDLE') return null;
if (state === 'MOVING_TO_CAMERA' || state === 'DETECTING') return 'detection';
if (state === 'MOVING_TO_GATE' || state === 'WAITING_AT_GATE') return 'classification';
if (state === 'CLASSIFYING') return 'decision';
if (state.startsWith('ROUTE_TO_')) return 'command';
if (state === 'RETURN_HOME') return 'routing';
if (state === 'FAULT' || state === 'EMERGENCY_STOP') return 'routing';
return null;
}
function stepStatus(key: StepKey, current: StepKey | null, machineState: MachineState): StepStatus {
if (machineState === 'IDLE') return 'pending';
const order: StepKey[] = ['detection', 'classification', 'decision', 'command', 'routing'];
const currentIndex = current ? order.indexOf(current) : -1;
const keyIndex = order.indexOf(key);
if (machineState === 'RETURN_HOME') {
return keyIndex < order.length - 1 ? 'completed' : 'active';
}
if (machineState === 'FAULT' || machineState === 'EMERGENCY_STOP') {
return keyIndex <= currentIndex ? 'active' : 'pending';
}
if (keyIndex < currentIndex) return 'completed';
if (keyIndex === currentIndex) return 'active';
return 'pending';
}
export default function StorylineStepper({ simulation }: { simulation: SimulationState }) {
const current = activeStep(simulation.machineState);
return (
<section className="storyline-section" id="storyline" aria-labelledby="storyline-title">
<div className="section-header">
<h2 id="storyline-title">Этапы цикла</h2>
<p>Текущий этап системы в цепочке Detection → Classification → Decision → Command → Routing.</p>
</div>
<ol className="storyline-stepper">
{STEPS.map((step) => {
const status = stepStatus(step.key, current, simulation.machineState);
return (
<li key={step.key} className={`story-step step-${status}`}>
<div className="step-indicator" aria-hidden="true">
<span className="step-number">{step.number}</span>
</div>
<div className="step-content">
<strong>{step.label}</strong>
<span>{step.description}</span>
<span className="step-status-label">
{status === 'active' ? 'Сейчас' : status === 'completed' ? 'Готово' : 'Ожидание'}
</span>
</div>
</li>
);
})}
</ol>
</section>
);
}

View File

@@ -1,141 +0,0 @@
import { useEffect, useMemo } from 'react';
import * as THREE from 'three';
import type { SimulatedItem, SimulationState } from '../../domain/types';
import { itemPosition3D, ROUTE_COLORS } from './itemMotion';
import { getModelAsset } from '../../data/modelAssets';
import { getRenderedItemDimensions } from '../../domain/physicalLayout';
import RealItemModel from './RealItemModel';
/**
* Stage 1: VISUAL_SCALE_MULTIPLIER (2.5x) and the 0.12–0.45m clamps removed.
* `/details` now renders the same true physical scale as `/` (1 unit = 1m),
* with the shared manifest transform (bottom-center pivot, mm→m uniform).
*/
interface Props {
simulation: SimulationState;
currentItem?: SimulatedItem;
}
function FallbackPrimitive({
primitive,
sx,
sy,
sz,
color,
emissive,
roughness,
emissiveIntensity = 0.35,
}: {
primitive: 'box' | 'cylinder' | 'sphere';
sx: number;
sy: number;
sz: number;
color: string;
emissive: string;
roughness: number;
emissiveIntensity?: number;
}) {
const geometry = useMemo<THREE.BufferGeometry>(() => {
if (primitive === 'cylinder') {
return new THREE.CylinderGeometry(Math.min(sx, sz) / 2, Math.min(sx, sz) / 2, sy, 24);
}
if (primitive === 'sphere') {
return new THREE.SphereGeometry(Math.max(sx, sy, sz) / 2, 24, 16);
}
return new THREE.BoxGeometry(sx, sy, sz);
}, [primitive, sx, sy, sz]);
useEffect(() => () => geometry.dispose(), [geometry]);
// center-pivot primitives are lifted so their bottom touches the surface
return (
<mesh geometry={geometry} position={[0, sy / 2, 0]}>
<meshStandardMaterial
color={color}
emissive={emissive}
emissiveIntensity={emissiveIntensity}
roughness={roughness}
/>
</mesh>
);
}
export default function Item3D({ simulation, currentItem }: Props) {
if (!currentItem) {
return null;
}
const [x, y, z] = itemPosition3D(simulation);
const category = currentItem.classification.category;
const color = ROUTE_COLORS[category] ?? '#38bdf8';
const dims = getRenderedItemDimensions(currentItem.item.dimensionsMm);
const sx = dims.width;
const sy = dims.height;
const sz = dims.depth;
const detecting = simulation.machineState === 'DETECTING';
const moving = simulation.machineState.startsWith('ROUTE_TO_') ||
simulation.machineState === 'MOVING_TO_CAMERA' ||
simulation.machineState === 'MOVING_TO_GATE';
const fault = simulation.machineState === 'FAULT' || simulation.machineState === 'EMERGENCY_STOP';
const asset = getModelAsset(currentItem.item.id);
const finalColor = fault ? '#fb3d4e' : color;
const finalEmissive = fault ? '#fb3d4e' : color;
const finalRoughness = asset?.defaultRealAsset ? 0.35 : 0.4;
const emissiveBoost = moving ? 0.55 : 0.35;
const fallbackPrimitive = asset?.fallbackPrimitive ?? 'box';
const useReal = Boolean(asset?.defaultRealAsset && asset?.runtimePath);
const fallback = (
<FallbackPrimitive
primitive={fallbackPrimitive}
sx={sx}
sy={sy}
sz={sz}
color={finalColor}
emissive={finalEmissive}
roughness={finalRoughness}
emissiveIntensity={emissiveBoost}
/>
);
return (
<group position={[x, y, z]}>
{useReal && asset ? (
<RealItemModel
asset={asset}
material={{
color: finalColor,
emissive: finalEmissive,
emissiveIntensity: emissiveBoost,
roughness: finalRoughness,
}}
fallback={fallback}
/>
) : (
fallback
)}
{/* Glow ring at the contact plane under the item */}
<mesh position={[0, 0.01, 0]} rotation={[-Math.PI / 2, 0, 0]}>
<ringGeometry args={[Math.max(sx, sz) * 0.4, Math.max(sx, sz) * 0.6, 32]} />
<meshStandardMaterial
color={finalColor}
emissive={finalColor}
emissiveIntensity={moving ? 0.8 : 0.4}
transparent
opacity={moving ? 0.7 : 0.4}
/>
</mesh>
{detecting ? (
<mesh position={[0, sy / 2, 0]}>
<boxGeometry args={[sx + 0.12, sy + 0.12, sz + 0.12]} />
<meshStandardMaterial color="#38bdf8" wireframe transparent opacity={0.9} />
</mesh>
) : null}
</group>
);
}

View File

@@ -1,162 +0,0 @@
/**
* Junction rotary guide gates — two light-gray vanes at JUNCTION.
*
* Invented sorter drive assets (mechanism-final / mechanism-mount motors,
* servos, paddle) are not loaded. Each vane shares one kinematic RigidBody
* for visible mesh + collider (same pivot, position, quaternion).
*/
import { memo, useRef, type MutableRefObject } from 'react';
import { useFrame } from '@react-three/fiber';
import { Html } from '@react-three/drei';
import { RigidBody, CuboidCollider, type RapierRigidBody } from '@react-three/rapier';
import {
GATE_VANE,
getGateState,
gateOpenLeadSec,
} from '../../domain/pusherMotion';
// GATE_VANE used for gateShot hold snapshot timing
import { JUNCTION } from '../../domain/physicalLayout';
import { getRoutingStartMs } from '../../domain/physicalItemMotion';
import { physicsSimClock } from './SorterPhysics';
import type { Category } from '../../domain/types';
export const MECHANISM_SOURCE_STATUS = 'JUNCTION_ROTARY_GATES' as const;
export const MECHANISM_CAD_URL = '/models/sorter/mechanism-final.glb';
export const MECHANISM_MOUNT_URL = '/models/sorter/mechanism-mount-final.glb';
const VANE_COLOR = '#e6ebf0';
type YawRefs = { left: number; right: number };
function GateVaneBody({
side,
yawRefs,
castShadow,
}: {
side: 'left' | 'right';
yawRefs: MutableRefObject<YawRefs>;
castShadow: boolean;
}) {
const bodyRef = useRef<RapierRigidBody>(null);
const pivot = side === 'left' ? JUNCTION.leftPivot : JUNCTION.rightPivot;
const [hx, hy, hz] = GATE_VANE.halfExtents;
useFrame(() => {
const body = bodyRef.current;
if (!body) return;
const yawRad = side === 'left' ? yawRefs.current.left : yawRefs.current.right;
const x = pivot.x + Math.cos(yawRad) * hx;
const y = GATE_VANE.centerY;
const z = pivot.z + Math.sin(yawRad) * hx;
body.setNextKinematicTranslation({ x, y, z });
const half = yawRad / 2;
body.setNextKinematicRotation({ x: 0, y: Math.sin(half), z: 0, w: Math.cos(half) });
});
return (
<RigidBody
ref={bodyRef}
type="kinematicPosition"
colliders={false}
friction={0.35}
position={[pivot.x + hx, GATE_VANE.centerY, pivot.z]}
>
<CuboidCollider args={[hx, hy, hz]} />
<mesh castShadow={castShadow} receiveShadow={castShadow}>
<boxGeometry args={[hx * 2, hy * 2, hz * 2]} />
<meshStandardMaterial
color={VANE_COLOR}
metalness={0.35}
roughness={0.45}
transparent={false}
opacity={1}
depthWrite
/>
</mesh>
</RigidBody>
);
}
/** Invented sorter mount / motors — not rendered (GLBs not loaded). */
export const MechanismMount = memo(function MechanismMount(_props: {
castShadow?: boolean;
}) {
return null;
});
export const PusherMechanism = memo(function PusherMechanism({
category,
routingElapsedMs,
caseElapsedMs,
castShadow = false,
}: {
category: Category | null;
routingElapsedMs: number;
caseElapsedMs?: number;
castShadow?: boolean;
}) {
const yawRefs = useRef<YawRefs>({ left: 0, right: 0 });
const hudRef = useRef<HTMLDivElement>(null);
const routeCat: 'B' | 'C' | 'D' | null =
category === 'B' || category === 'C' || category === 'D' ? category : null;
useFrame(() => {
const routingStartMs = getRoutingStartMs();
const leadMs = gateOpenLeadSec() * 1000;
const openAtMs = routingStartMs - leadMs;
const elapsedCase = caseElapsedMs ?? routingElapsedMs + routingStartMs;
const gateTimelineSec = (elapsedCase - openAtMs) / 1000;
// ?gateShot=1 freezes the active divert pose at 45° for visual verification.
const gateShot = typeof window !== 'undefined'
&& new URLSearchParams(window.location.search).get('gateShot') === '1';
const state = gateShot && routeCat && routeCat !== 'B'
? getGateState(routeCat, GATE_VANE.swingSec + 0.05)
: getGateState(routeCat, gateTimelineSec);
yawRefs.current.left = state.leftYawRad;
yawRefs.current.right = state.rightYawRad;
if (hudRef.current) {
hudRef.current.textContent =
`L ${Math.round(state.leftDeg)}° / R ${Math.round(state.rightDeg)}°`;
}
if (typeof window !== 'undefined'
&& new URLSearchParams(window.location.search).get('trace') === '1') {
(window as unknown as { __GATE_STATE?: unknown }).__GATE_STATE = {
mode: state.mode,
phase: state.phase,
leftDeg: state.leftDeg,
rightDeg: state.rightDeg,
junction: { x: JUNCTION.x, y: JUNCTION.y, z: JUNCTION.z },
simSec: physicsSimClock.simSec,
source: MECHANISM_SOURCE_STATUS,
};
}
(window as unknown as { __GATE_ANGLES?: { left: number; right: number } }).__GATE_ANGLES = {
left: Math.round(state.leftDeg),
right: Math.round(state.rightDeg),
};
});
return (
<group name="junction-guide-gates">
<GateVaneBody side="left" yawRefs={yawRefs} castShadow={castShadow} />
<GateVaneBody side="right" yawRefs={yawRefs} castShadow={castShadow} />
<Html position={[JUNCTION.x, JUNCTION.y + 0.45, 0]} center style={{ pointerEvents: 'none' }}>
<div
ref={hudRef}
style={{
color: '#e2e8f0',
fontFamily: 'ui-monospace, monospace',
fontSize: '13px',
fontWeight: 700,
textShadow: '0 1px 3px #000',
whiteSpace: 'nowrap',
}}
>
L 0° / R 0°
</div>
</Html>
</group>
);
});

View File

@@ -5,7 +5,7 @@
* Открытый верх, читаемая сетка стен (~100мм), пол-панель на CAGE_FLOOR_Y.
*
* Вся геометрия — 3 instanced draw call (трубы+прутья, колёса) + 1 mesh (пол).
* Одна и та же модель используется обеими сценами (`/` и `/details`).
* Shared roll-cage mesh for C/D receivers.
*
* Классификация узла (Stage 1 §13.4): PROCEDURAL_FALLBACK — официальной
* CAD-модели роллтейнера в архивах нет; размеры соответствуют спецификации.

View File

@@ -1,95 +0,0 @@
import type { Category, MachineState } from '../../domain/types';
import { ROUTE_COLORS, TWIN_LAYOUT } from './itemMotion';
interface Props {
category?: Category;
machineState: MachineState;
}
function RouteBeam({
start,
end,
color,
active,
}: {
start: [number, number, number];
end: [number, number, number];
color: string;
active: boolean;
}) {
const mid: [number, number, number] = [
(start[0] + end[0]) / 2,
(start[1] + end[1]) / 2,
(start[2] + end[2]) / 2,
];
const dx = end[0] - start[0];
const dz = end[2] - start[2];
const length = Math.sqrt(dx * dx + dz * dz) || 0.1;
const angle = Math.atan2(dz, dx);
// Much thicker and brighter active route
const thickness = active ? 0.12 : 0.04;
const width = active ? 0.22 : 0.08;
return (
<group>
{/* Main route beam */}
<mesh position={mid} rotation={[0, -angle, 0]}>
<boxGeometry args={[length, thickness, width]} />
<meshStandardMaterial
color={color}
transparent
opacity={active ? 1 : 0.3}
emissive={color}
emissiveIntensity={active ? 0.8 : 0.12}
/>
</mesh>
{/* Glow layer for active route */}
{active && (
<mesh position={[mid[0], mid[1] - 0.02, mid[2]]} rotation={[0, -angle, 0]}>
<boxGeometry args={[length, 0.02, width + 0.1]} />
<meshStandardMaterial
color={color}
transparent
opacity={0.5}
emissive={color}
emissiveIntensity={1.0}
/>
</mesh>
)}
</group>
);
}
export default function RouteArrows3D({ category, machineState }: Props) {
const routing = machineState.startsWith('ROUTE_TO_');
const classifying = machineState === 'CLASSIFYING';
const preview = classifying || routing || Boolean(category);
const y = TWIN_LAYOUT.beltY + 0.05;
const from: [number, number, number] = [TWIN_LAYOUT.gateX, y, 0];
return (
<group>
{/* Always draw B/C/D routes in distinct colors; active route is brighter */}
<RouteBeam
start={from}
end={[TWIN_LAYOUT.zoneBX, y, 0]}
color={ROUTE_COLORS.B}
active={preview && category === 'B'}
/>
<RouteBeam
start={from}
end={[TWIN_LAYOUT.gateX + 0.4, y, TWIN_LAYOUT.zoneCZ]}
color={ROUTE_COLORS.C}
active={preview && category === 'C'}
/>
<RouteBeam
start={from}
end={[TWIN_LAYOUT.gateX + 0.4, y, TWIN_LAYOUT.zoneDZ]}
color={ROUTE_COLORS.D}
active={preview && category === 'D'}
/>
</group>
);
}

View File

@@ -1,89 +0,0 @@
/**
* STLModel component — loads and displays STL models.
* Uses STLLoader from three/examples.
*/
import { useLoader } from '@react-three/fiber';
import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js';
import { Center } from '@react-three/drei';
import type { BufferGeometry, Mesh as ThreeMesh } from 'three';
import { Suspense, useRef, useEffect, useMemo } from 'react';
interface STLModelProps {
/** Path to STL file in public folder */
path: string;
/** Scale factor [x, y, z] */
scale: [number, number, number];
/** Rotation [x, y, z] in radians */
rotation?: [number, number, number];
/** Position offset [x, y, z] */
position?: [number, number, number];
/** Material color */
color: string;
/** Emissive color (for glow effect) */
emissive?: string;
/** Emissive intensity */
emissiveIntensity?: number;
/** Roughness */
roughness?: number;
/** Fallback component if loading fails */
fallback?: React.ReactNode;
}
/**
* Outer wrapper: Suspense boundary around the loader. Load errors propagate
* to the nearest ErrorBoundary (hooks must not live inside try/catch).
*/
export default function STLModel(props: STLModelProps) {
return (
<Suspense fallback={props.fallback ? <>{props.fallback}</> : null}>
<STLModelInner {...props} />
</Suspense>
);
}
function STLModelInner({
path,
scale,
rotation = [0, 0, 0],
position = [0, 0, 0],
color,
emissive,
emissiveIntensity = 0.2,
roughness = 0.5,
}: STLModelProps) {
const meshRef = useRef<ThreeMesh>(null);
const shared = useLoader(STLLoader, path) as BufferGeometry;
// Clone the loader-cached geometry before centering so the shared cache
// entry is never mutated; dispose the clone on unmount.
const geometry = useMemo(() => {
const g = shared.clone();
g.center();
g.computeVertexNormals();
return g;
}, [shared]);
useEffect(() => () => geometry.dispose(), [geometry]);
return (
<Center position={position} rotation={rotation}>
<mesh ref={meshRef} geometry={geometry} scale={scale}>
<meshStandardMaterial
color={color}
emissive={emissive ?? color}
emissiveIntensity={emissiveIntensity}
roughness={roughness}
/>
</mesh>
</Center>
);
}

View File

@@ -1,205 +0,0 @@
import { Html } from '@react-three/drei';
import type { Category, MachineState, SimulatedItem } from '../../domain/types';
import { ROUTE_COLORS, TWIN_LAYOUT } from './itemMotion';
import { OFFICIAL_RULE_LABELS } from '../../domain/classifier';
interface Props {
machineState: MachineState;
currentItem?: SimulatedItem;
simplified?: boolean;
conveyorTargetMps?: number;
technicalLabelsEnabled?: boolean;
cleanView?: boolean;
}
function Badge({
position,
text,
color = '#e5f2ff',
large = false,
}: {
position: [number, number, number];
text: string;
color?: string;
large?: boolean;
}) {
return (
<Html position={position} center distanceFactor={large ? 8 : 10} style={{ pointerEvents: 'none' }}>
<div
style={{
padding: large ? '8px 12px' : '4px 8px',
borderRadius: large ? 12 : 8,
background: 'rgba(5, 9, 16, 0.9)',
border: `1px solid ${color}`,
color,
fontSize: large ? 15 : 12,
fontWeight: 800,
whiteSpace: 'nowrap',
fontFamily: 'Inter, system-ui, sans-serif',
letterSpacing: large ? '0.04em' : undefined,
boxShadow: '0 8px 20px rgba(0,0,0,0.35)',
}}
>
{text}
</div>
</Html>
);
}
// ItemProofPanel removed — info now displayed in 2D proof card only
export default function SceneLabels3D({
machineState,
currentItem,
conveyorTargetMps = 1,
technicalLabelsEnabled = false,
cleanView = true,
}: 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_');
const fault = machineState === 'FAULT' || machineState === 'EMERGENCY_STOP';
// C-priority: dimensions failed + round detected → only C active, D not active
const isCPriority = Boolean(
category === 'C' && currentItem && !currentItem.classification.dimensionsPass && !currentItem.classification.roundnessPass
);
return (
<group>
{/* === CLEAN VIEW (always visible) === */}
{/* Zones A/B/C/D — always visible */}
<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"
color={ROUTE_COLORS.C}
large
/>
<Badge
position={[TWIN_LAYOUT.gateX + 0.4, cage.y + 0.35, TWIN_LAYOUT.zoneDZ]}
text="D"
color={ROUTE_COLORS.D}
large
/>
{/* Накопитель — only in technical mode (убран из clean view) */}
{technicalLabelsEnabled && (
<Badge
position={[TWIN_LAYOUT.accumulatorX, beltY + 0.25, 0.65]}
text="Накопитель"
color="#5eead4"
/>
)}
{/* === STEP-BASED LABELS (shown only when active) === */}
{/* Detection: Camera/CV + Laser */}
{detecting && (
<>
<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, beltY + 0.45, 0]} text="Stop-gate" color="#fda4af" />
</>
)}
{/* Routing: active pusher only */}
{routing && category === '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, 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, beltY + 0.05, 0]} text="→ B" color={ROUTE_COLORS.B} />
)}
{routing && category === 'C' && (
<Badge
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, beltY + 0.05, TWIN_LAYOUT.zoneDZ / 2]}
text="→ D"
color={ROUTE_COLORS.D}
/>
)}
{/* C-priority badge (only when applicable) */}
{isCPriority && (
<Badge
position={[TWIN_LAYOUT.gateX + 0.4, cage.y + 0.7, TWIN_LAYOUT.zoneCZ]}
text="C-priority"
color={ROUTE_COLORS.C}
large
/>
)}
{/* Fault / Emergency stop */}
{fault && (
<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, 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, beltY + 0.45, 0]} text="Stop-gate" color="#fda4af" />}
{!(routing && category === '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, 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, beltY + 0.05, 0]} text="Route B" color={ROUTE_COLORS.B} />
)}
{!(routing && category === 'C') && (
<Badge
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, beltY + 0.05, TWIN_LAYOUT.zoneDZ / 2]}
text="Route D"
color={ROUTE_COLORS.D}
/>
)}
{/* Conveyor info */}
<Badge
position={[-3.2, beltY + 0.85, 1.4]}
text={`Conveyor ${conveyorTargetMps.toFixed(2)} m/s · ${OFFICIAL_RULE_LABELS.minDisplay}`}
color="#91a4b8"
/>
</>
)}
</group>
);
}

View File

@@ -1,92 +0,0 @@
import { Canvas, useFrame } from '@react-three/fiber';
import { useEffect, useMemo, useRef, useState } from 'react';
import { detectWebGL, useWebGLSupport } from './useWebGL';
import { PHYSICS_ENGINE_ENABLED } from './itemMotion';
function SpikeScene({ onFps }: { onFps: (fps: number) => void }) {
const frames = useRef<number[]>([]);
const last = useRef(performance.now());
useFrame(() => {
const now = performance.now();
const dt = now - last.current;
last.current = now;
if (dt <= 0) return;
const fps = 1000 / dt;
frames.current.push(fps);
if (frames.current.length > 60) {
frames.current.shift();
}
const avg = frames.current.reduce((a, b) => a + b, 0) / frames.current.length;
onFps(Math.round(avg));
});
const boxes = useMemo(
() =>
Array.from({ length: 16 }, (_, index) => ({
key: index,
position: [((index % 4) - 1.5) * 0.45, 0.2 + Math.floor(index / 4) * 0.35, -0.4] as [
number,
number,
number,
],
})),
[],
);
return (
<>
<ambientLight intensity={0.55} />
<directionalLight position={[4, 6, 2]} intensity={0.85} />
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0, 0]}>
<planeGeometry args={[6, 4]} />
<meshStandardMaterial color="#0b1725" />
</mesh>
<mesh position={[0, 0.15, 0]}>
<boxGeometry args={[3.5, 0.2, 0.5]} />
<meshStandardMaterial color="#1e3a54" />
</mesh>
{boxes.map((box) => (
<mesh key={box.key} position={box.position}>
<boxGeometry args={[0.28, 0.28, 0.28]} />
<meshStandardMaterial color={box.key % 3 === 0 ? '#4ade80' : box.key % 3 === 1 ? '#f59e0b' : '#c084fc'} />
</mesh>
))}
</>
);
}
/**
* Diagnostic utility: WebGL probe + lightweight scene FPS.
* Physics engine is intentionally not loaded (see PHYSICS_ENGINE_ENABLED).
*/
export default function ThreeCapabilityCheck() {
const webgl = useWebGLSupport();
const [fps, setFps] = useState(0);
const [ready, setReady] = useState(false);
useEffect(() => {
setReady(true);
}, []);
return (
<div className="three-capability-check">
<div className="three-capability-meta">
<strong>3D capability check</strong>
<span>WebGL: {webgl ? 'OK' : 'unavailable'}</span>
<span>Physics engine: {PHYSICS_ENGINE_ENABLED ? 'enabled' : 'disabled (state-machine motion)'}</span>
<span>Avg FPS: {webgl && ready ? fps : '—'}</span>
<span>Runtime detect: {detectWebGL() ? 'yes' : 'no'}</span>
</div>
{webgl && ready ? (
<div className="three-capability-canvas">
<Canvas camera={{ position: [2.5, 2.2, 3.2], fov: 45 }} dpr={[1, 1.5]}>
<SpikeScene onFps={setFps} />
</Canvas>
</div>
) : (
<p className="three-fallback-note">WebGL недоступен — 3D digital twin будет в 2D fallback.</p>
)}
</div>
);
}

View File

@@ -1,24 +0,0 @@
import SorterScene from '../SorterScene';
import type { SimulationState } from '../../domain/types';
interface Props {
simulation: SimulationState;
reason?: 'webgl' | 'user' | 'mobile';
}
const MESSAGES: Record<NonNullable<Props['reason']>, string> = {
webgl: '3D недоступен (WebGL), включён 2D fallback. Логика симуляции та же.',
user: 'Включён 2D fallback. Логика симуляции та же.',
mobile: 'На узком экране включён 2D fallback. Логика симуляции та же.',
};
export default function ThreeFallback({ simulation, reason = 'user' }: Props) {
return (
<div className="three-fallback">
<p className="three-fallback-note" role="status">
{MESSAGES[reason]}
</p>
<SorterScene simulation={simulation} variant="simple" />
</div>
);
}

View File

@@ -1,68 +0,0 @@
import type { Category, MachineState, SimulationState } from '../../domain/types';
import {
CATEGORY_COLORS,
DETAILS_TWIN_LAYOUT,
} from '../../domain/layout/sharedLayout';
/**
* 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: CATEGORY_COLORS.B,
C: CATEGORY_COLORS.C,
D: CATEGORY_COLORS.D,
};
export function progressForState(state: MachineState, elapsedMs: number): number {
const ratios: Partial<Record<MachineState, [number, number, number]>> = {
MOVING_TO_CAMERA: [0.06, 0.34, 1200],
DETECTING: [0.34, 0.36, 900],
MOVING_TO_GATE: [0.36, 0.64, 1300],
WAITING_AT_GATE: [0.64, 0.65, 800],
CLASSIFYING: [0.65, 0.66, 700],
ROUTE_TO_B: [0.66, 0.93, 1200],
ROUTE_TO_C: [0.66, 0.82, 1200],
ROUTE_TO_D: [0.66, 0.82, 1200],
RETURN_HOME: [0.93, 0.94, 700],
};
const segment = ratios[state];
if (!segment) {
return state === 'IDLE' ? 0.04 : 0.65;
}
const [from, to, duration] = segment;
return from + (to - from) * Math.min(elapsedMs / duration, 1);
}
export function itemPosition3D(simulation: SimulationState): [number, number, number] {
const progress = progressForState(simulation.machineState, simulation.elapsedInStateMs);
const x = TWIN_LAYOUT.startX + progress * (TWIN_LAYOUT.endX - TWIN_LAYOUT.startX);
// Stage 1: bottom-contact semantics — the item's bottom point rests on the
// belt surface (was beltY + 0.12, a 12cm visual float).
const y = TWIN_LAYOUT.beltY;
let z = 0;
if (simulation.machineState === 'ROUTE_TO_C') {
z = Math.min(simulation.elapsedInStateMs / 1200, 1) * TWIN_LAYOUT.zoneCZ;
} else if (simulation.machineState === 'ROUTE_TO_D') {
z = -Math.min(simulation.elapsedInStateMs / 1200, 1) * Math.abs(TWIN_LAYOUT.zoneDZ);
}
return [x, y, z];
}
export function pusherOffset(state: 'idle' | 'extended' | 'retracting'): number {
if (state === 'extended') return 0.55;
if (state === 'retracting') return 0.25;
return 0;
}
/**
* Motion layer is state-machine driven (no physics engine).
* Future physics integration can replace this module with kinematic bodies.
*/
export const PHYSICS_ENGINE_ENABLED = false;

View File

@@ -1,39 +0,0 @@
import { buildCycleTimeline } from '../domain/simulation';
import type { SimulationState } from '../domain/types';
function formatMs(ms?: number): string {
return ms === undefined ? '-' : `t+${(ms / 1000).toFixed(1)}s`;
}
export default function TimelinePanel({ simulation }: { simulation: SimulationState }) {
const timeline = buildCycleTimeline(simulation);
const current = simulation.currentItem;
const totalCycleTime = current ? simulation.simTimeMs - current.startedAtMs : 0;
return (
<section className="panel timeline-panel">
<div className="panel-heading">
<p className="eyebrow">Cycle timeline</p>
<h2>{current ? current.item.id : 'No active cycle'}</h2>
</div>
<div className="timeline-summary">
<div><span>total cycle</span><strong>{totalCycleTime} ms</strong></div>
<div><span>cv latency</span><strong>{simulation.metrics.cvLatencyMs} ms</strong></div>
<div><span>actuator latency</span><strong>{simulation.metrics.actuatorLatencyMs} ms</strong></div>
<div><span>conveyor</span><strong>{simulation.metrics.conveyorSpeedMps.toFixed(2)} m/s</strong></div>
<div><span>queue delay</span><strong>{simulation.metrics.queueDelayMs} ms</strong></div>
</div>
<div className="timeline-list">
{timeline.map((entry) => (
<div className={`timeline-row ${entry.status}`} key={entry.state}>
<span className="timeline-dot" />
<strong>{entry.state}</strong>
<span>{formatMs(entry.startedAtMs)}</span>
<span>{entry.durationMs} ms</span>
<em>{entry.status}</em>
</div>
))}
</div>
</section>
);
}

View File

@@ -1,22 +0,0 @@
import { describe, expect, it } from 'vitest';
import { OZON_CRITERIA } from './criteria';
import { SCENARIOS } from './scenarios';
const scenarioIds = new Set(SCENARIOS.map((scenario) => scenario.id));
describe('OZON criteria', () => {
it('contains evidence and valid scenario references', () => {
expect(OZON_CRITERIA.length).toBeGreaterThan(0);
for (const criterion of OZON_CRITERIA) {
expect(criterion.title).toBeTruthy();
expect(criterion.status).toMatch(/covered|partially covered|demo step available/);
expect(criterion.evidence).toBeTruthy();
expect(criterion.relatedDoc).toBeTruthy();
expect(criterion.relatedScenarioIds.length).toBeGreaterThan(0);
for (const scenarioId of criterion.relatedScenarioIds) {
expect(scenarioIds.has(scenarioId)).toBe(true);
}
}
});
});

View File

@@ -1,108 +0,0 @@
import type { OzonCriterion } from '../domain/types';
export const OZON_CRITERIA: OzonCriterion[] = [
{
id: 'category-correctness',
title: 'Category correctness',
status: 'covered',
evidence: 'Classifier tests and decision tree prove B/C/D outcomes for mock SKUs.',
relatedScenarioIds: ['normal_flow', 'oversized_item', 'round_object'],
relatedDoc: 'docs/SCENARIOS.md',
},
{
id: 'classification-rules',
title: 'Classification rules: dimensions, roundness, priority',
status: 'covered',
evidence: 'ClassificationPanel shows thresholds, actual values, PASS/FAIL and C priority.',
relatedScenarioIds: ['oversized_item', 'round_object', 'c_priority', 'boundary_dimensions'],
relatedDoc: 'docs/ARCHITECTURE.md',
},
{
id: 'boundary-cases',
title: 'Boundary cases',
status: 'covered',
evidence: 'Boundary dimensions scenario and tests cover max boundary and min-width violation.',
relatedScenarioIds: ['boundary_dimensions'],
relatedDoc: 'docs/SCENARIOS.md',
},
{
id: 'physical-routing',
title: 'Physical routing B/C/D',
status: 'covered',
evidence: 'SorterScene displays B straight route, C lower route and D upper route with commands.',
relatedScenarioIds: ['normal_flow', 'oversized_item', 'round_object'],
relatedDoc: 'docs/DEMO_SCRIPT.md',
},
{
id: 'manipulation-logic',
title: 'Manipulation logic',
status: 'covered',
evidence: 'Stop-gate and pusher states are tied to state machine routes.',
relatedScenarioIds: ['oversized_item', 'round_object'],
relatedDoc: 'docs/ARCHITECTURE.md',
},
{
id: 'geometry-variety',
title: 'Geometry variety',
status: 'covered',
evidence: 'Mock items include boxes, pouf, plate, bottle, cylinder, pen and boundary box.',
relatedScenarioIds: ['normal_flow', 'round_object', 'boundary_dimensions'],
relatedDoc: 'docs/SCENARIOS.md',
},
{
id: 'safety-emergency',
title: 'Safety / emergency stop',
status: 'demo step available',
evidence: 'Emergency stop scenario enters EMERGENCY_STOP and requires Reset.',
relatedScenarioIds: ['emergency_stop'],
relatedDoc: 'docs/DEMO_SCRIPT.md',
},
{
id: 'cycle-time-throughput',
title: 'Cycle time and throughput',
status: 'covered',
evidence: 'Metrics cards show processed count, avg cycle time and throughput.',
relatedScenarioIds: ['normal_flow', 'close_items'],
relatedDoc: 'docs/ARCHITECTURE.md',
},
{
id: 'timing-synchronization',
title: 'Timing synchronization',
status: 'covered',
evidence: 'CycleTimeline shows state timestamps, durations and active/done status.',
relatedScenarioIds: ['normal_flow', 'close_items'],
relatedDoc: 'docs/ARCHITECTURE.md',
},
{
id: 'fault-handling',
title: 'Fault handling',
status: 'demo step available',
evidence: 'Jam scenario enters FAULT, logs fault and stops conveyor.',
relatedScenarioIds: ['jam', 'low_confidence'],
relatedDoc: 'docs/JURY_QA.md',
},
{
id: 'cv-actuator-integration',
title: 'CV-to-actuator integration',
status: 'covered',
evidence: 'Pseudo-CV packet feeds classification, which emits ROUTE_TO_* actuator commands.',
relatedScenarioIds: ['normal_flow', 'low_confidence'],
relatedDoc: 'docs/ARCHITECTURE.md',
},
{
id: 'engineering-realism',
title: 'Engineering realism',
status: 'partially covered',
evidence: 'Scaled 2D layout, sensor latency, PID imitation and event trace are present; real hardware is out of MVP scope.',
relatedScenarioIds: ['normal_flow', 'jam', 'emergency_stop'],
relatedDoc: 'docs/JURY_QA.md',
},
{
id: 'reproducibility-docs',
title: 'Reproducibility / docs',
status: 'covered',
evidence: 'README and docs describe architecture, demo script, scenarios and jury Q&A.',
relatedScenarioIds: ['normal_flow', 'boundary_dimensions'],
relatedDoc: 'docs/DEMO_SCRIPT.md',
},
];

View File

@@ -1,17 +0,0 @@
import { describe, expect, it } from 'vitest';
import { DEMO_STEPS } from './demoSteps';
import { SCENARIOS } from './scenarios';
const scenarioIds = new Set(SCENARIOS.map((scenario) => scenario.id));
describe('demo steps', () => {
it('have required narrative fields and valid scenarios', () => {
for (const step of DEMO_STEPS) {
expect(step.id).toBeTruthy();
expect(step.title).toBeTruthy();
expect(scenarioIds.has(step.scenarioId)).toBe(true);
expect(step.relatedCriteria.length).toBeGreaterThan(0);
expect(step.presenterPhrase).toBeTruthy();
}
});
});

View File

@@ -1,137 +0,0 @@
import type { DemoStep } from '../domain/types';
export const DEMO_STEPS: DemoStep[] = [
{
id: 'system-overview',
title: 'System overview',
scenarioId: 'normal_flow',
preferredAction: 'reset',
focusArea: 'scene',
explanation: 'The line is presented as detection -> classification -> actuator command -> physical route.',
whatToWatch: 'Scaled SVG scene, sensor positions, stop-gate, pushers and B/C/D routing arrows.',
juryValue: 'Shows that the project is an engineering simulation of a sorting cell, not a decorative animation.',
relatedCriteria: ['engineering-realism', 'cv-actuator-integration', 'physical-routing'],
presenterPhrase: 'We model the whole loop: the item is detected, classified by rules, converted to an actuator command and routed physically.',
},
{
id: 'normal-item-to-b',
title: 'Normal item to B',
scenarioId: 'normal_flow',
preferredAction: 'step',
focusArea: 'classification',
explanation: 'A regular box passes dimensions and roundness checks, so it stays on the main sorter path.',
whatToWatch: 'Decision tree PASS/PASS and ROUTE_TO_B command in the scene and event log.',
juryValue: 'Proves the happy path and shows category correctness for standard goods.',
relatedCriteria: ['category-correctness', 'classification-rules', 'physical-routing'],
presenterPhrase: 'For a normal SKU, dimensions pass and circular section is not detected, so the gate opens to B.',
},
{
id: 'oversized-to-c',
title: 'Oversized item to C',
scenarioId: 'oversized_item',
preferredAction: 'step',
focusArea: 'classification',
explanation: 'Oversized goods fail the first rule and are routed to roll-cage C before shape is considered.',
whatToWatch: 'Dimensions FAIL, category C, pusher C and route arrow to the lower roll-cage.',
juryValue: 'Shows rule priority and safe diversion for non-compliant dimensions.',
relatedCriteria: ['classification-rules', 'boundary-cases', 'manipulation-logic'],
presenterPhrase: 'C has priority because geometry safety is checked before shape: this item cannot continue on the main sorter.',
},
{
id: 'round-object-to-d',
title: 'Round object to D',
scenarioId: 'round_object',
preferredAction: 'step',
focusArea: 'scene',
explanation: 'Roundness K > 0.8 after valid dimensions sends the item to D for repack/shape issue handling.',
whatToWatch: 'Roundness FAIL for B, category D and the upper route/pusher D command.',
juryValue: 'Shows how the circle-section rule becomes a physical route.',
relatedCriteria: ['classification-rules', 'geometry-variety', 'physical-routing'],
presenterPhrase: 'The dimensions fit, but roundness is high, so the system sends it to D for do-upakovka.',
},
{
id: 'c-priority-oversized-round',
title: 'C priority oversized + round',
scenarioId: 'c_priority',
preferredAction: 'step',
focusArea: 'classification',
explanation: 'Item is both oversized and round; dimensions are checked first so category is C, not D.',
whatToWatch: 'DIM FAIL, K high, category C, ROUTE_TO_C active, route D inactive.',
juryValue: 'Proves C-priority rule for Track 3.',
relatedCriteria: ['classification-rules', 'boundary-cases', 'physical-routing'],
presenterPhrase: 'Even though the item is round, dimensions fail first, so we route only to C.',
},
{
id: 'boundary-dimensions',
title: 'Boundary dimensions',
scenarioId: 'boundary_dimensions',
preferredAction: 'step',
focusArea: 'classification',
explanation: 'Items at the edge of the allowed envelope prove the rule implementation is stable.',
whatToWatch: '450 x 320 x 320 passes, while width 9 mm fails min width and goes to C.',
juryValue: 'Shows deterministic boundary behavior rather than visual guessing.',
relatedCriteria: ['boundary-cases', 'category-correctness', 'reproducibility-docs'],
presenterPhrase: 'The exact boundary is accepted, but one millimeter below minimum width is rejected.',
},
{
id: 'low-confidence-fallback',
title: 'Low confidence fallback',
scenarioId: 'low_confidence',
preferredAction: 'step',
focusArea: 'eventLog',
explanation: 'Low pseudo-CV confidence raises a warning but does not block rule-based classification.',
whatToWatch: 'Warning message, fallback note and final category in classification/event log.',
juryValue: 'Shows graceful degradation when CV is uncertain.',
relatedCriteria: ['cv-actuator-integration', 'fault-handling', 'classification-rules'],
presenterPhrase: 'CV confidence is low, so we flag it, but dimensions and roundness still produce a deterministic decision.',
},
{
id: 'close-items-queue',
title: 'Close items queue',
scenarioId: 'close_items',
preferredAction: 'start',
focusArea: 'timeline',
explanation: 'Close spacing creates a queue warning and items are still processed one cycle at a time.',
whatToWatch: 'Queue length, queue delay, spacing warning and sequential timeline.',
juryValue: 'Shows robustness for a common operational issue without overcomplicated physics.',
relatedCriteria: ['timing-synchronization', 'cycle-time-throughput', 'fault-handling'],
presenterPhrase: 'The line detects close spacing, holds the queue and keeps the state machine deterministic.',
},
{
id: 'jam-fault-handling',
title: 'Jam / fault handling',
scenarioId: 'jam',
preferredAction: 'step',
focusArea: 'safety',
explanation: 'A jam at the stop-gate moves the system to FAULT and stops the conveyor.',
whatToWatch: 'FAULT state, red scene overlay, PID target 0 and Reset required.',
juryValue: 'Shows fail-safe behavior and operator recovery path.',
relatedCriteria: ['fault-handling', 'safety-emergency', 'pid-synchronization'],
presenterPhrase: 'When the gate jams, the safest command is to stop motion and require reset.',
},
{
id: 'emergency-stop',
title: 'Emergency stop',
scenarioId: 'emergency_stop',
preferredAction: 'step',
focusArea: 'safety',
explanation: 'Emergency stop interrupts the line and brings motion toward zero.',
whatToWatch: 'EMERGENCY_STOP state, stopped conveyor and PID speed falling to zero.',
juryValue: 'Shows explicit safety handling for abnormal operation.',
relatedCriteria: ['safety-emergency', 'fault-handling', 'engineering-realism'],
presenterPhrase: 'Emergency stop is not another route; it is a safety state that freezes the line until reset.',
},
{
id: 'performance-sync',
title: 'Performance and synchronization',
scenarioId: 'normal_flow',
preferredAction: 'start',
focusArea: 'pid',
explanation: 'Timeline, latency cards and PID graph show how the simulated control loop stays synchronized.',
whatToWatch: 'CycleTimeline, CV latency, actuator latency, throughput and PID speed curve.',
juryValue: 'Shows that the demo explains timing and throughput, not only classification.',
relatedCriteria: ['cycle-time-throughput', 'timing-synchronization', 'engineering-realism'],
presenterPhrase: 'Here we close the loop: decisions are timestamped, actuators have latency and conveyor control is visible.',
},
];

View File

@@ -1,70 +1,182 @@
/**
* Compact tracked production-status summary for the Documentation page.
* Sources: Gate 2C / 2D confirmed decisions. Unverified values are NOT stated as facts.
* Does not import ignored tools/author-exact-v4/out/ at runtime.
* Canonical summary data for `/documentation`.
* Authority: official sources present in-repo → production code → unit tests.
* Unverified / planned items are labeled explicitly — never implied complete.
*/
/** Kept for e2e (`docs-production-status`) and acquisition-pack provenance. */
export const PRODUCTION_STATUS = {
acquisitionPackStatus: 'DATA_ACQUISITION_PACK_READY',
electricalGateStatus: 'BLOCKED_BY_MISSING_PRODUCTION_INPUTS',
productionDesignReady: false,
motorSelected: false,
encoderSelected: false,
diverterApproved: false,
cadReady: false,
gate3Started: false,
webTwinStatus: 'BASELINE_PRESERVED',
unitTests: '196/196',
productionBuild: 'PASS',
contactPhysics: 'NOT_FULLY_VALIDATED',
officialCompliance: 'PARTIAL_SOURCES_PRESENT',
} as const;
/** Confirmed layout facts only (drawing / shared provenance). */
export const CONFIRMED_LAYOUT = {
workspaceMm: { length: 10000, width: 6000 },
conveyorWidthMm: 500,
conveyorHeightMm: 700,
pointACenterlineFromWorkspaceBottomMm: 3000,
authorDiverter: 'ABSENT' as const,
link027029Role: 'STOP_GATE' as const,
modules: ['clean', 'camera', 'sorter'] as const,
receivers: ['B_STRAIGHT', 'ZONE_C', 'ZONE_D'] as const,
} as const;
export const CONFIRMED_COMPONENT_POLICY = {
mg996r: 'PROTOTYPE_ONLY' as const,
vl53l0x: 'NOT_PRODUCTION_OR_SAFETY' as const,
productionMotor: 'NOT_DEFINED' as const,
productionGearbox: 'NOT_DEFINED' as const,
productionDriver: 'NOT_DEFINED' as const,
productionEncoder: 'NOT_SELECTED' as const,
export const CLASSIFIER_BOUNDS = {
status: 'CURRENT_IMPLEMENTATION_VERIFIED_IN_CODE' as const,
officialSourceReference: 'official_sources/doc-1783095831.pdf',
officialSourceParsedThisPass: false,
minExclusiveMm: { width: 10, depth: 10, height: 10 },
maxExclusiveMm: { width: 450, depth: 320, height: 320 },
roundnessThresholdExclusive: 0.8,
display: {
min: '> 10×10×10 мм',
max: '< 450×320×320 мм',
roundness: 'K > 0.8',
},
checkOrder: 'dimensions→C, else circular→D, else B' as const,
} as const;
export const ROLLER_DIAMETER_CONFLICT = {
authorCadIdlerMm: 50,
runtimeIdlerMm: 80,
runtimeDriveMm: 120,
status: 'CONFLICTING' as const,
} as const;
export const CURRENT_BLOCKERS = [
'Отсутствуют производственные параметры двигателя',
'Энкодер не выбран',
'Конфликт диаметров роликов (CAD idler 50 / runtime idler 80 / runtime drive 120)',
'ROOT_BIND не подтверждён',
'Не зафиксирована геометрия junction',
'Отсутствуют товарные нагрузки (масса, COM, трение)',
'Не завершена силовая архитектура',
'Не завершена safety-архитектура',
'Производственный diverter ещё не спроектирован',
export const ROUTE_MAPPING = [
{ category: 'B', physicalRoute: 'STRAIGHT', activeDiverter: 'NONE', signedAngleDeg: 0 },
{ category: 'C', physicalRoute: 'PHYSICAL_LEFT', activeDiverter: 'LEFT', signedAngleDeg: -45 },
{ category: 'D', physicalRoute: 'PHYSICAL_RIGHT', activeDiverter: 'RIGHT', signedAngleDeg: 45 },
] as const;
export const GATE_STATUS_BOARD = [
{ gate: '0 BASELINE', status: 'PASS' },
{ gate: '1 AUTHOR STRUCTURE', status: 'PASS' },
{ gate: '2 KINEMATICS', status: 'BLOCKED' },
{ gate: '2A source discovery', status: 'NO_AUTHOR_DIVERTER_SOURCE' },
{ gate: '2B engineering spec', status: 'ARCHITECTURE_RESELECTION_REQUIRED' },
{ gate: '2C production electrical', status: 'BLOCKED_BY_MISSING_PRODUCTION_INPUTS' },
{ gate: '2D data acquisition pack', status: 'DATA_ACQUISITION_PACK_READY' },
{ gate: '3 AUTHOR_EXACT / production CAD', status: 'NOT_STARTED' },
export const DIVERTER_KINEMATICS = {
rotationDurationSec: 0.5,
openingSafetyMarginSec: 0.15,
contactPlaneS: 1.0538,
clearPlaneS: 1.6,
phases: ['READY', 'ARMED', 'OPENING', 'HOLDING', 'CLOSING'] as const,
productBound: true,
oneActiveProduct: true,
closeAfterRearClear: true,
generatedMechanismActive: false,
} as const;
export const CAD_PROVENANCE = {
authorFcstd: '3d_models/conveer.FCStd',
authorSha256: '90c1844a4ca05e26def783d6130fc4b993430dde14307534ef8fbb21c9fac2e6',
runtimeGlb: 'public/models/sorter/conveyor-clean.glb',
runtimeSha256: '1dc7a8d7891bfe756e277ad5368df74cb73410156b2fe0f92845afb8a56f285a',
authorServosInSorterModule: true,
generatedMechanismInactive: true,
hornTransmissionInGlb: 'ABSENT_OR_INCOMPLETE' as const,
} as const;
export const PHYSICS_STATUS = {
implemented: [
'Runtime product motion on belt (domain pose + Rapier handoff)',
'Product-associated diverter route timing (productId-bound)',
'Synchronized CAD diverter visual / kinematic targets',
'CCD enabled for light/thin SKUs in runtime and headless sim',
'Visual/physics spawn gating via product asset preload',
],
notFullyValidated: [
'Complete contact-only routing through CAD diverters',
'Belt surface velocity exactly 1 m/s with tangential drive',
'Calibrated friction / mass / COM per SKU',
'Fully physical continuous conveyor loop',
'Receiver capture under all item classes',
],
planned: [
'Visual full belt loop with surface-velocity coupling',
'Controlled tangential friction at 1 m/s',
'Dynamic rigid bodies for divert segment with fixed timestep',
'Per-SKU collider, damping, and friction profiles',
],
} as const;
export const VALIDATION_BOARD = [
{ item: 'Unit tests', status: '196/196 PASS' },
{ item: 'Production build', status: 'PASS' },
{ item: 'Active routes / + /documentation', status: 'PASS' },
{ item: 'conveyor-clean.glb checksum', status: 'PASS' },
{ item: 'Author FCStd checksum', status: 'PASS' },
{ item: 'Frozen diverter angles / 0.50 s', status: 'PASS' },
{ item: 'Full contact physics', status: 'NOT_FULLY_VALIDATED' },
] as const;
export const OFFICIAL_SOURCE_MATRIX = [
{
source: 'input_info/doc-1783009063.pdf',
purpose: 'Allowed software list',
present: true,
canonical: true,
usage: 'Stack compliance reference',
},
{
source: 'input_info/doc-1783009942.pdf',
purpose: 'Workspace / zone scheme',
present: true,
canonical: true,
usage: 'Layout provenance (workspace 10×6 m)',
},
{
source: 'input_info/doc-1783011400.pdf',
purpose: 'Track 3 scoring criteria',
present: true,
canonical: true,
usage: 'Jury scoring — not re-parsed this pass',
},
{
source: 'input_info/doc-1782987706.zip',
purpose: 'Official STEP product set',
present: true,
canonical: true,
usage: 'Product geometry source archive',
},
{
source: 'input_info/doc-1782987733.zip',
purpose: 'Official STL product set',
present: true,
canonical: true,
usage: 'Feeds public/models/*.stl',
},
{
source: 'input_info/doc-1783011771.zip',
purpose: 'Official pack archive',
present: true,
canonical: true,
usage: 'Retained official material',
},
{
source: 'official_sources/doc-1783095831.pdf',
purpose: 'Classifier bounds authority cited by code',
present: true,
canonical: true,
usage: 'Referenced by classifier.ts; not re-parsed this pass',
},
{
source: 'input_info/extracted/Постановка_Задача_3_сжато_2.pdf',
purpose: 'Full task brief (historical citation)',
present: false,
canonical: false,
usage: 'MISSING — do not cite as available evidence',
},
] as const;
export const RUNTIME_FLOW = [
'SPAWN',
'CONVEYOR',
'CAMERA',
'CLASSIFICATION',
'ARMED',
'OPENING',
'HOLDING',
'CLOSING',
'RECEIVER',
] as const;
export const CURRENT_LIMITATIONS = [
'Full physical contact sorting through CAD diverters is not fully validated.',
'Belt surface-velocity drive at exactly 1 m/s is planned, not complete.',
'Per-SKU physical parameters still require profiling/calibration.',
'Author CAD horn / transmission incomplete in active GLB.',
'Official compliance is partial: missing extracted task PDF; scoring PDF not re-parsed this pass.',
'Repository retains only the web twin, author CAD, official sources, and active tests.',
] as const;
/** @deprecated alias — historical Gate wording retained for acquisition-pack note */
export const DATA_ACQUISITION_SEQUENCE = ['MEASURE', 'VERIFY', 'FREEZE', 'DESIGN'] as const;
export const OWNER_INPUT_FORM_NOTE =
'Главный документ входных данных владельца: OWNER_PRODUCTION_INPUT_FORM.md (пакет Gate 2D, вне публичного runtime).';

View File

@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest';
import { SCENARIOS } from './scenarios';
import type { ScenarioId } from '../domain/types';
const expectedIds: ScenarioId[] = [
'normal_flow',
'oversized_item',
'round_object',
'c_priority',
'boundary_dimensions',
'close_items',
'low_confidence',
'jam',
'emergency_stop',
];
describe('scenarios', () => {
it('contains every expected scenario id', () => {
const ids = SCENARIOS.map((scenario) => scenario.id);
expect(ids).toEqual(expectedIds);
});
it('contains items and demo metadata for every scenario', () => {
for (const scenario of SCENARIOS) {
expect(scenario.items.length).toBeGreaterThan(0);
expect(scenario.goal.length).toBeGreaterThan(0);
expect(scenario.expectedCategorySummary.length).toBeGreaterThan(0);
expect(scenario.demonstrates.length).toBeGreaterThan(0);
}
});
});

View File

@@ -1,145 +0,0 @@
/**
* Conveyor Path — calculates item position based on phase and progress.
* Uses real-world scale: 1 unit = 1 meter, conveyor speed = 1 m/s.
*
* Physical parameters sourced from physicalLayout.ts
*/
import type { Category } from './types';
import type { CasePhase, ContinuousPlaybackState } from './continuousPlayback';
import { getPhaseProgress } from './continuousPlayback';
import {
CONVEYOR_POSITIONS,
BELT_TOP_Y,
CONVEYOR_SPEED_MPS,
getItemYOnBelt,
} from './physicalLayout';
// Re-export for backwards compatibility
export { CONVEYOR_POSITIONS, CONVEYOR_SPEED_MPS };
/** Total conveyor length from A to gate in meters. */
export const CONVEYOR_LENGTH = CONVEYOR_POSITIONS.gateX - CONVEYOR_POSITIONS.spawnX;
export interface ItemPosition3D {
x: number;
y: number;
z: number;
}
/** Calculate item X position based on phase and progress. */
function getItemXForPhase(phase: CasePhase, phaseProgress: number, category: Category | null): number {
const { spawnX, cameraX, laserX, gateX, zoneBX } = CONVEYOR_POSITIONS;
switch (phase) {
case 'spawn':
return spawnX;
case 'move_to_detection':
return spawnX + (cameraX - spawnX) * phaseProgress;
case 'detection':
return cameraX;
case 'measurement':
return cameraX + (laserX - cameraX) * phaseProgress;
case 'classification':
return laserX + (gateX - laserX) * 0.5 * phaseProgress;
case 'command_sent':
const midPoint = laserX + (gateX - laserX) * 0.5;
return midPoint + (gateX - midPoint) * phaseProgress;
case 'routing':
if (category === 'B') {
return gateX + (zoneBX - gateX) * phaseProgress;
}
return gateX;
case 'exit':
return category === 'B' ? zoneBX : gateX;
case 'clear_gap':
return category === 'B' ? zoneBX : gateX;
default:
return gateX;
}
}
/** Calculate item Z position for routing to C or D. */
function getItemZForPhase(phase: CasePhase, phaseProgress: number, category: Category | null): number {
if (!category || category === 'B') return 0;
const { zoneCZ, zoneDZ } = CONVEYOR_POSITIONS;
if (phase === 'routing') {
const targetZ = category === 'C' ? zoneCZ : zoneDZ;
return targetZ * phaseProgress;
}
if (phase === 'exit' || phase === 'clear_gap') {
return category === 'C' ? zoneCZ : zoneDZ;
}
return 0;
}
/**
* Get item 3D position from playback state.
* Item is positioned ON the belt surface (not floating above).
*/
export function getItemPosition(state: ContinuousPlaybackState, itemVisualHeight: number = 0.15): ItemPosition3D {
const phaseProgress = getPhaseProgress(state);
const x = getItemXForPhase(state.currentPhase, phaseProgress, state.targetCategory);
const z = getItemZForPhase(state.currentPhase, phaseProgress, state.targetCategory);
// Item sits ON the belt: belt top + half item height
const y = getItemYOnBelt(itemVisualHeight);
return { x, y, z };
}
/** Get item visibility based on phase. */
export function isItemVisible(state: ContinuousPlaybackState): boolean {
return state.currentPhase !== 'clear_gap' || getPhaseProgress(state) < 0.5;
}
/** Get detection zone highlight status. */
export function isDetectionZoneActive(state: ContinuousPlaybackState): boolean {
return state.currentPhase === 'detection' || state.currentPhase === 'measurement';
}
/** Get active route based on phase and category. */
export function getActiveRoute(state: ContinuousPlaybackState): Category | null {
if (state.currentPhase === 'routing' || state.currentPhase === 'exit') {
return state.targetCategory;
}
return null;
}
/** Get conveyor belt animation speed factor (0 when stopped, 1 when running). */
export function getConveyorSpeedFactor(state: ContinuousPlaybackState): number {
if (state.status !== 'running') return 0;
const movingPhases: CasePhase[] = [
'move_to_detection',
'measurement',
'classification',
'command_sent',
'routing',
];
return movingPhases.includes(state.currentPhase) ? 1.0 : 0;
}
/** Calculate distance traveled in meters from elapsed time. */
export function getDistanceTraveled(elapsedMs: number): number {
return (elapsedMs / 1000) * CONVEYOR_SPEED_MPS;
}
/** Calculate time in ms to travel a distance at conveyor speed. */
export function getTimeForDistance(distanceM: number): number {
return (distanceM / CONVEYOR_SPEED_MPS) * 1000;
}

View File

@@ -1,201 +0,0 @@
import { describe, it, expect } from 'vitest';
import {
DemoStep,
createDemoDirectorState,
startAutoDemo,
pauseAutoDemo,
resumeAutoDemo,
stopAutoDemo,
updateAutoDemo,
getDemoStepSequence,
getDemoStepConfig,
setPlaybackSpeed,
toggleLoopMode,
} from './demoDirector';
import type { Scenario } from './types';
import { ITEMS } from '../data/items';
const mockScenario: Scenario = {
id: 'normal_flow',
name: 'Normal Flow',
description: 'Test scenario',
goal: 'Test auto demo',
expectedCategorySummary: 'B',
demonstrates: 'Demo director test',
items: [ITEMS[0]],
};
describe('demoDirector', () => {
describe('createDemoDirectorState', () => {
it('should create initial state', () => {
const state = createDemoDirectorState(mockScenario);
expect(state.isAutoDemoRunning).toBe(false);
expect(state.currentStep).toBe(DemoStep.intro);
expect(state.stepElapsedMs).toBe(0);
expect(state.totalElapsedMs).toBe(0);
expect(state.playbackSpeed).toBe(1);
expect(state.loopMode).toBe(false);
expect(state.paused).toBe(false);
});
});
describe('startAutoDemo', () => {
it('should start auto demo from intro', () => {
const initial = createDemoDirectorState(mockScenario);
const started = startAutoDemo(initial);
expect(started.isAutoDemoRunning).toBe(true);
expect(started.currentStep).toBe(DemoStep.intro);
expect(started.paused).toBe(false);
});
});
describe('pauseAutoDemo', () => {
it('should pause running demo', () => {
let state = createDemoDirectorState(mockScenario);
state = startAutoDemo(state);
state = pauseAutoDemo(state);
expect(state.paused).toBe(true);
expect(state.isAutoDemoRunning).toBe(true);
});
});
describe('resumeAutoDemo', () => {
it('should resume paused demo', () => {
let state = createDemoDirectorState(mockScenario);
state = startAutoDemo(state);
state = pauseAutoDemo(state);
state = resumeAutoDemo(state);
expect(state.paused).toBe(false);
expect(state.isAutoDemoRunning).toBe(true);
});
});
describe('stopAutoDemo', () => {
it('should stop demo and reset to intro', () => {
let state = createDemoDirectorState(mockScenario);
state = startAutoDemo(state);
state = stopAutoDemo(state);
expect(state.isAutoDemoRunning).toBe(false);
expect(state.paused).toBe(false);
expect(state.currentStep).toBe(DemoStep.intro);
});
});
describe('updateAutoDemo', () => {
it('should not update if not running', () => {
const state = createDemoDirectorState(mockScenario);
const updated = updateAutoDemo(state, 100);
expect(updated.stepElapsedMs).toBe(0);
});
it('should not update if paused', () => {
let state = createDemoDirectorState(mockScenario);
state = startAutoDemo(state);
state = pauseAutoDemo(state);
const updated = updateAutoDemo(state, 100);
expect(updated.stepElapsedMs).toBe(0);
});
it('should increment elapsed time', () => {
let state = createDemoDirectorState(mockScenario);
state = startAutoDemo(state);
const updated = updateAutoDemo(state, 100);
expect(updated.stepElapsedMs).toBe(100);
expect(updated.totalElapsedMs).toBe(100);
});
it('should transition to next step when duration exceeded', () => {
let state = createDemoDirectorState(mockScenario);
state = startAutoDemo(state);
const config = getDemoStepConfig(DemoStep.intro);
const updated = updateAutoDemo(state, config.durationMs + 100);
expect(updated.currentStep).toBe(DemoStep.spawn_item);
expect(updated.stepElapsedMs).toBe(0);
});
it('should stop demo when all steps completed (no loop)', () => {
let state = createDemoDirectorState(mockScenario);
state = startAutoDemo(state);
state = { ...state, currentStep: DemoStep.reset_or_next };
const config = getDemoStepConfig(DemoStep.reset_or_next);
const updated = updateAutoDemo(state, config.durationMs + 100);
expect(updated.isAutoDemoRunning).toBe(false);
});
it('should restart demo when all steps completed (loop mode)', () => {
let state = createDemoDirectorState(mockScenario);
state = startAutoDemo(state);
state = toggleLoopMode(state);
state = { ...state, currentStep: DemoStep.reset_or_next };
const config = getDemoStepConfig(DemoStep.reset_or_next);
const updated = updateAutoDemo(state, config.durationMs + 100);
expect(updated.currentStep).toBe(DemoStep.intro);
expect(updated.isAutoDemoRunning).toBe(true);
});
});
describe('getDemoStepSequence', () => {
it('should contain all key steps in order', () => {
const sequence = getDemoStepSequence();
expect(sequence).toContain(DemoStep.intro);
expect(sequence).toContain(DemoStep.spawn_item);
expect(sequence).toContain(DemoStep.detection_scan);
expect(sequence).toContain(DemoStep.dimensions_check);
expect(sequence).toContain(DemoStep.roundness_check);
expect(sequence).toContain(DemoStep.decision);
expect(sequence).toContain(DemoStep.command_sent);
expect(sequence).toContain(DemoStep.actuator_move);
expect(sequence).toContain(DemoStep.route_item);
expect(sequence).toContain(DemoStep.result);
// Verify order: command_sent must come before actuator_move
const commandIndex = sequence.indexOf(DemoStep.command_sent);
const actuatorIndex = sequence.indexOf(DemoStep.actuator_move);
expect(commandIndex).toBeLessThan(actuatorIndex);
// Verify order: actuator_move must come before route_item
const routeIndex = sequence.indexOf(DemoStep.route_item);
expect(actuatorIndex).toBeLessThan(routeIndex);
});
});
describe('getDemoStepConfig', () => {
it('should return config for each step', () => {
const config = getDemoStepConfig(DemoStep.detection_scan);
expect(config.step).toBe(DemoStep.detection_scan);
expect(config.durationMs).toBeGreaterThan(0);
expect(config.label).toBeTruthy();
expect(config.description).toBeTruthy();
expect(config.cameraPreset).toBeDefined();
expect(config.activeLabels).toBeInstanceOf(Array);
});
it('should use category for routing steps', () => {
const configC = getDemoStepConfig(DemoStep.route_item, 'C');
expect(configC.activeLabels).toContain('C');
const configD = getDemoStepConfig(DemoStep.route_item, 'D');
expect(configD.activeLabels).toContain('D');
});
});
describe('setPlaybackSpeed', () => {
it('should set playback speed', () => {
const state = createDemoDirectorState(mockScenario);
const updated = setPlaybackSpeed(state, 2);
expect(updated.playbackSpeed).toBe(2);
});
});
describe('toggleLoopMode', () => {
it('should toggle loop mode', () => {
const state = createDemoDirectorState(mockScenario);
expect(state.loopMode).toBe(false);
const toggled = toggleLoopMode(state);
expect(toggled.loopMode).toBe(true);
const toggledAgain = toggleLoopMode(toggled);
expect(toggledAgain.loopMode).toBe(false);
});
});
});

View File

@@ -1,413 +0,0 @@
/**
* Demo Director — автоматическая демонстрация работы ПАК.
* Управляет step-by-step показом: intro → spawn → detection → decision → routing → result.
*/
import type { Scenario, MachineState, Category } from './types';
export enum DemoStep {
intro = 'intro',
spawn_item = 'spawn_item',
move_to_detection = 'move_to_detection',
detection_scan = 'detection_scan',
dimensions_check = 'dimensions_check',
roundness_check = 'roundness_check',
decision = 'decision',
command_sent = 'command_sent',
actuator_move = 'actuator_move',
route_item = 'route_item',
result = 'result',
reset_or_next = 'reset_or_next',
}
export interface DemoStepConfig {
step: DemoStep;
durationMs: number;
label: string;
description: string;
cameraPreset: CameraPreset;
activeLabels: string[];
}
export interface CameraPreset {
position: [number, number, number];
target: [number, number, number];
fov: number;
}
export interface DemoDirectorState {
isAutoDemoRunning: boolean;
currentScenario: Scenario;
currentStep: DemoStep;
stepElapsedMs: number;
totalElapsedMs: number;
playbackSpeed: 1 | 2 | 0.5;
loopMode: boolean;
paused: boolean;
}
/**
* Camera presets for demo steps.
*/
export const CAMERA_PRESETS: Record<string, CameraPreset> = {
overview: {
position: [6.2, 4.8, 6.2],
target: [0, 0.3, 0],
fov: 42,
},
detectionCloseup: {
position: [-1.2, 2.5, 3.5],
target: [-1.2, 0.3, 0],
fov: 38,
},
gateCloseup: {
position: [1.6, 2.0, 3.0],
target: [1.6, 0.3, 0],
fov: 36,
},
routingB: {
position: [2.5, 3.5, 0],
target: [3.0, 0.5, 0],
fov: 40,
},
routingC: {
position: [2.5, 3.5, 2.4],
target: [2.0, 0.5, 2.4],
fov: 40,
},
routingD: {
position: [2.5, 3.5, -2.4],
target: [2.0, 0.5, -2.4],
fov: 40,
},
resultB: {
position: [3.8, 3.0, 0],
target: [3.8, 0.5, 0],
fov: 38,
},
resultC: {
position: [2.0, 2.5, 2.4],
target: [2.0, 0.5, 2.4],
fov: 38,
},
resultD: {
position: [2.0, 2.5, -2.4],
target: [2.0, 0.5, -2.4],
fov: 38,
},
};
/**
* Demo step configurations.
*/
export function getDemoStepConfig(step: DemoStep, category?: Category): DemoStepConfig {
const configs: Record<DemoStep, DemoStepConfig> = {
[DemoStep.intro]: {
step: DemoStep.intro,
durationMs: 1500,
label: 'Введение',
description: 'Обзор сортировочной ячейки A/B/C/D',
cameraPreset: CAMERA_PRESETS.overview,
activeLabels: ['A', 'B', 'C', 'D', 'Накопитель'],
},
[DemoStep.spawn_item]: {
step: DemoStep.spawn_item,
durationMs: 800,
label: 'Появление товара',
description: 'Товар входит в зону A',
cameraPreset: CAMERA_PRESETS.overview,
activeLabels: ['A'],
},
[DemoStep.move_to_detection]: {
step: DemoStep.move_to_detection,
durationMs: 1200,
label: 'Движение к камере',
description: 'Товар едет по конвейеру к зоне детекции',
cameraPreset: CAMERA_PRESETS.detectionCloseup,
activeLabels: ['A', 'Camera CV'],
},
[DemoStep.detection_scan]: {
step: DemoStep.detection_scan,
durationMs: 900,
label: 'CV детекция',
description: 'Камера сканирует товар, определяет bbox',
cameraPreset: CAMERA_PRESETS.detectionCloseup,
activeLabels: ['Camera CV', 'Laser'],
},
[DemoStep.dimensions_check]: {
step: DemoStep.dimensions_check,
durationMs: 700,
label: 'Проверка габаритов',
description: 'Dimensions: PASS or FAIL',
cameraPreset: CAMERA_PRESETS.gateCloseup,
activeLabels: ['Накопитель', 'Stop-gate'],
},
[DemoStep.roundness_check]: {
step: DemoStep.roundness_check,
durationMs: 700,
label: 'Проверка круглости',
description: 'Roundness K > 0.8 or not',
cameraPreset: CAMERA_PRESETS.gateCloseup,
activeLabels: ['Накопитель', 'Stop-gate'],
},
[DemoStep.decision]: {
step: DemoStep.decision,
durationMs: 700,
label: 'Решение',
description: 'Category: B/C/D определён',
cameraPreset: CAMERA_PRESETS.gateCloseup,
activeLabels: ['Stop-gate', 'B', 'C', 'D'],
},
[DemoStep.command_sent]: {
step: DemoStep.command_sent,
durationMs: 600,
label: 'Команда отправлена',
description: 'ROUTE_TO_* команда передана исполнительной части',
cameraPreset: CAMERA_PRESETS.gateCloseup,
activeLabels: ['Stop-gate', category ?? 'B'],
},
[DemoStep.actuator_move]: {
step: DemoStep.actuator_move,
durationMs: 1000,
label: 'Исполнительная часть',
description: 'Gate открывается или Pusher выдвигается',
cameraPreset: CAMERA_PRESETS.gateCloseup,
activeLabels: ['Stop-gate', category === 'C' ? 'Pusher C' : category === 'D' ? 'Pusher D' : 'B'],
},
[DemoStep.route_item]: {
step: DemoStep.route_item,
durationMs: 1200,
label: 'Маршрутизация',
description: 'Товар физически уходит в целевую зону',
cameraPreset: category === 'C' ? CAMERA_PRESETS.routingC : category === 'D' ? CAMERA_PRESETS.routingD : CAMERA_PRESETS.routingB,
activeLabels: [category ?? 'B'],
},
[DemoStep.result]: {
step: DemoStep.result,
durationMs: 1500,
label: 'Результат',
description: 'Товар в целевой зоне, цикл завершён',
cameraPreset: category === 'C' ? CAMERA_PRESETS.resultC : category === 'D' ? CAMERA_PRESETS.resultD : CAMERA_PRESETS.resultB,
activeLabels: [category ?? 'B'],
},
[DemoStep.reset_or_next]: {
step: DemoStep.reset_or_next,
durationMs: 500,
label: 'Сброс',
description: 'Подготовка к следующему циклу',
cameraPreset: CAMERA_PRESETS.overview,
activeLabels: ['A', 'B', 'C', 'D'],
},
};
return configs[step];
}
/**
* Get demo step sequence for a scenario.
*/
export function getDemoStepSequence(): DemoStep[] {
return [
DemoStep.intro,
DemoStep.spawn_item,
DemoStep.move_to_detection,
DemoStep.detection_scan,
DemoStep.dimensions_check,
DemoStep.roundness_check,
DemoStep.decision,
DemoStep.command_sent,
DemoStep.actuator_move,
DemoStep.route_item,
DemoStep.result,
DemoStep.reset_or_next,
];
}
/**
* Map demo step to machine state (approximation).
*/
export function mapDemoStepToMachineState(step: DemoStep): MachineState | undefined {
const mapping: Partial<Record<DemoStep, MachineState>> = {
[DemoStep.move_to_detection]: 'MOVING_TO_CAMERA',
[DemoStep.detection_scan]: 'DETECTING',
[DemoStep.dimensions_check]: 'MOVING_TO_GATE',
[DemoStep.roundness_check]: 'WAITING_AT_GATE',
[DemoStep.decision]: 'CLASSIFYING',
[DemoStep.command_sent]: 'CLASSIFYING',
[DemoStep.actuator_move]: 'ROUTE_TO_B', // will be overridden by category
[DemoStep.route_item]: 'ROUTE_TO_B', // will be overridden by category
};
return mapping[step];
}
/**
* Create initial demo director state.
*/
export function createDemoDirectorState(scenario: Scenario): DemoDirectorState {
return {
isAutoDemoRunning: false,
currentScenario: scenario,
currentStep: DemoStep.intro,
stepElapsedMs: 0,
totalElapsedMs: 0,
playbackSpeed: 1,
loopMode: false,
paused: false,
};
}
/**
* Start auto demo.
*/
export function startAutoDemo(state: DemoDirectorState): DemoDirectorState {
return {
...state,
isAutoDemoRunning: true,
currentStep: DemoStep.intro,
stepElapsedMs: 0,
totalElapsedMs: 0,
paused: false,
};
}
/**
* Pause auto demo.
*/
export function pauseAutoDemo(state: DemoDirectorState): DemoDirectorState {
return {
...state,
paused: true,
};
}
/**
* Resume auto demo.
*/
export function resumeAutoDemo(state: DemoDirectorState): DemoDirectorState {
return {
...state,
paused: false,
};
}
/**
* Stop auto demo.
*/
export function stopAutoDemo(state: DemoDirectorState): DemoDirectorState {
return {
...state,
isAutoDemoRunning: false,
paused: false,
currentStep: DemoStep.intro,
stepElapsedMs: 0,
};
}
/**
* Update auto demo state (call on each animation frame).
*/
export function updateAutoDemo(
state: DemoDirectorState,
deltaMs: number,
category?: Category,
): DemoDirectorState {
if (!state.isAutoDemoRunning || state.paused) {
return state;
}
const adjustedDelta = deltaMs * state.playbackSpeed;
const newStepElapsed = state.stepElapsedMs + adjustedDelta;
const newTotalElapsed = state.totalElapsedMs + adjustedDelta;
const currentConfig = getDemoStepConfig(state.currentStep, category);
if (newStepElapsed >= currentConfig.durationMs) {
// Move to next step
const sequence = getDemoStepSequence();
const currentIndex = sequence.indexOf(state.currentStep);
const nextIndex = currentIndex + 1;
if (nextIndex >= sequence.length) {
// Demo completed
if (state.loopMode) {
// Restart from intro
return {
...state,
currentStep: DemoStep.intro,
stepElapsedMs: 0,
totalElapsedMs: 0,
};
} else {
// Stop demo
return stopAutoDemo(state);
}
}
// Move to next step
return {
...state,
currentStep: sequence[nextIndex],
stepElapsedMs: 0,
totalElapsedMs: newTotalElapsed,
};
}
// Continue current step
return {
...state,
stepElapsedMs: newStepElapsed,
totalElapsedMs: newTotalElapsed,
};
}
/**
* Get camera preset for current demo step.
*/
export function getCameraPresetForStep(step: DemoStep, category?: Category): CameraPreset {
const config = getDemoStepConfig(step, category);
return config.cameraPreset;
}
/**
* Get active labels for current demo step.
*/
export function getActiveLabelsForStep(step: DemoStep, category?: Category): string[] {
const config = getDemoStepConfig(step, category);
return config.activeLabels;
}
/**
* Set playback speed.
*/
export function setPlaybackSpeed(state: DemoDirectorState, speed: 1 | 2 | 0.5): DemoDirectorState {
return {
...state,
playbackSpeed: speed,
};
}
/**
* Toggle loop mode.
*/
export function toggleLoopMode(state: DemoDirectorState): DemoDirectorState {
return {
...state,
loopMode: !state.loopMode,
};
}
/**
* Select scenario (reset demo).
*/
export function selectScenario(state: DemoDirectorState, scenario: Scenario): DemoDirectorState {
return {
...state,
currentScenario: scenario,
currentStep: DemoStep.intro,
stepElapsedMs: 0,
totalElapsedMs: 0,
isAutoDemoRunning: false,
paused: false,
};
}

View File

@@ -1,5 +1,5 @@
/**
* Shared industrial visual tokens for `/` continuous twin and `/details` twin.
* Shared industrial visual tokens for the continuous digital twin.
* Keeps both modes looking like projections of one system.
*/

View File

@@ -1,18 +0,0 @@
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

@@ -1,99 +0,0 @@
/**
* 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

@@ -1,32 +0,0 @@
import type { Metrics } from './types';
export function createMetrics(): Metrics {
return {
processedCount: 0,
successCount: 0,
errorCount: 0,
avgCycleTimeMs: 0,
throughputItemsPerMin: 0,
cvLatencyMs: 0,
actuatorLatencyMs: 0,
queueLength: 0,
queueDelayMs: 0,
conveyorSpeedMps: 0,
pidTargetSpeedMps: 1,
pidActualSpeedMps: 0,
};
}
export function recordCycle(metrics: Metrics, cycleTimeMs: number, success: boolean): Metrics {
const processedCount = metrics.processedCount + 1;
const totalCycleTime = metrics.avgCycleTimeMs * metrics.processedCount + cycleTimeMs;
return {
...metrics,
processedCount,
successCount: metrics.successCount + (success ? 1 : 0),
errorCount: metrics.errorCount + (success ? 0 : 1),
avgCycleTimeMs: Math.round(totalCycleTime / processedCount),
throughputItemsPerMin: Number((60000 / Math.max(cycleTimeMs, 1)).toFixed(1)),
};
}

View File

@@ -33,7 +33,6 @@ describe('performance and production hygiene', () => {
const allowed = new Set([
'../components/ThreeD/ThreeErrorBoundary.tsx',
'../pages/MainPage.tsx',
'../components/ProductDemoSection.tsx',
]);
const offenders: string[] = [];
for (const [path, text] of Object.entries(srcModules)) {

View File

@@ -1,40 +0,0 @@
import { describe, expect, it } from 'vitest';
import { createPidState, updatePid } from './pid';
import { NOMINAL_CONVEYOR_SPEED_MPS } from './simulation';
describe('PID conveyor speed imitation', () => {
it('uses 1.00 m/s as default conveyor target', () => {
expect(NOMINAL_CONVEYOR_SPEED_MPS).toBe(1);
expect(NOMINAL_CONVEYOR_SPEED_MPS.toFixed(2)).toBe('1.00');
const pid = createPidState();
expect(pid.targetSpeedMps).toBe(NOMINAL_CONVEYOR_SPEED_MPS);
});
it('moves actual speed toward target in normal mode', () => {
let pid = createPidState(1);
for (let index = 0; index < 20; index += 1) {
pid = updatePid(pid, 1, 250);
}
expect(pid.actualSpeedMps).toBeGreaterThan(0.7);
expect(Math.abs(pid.pidError)).toBeLessThan(0.35);
});
it('decays actual speed toward zero when target is stopped', () => {
let pid = createPidState(1);
for (let index = 0; index < 20; index += 1) {
pid = updatePid(pid, 1, 250);
}
const runningSpeed = pid.actualSpeedMps;
for (let index = 0; index < 30; index += 1) {
pid = updatePid(pid, 0, 250);
}
expect(pid.actualSpeedMps).toBeLessThan(runningSpeed);
expect(pid.actualSpeedMps).toBeLessThan(0.12);
});
});

View File

@@ -1,30 +0,0 @@
import type { PidState } from './types';
const PID_HISTORY_LIMIT = 40;
export function createPidState(targetSpeedMps = 1): PidState {
return {
targetSpeedMps,
actualSpeedMps: 0,
pidError: targetSpeedMps,
correction: 0,
speedHistoryMps: [0],
};
}
export function updatePid(state: PidState, targetSpeedMps: number, deltaMs: number): PidState {
const dt = Math.max(deltaMs / 1000, 0.1);
const pidError = targetSpeedMps - state.actualSpeedMps;
const correction = pidError * 0.42;
const nextActual = Math.max(0, state.actualSpeedMps + correction * dt);
const actualSpeedMps = Number(nextActual.toFixed(3));
const speedHistoryMps = [...state.speedHistoryMps, actualSpeedMps].slice(-PID_HISTORY_LIMIT);
return {
targetSpeedMps,
actualSpeedMps,
pidError: Number(pidError.toFixed(3)),
correction: Number(correction.toFixed(3)),
speedHistoryMps,
};
}

View File

@@ -1,62 +0,0 @@
/**
* 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

@@ -1,54 +0,0 @@
import { describe, it, expect } from 'vitest';
import { createSimulation, stepSimulationToNextState, setRunning, stepSimulation } from './simulation';
import { SCENARIOS } from '../data/scenarios';
function scenario(id: string) {
const s = SCENARIOS.find((x) => x.id === id);
if (!s) throw new Error(`missing scenario ${id}`);
return s;
}
describe('simulation state machine', () => {
it('classifies and routes normal item to B/C/D via classifyItem', () => {
let state = createSimulation(scenario('normal_flow'));
state = stepSimulationToNextState(state);
expect(state.machineState).toBe('MOVING_TO_CAMERA');
expect(state.currentItem).toBeDefined();
expect(['B', 'C', 'D']).toContain(state.currentItem!.classification.category);
});
it('oversized scenario routes to C', () => {
let state = createSimulation(scenario('oversized_item'));
state = stepSimulationToNextState(state);
expect(state.currentItem!.classification.category).toBe('C');
});
it('c_priority chooses C over D', () => {
let state = createSimulation(scenario('c_priority'));
state = stepSimulationToNextState(state);
expect(state.currentItem!.classification.category).toBe('C');
expect(state.currentItem!.item.roundness).toBeGreaterThan(0.8);
});
it('jam scenario enters FAULT', () => {
let state = setRunning(createSimulation(scenario('jam')), true);
state = setRunning(stepSimulationToNextState(state), true);
for (let i = 0; i < 120; i++) {
state = stepSimulation(setRunning(state, true), 100);
if (state.machineState === 'FAULT') break;
}
expect(state.machineState).toBe('FAULT');
expect(state.systemStatus).toBe('FAULT');
});
it('emergency_stop freezes system', () => {
let state = setRunning(createSimulation(scenario('emergency_stop')), true);
state = stepSimulationToNextState(state);
for (let i = 0; i < 40; i++) {
state = stepSimulation(state, 100);
if (state.machineState === 'EMERGENCY_STOP') break;
}
expect(state.machineState).toBe('EMERGENCY_STOP');
expect(state.systemStatus).toBe('EMERGENCY_STOP');
});
});

View File

@@ -1,503 +0,0 @@
import { classifyItem } from './classifier';
import { createMetrics, recordCycle } from './metrics';
import { createPidState, updatePid } from './pid';
import type {
Category,
CycleTimelineEntry,
EventLogEntry,
MachineState,
Scenario,
SimulationState,
SystemStatus,
} from './types';
export const STATE_DURATIONS_MS: Record<Exclude<MachineState, 'IDLE' | 'FAULT' | 'EMERGENCY_STOP'>, number> = {
MOVING_TO_CAMERA: 1200,
DETECTING: 900,
MOVING_TO_GATE: 1300,
WAITING_AT_GATE: 800,
CLASSIFYING: 700,
ROUTE_TO_B: 1200,
ROUTE_TO_C: 1200,
ROUTE_TO_D: 1200,
RETURN_HOME: 700,
};
export const CYCLE_STATE_ORDER: MachineState[] = [
'MOVING_TO_CAMERA',
'DETECTING',
'MOVING_TO_GATE',
'WAITING_AT_GATE',
'CLASSIFYING',
'ROUTE_TO_B',
'ROUTE_TO_C',
'ROUTE_TO_D',
'RETURN_HOME',
];
const ROUTE_STATE_BY_CATEGORY: Record<Category, MachineState> = {
B: 'ROUTE_TO_B',
C: 'ROUTE_TO_C',
D: 'ROUTE_TO_D',
};
let eventCounter = 0;
type EventInput = Omit<EventLogEntry, 'id' | 'timestampMs'>;
function event(timestampMs: number, entry: EventInput): EventLogEntry {
eventCounter += 1;
return {
id: `evt-${eventCounter}`,
timestampMs,
...entry,
};
}
function appendEvent(state: SimulationState, entry: EventInput): SimulationState {
return {
...state,
events: [event(state.simTimeMs, { state: state.machineState, ...entry }), ...state.events].slice(0, 120),
};
}
function transitionTo(state: SimulationState, nextState: MachineState): SimulationState {
const item = state.currentItem?.item;
let next: SimulationState = {
...state,
machineState: nextState,
elapsedInStateMs: 0,
activeRoute: nextState.startsWith('ROUTE_TO_') ? state.currentItem?.classification.category : undefined,
};
if (!item) {
return next;
}
if (nextState === 'DETECTING') {
next = appendEvent(next, {
itemId: item.id,
type: 'sensor',
message: `Camera bbox ${item.dimensionsMm.width}x${item.dimensionsMm.depth} mm, confidence ${Math.round(item.confidence * 100)}%`,
category: state.currentItem?.classification.category,
command: 'CAMERA_CAPTURE',
state: nextState,
status: item.confidence < 0.65 ? 'warning' : 'info',
});
}
if (nextState === 'WAITING_AT_GATE') {
next = appendEvent(next, {
itemId: item.id,
type: 'actuator',
message: 'Stop-gate closed, item fixed before classification',
command: 'GATE_CLOSE',
state: nextState,
status: 'info',
});
}
if (nextState === 'CLASSIFYING' && state.currentItem) {
next = appendEvent(next, {
itemId: item.id,
type: 'classification',
message: `${state.currentItem.classification.label}: ${state.currentItem.classification.reason}`,
category: state.currentItem.classification.category,
command: 'CLASSIFY_RULE_BASED',
state: nextState,
status: state.currentItem.classification.warnings.length > 0 ? 'warning' : 'success',
});
}
if (nextState.startsWith('ROUTE_TO_') && state.currentItem) {
next = appendEvent(next, {
itemId: item.id,
type: 'routing',
message: `Route selected: ${state.currentItem.classification.category}`,
category: state.currentItem.classification.category,
command: nextState,
state: nextState,
status: 'success',
});
}
return next;
}
function startNextItem(state: SimulationState): SimulationState {
const item = state.scenario.items[state.itemIndex];
if (!item) {
return { ...state, machineState: 'IDLE', running: false, systemStatus: 'PAUSED', currentItem: undefined };
}
const classification = classifyItem(item);
let next: SimulationState = {
...state,
currentItem: {
item,
classification,
startedAtMs: state.simTimeMs,
cycleTimeMs: 0,
},
machineState: 'MOVING_TO_CAMERA',
elapsedInStateMs: 0,
activeRoute: undefined,
itemIndex: state.itemIndex + 1,
};
next = appendEvent(next, {
itemId: item.id,
type: 'system',
message: `Item entered zone A: ${item.name}`,
command: 'FEED_ITEM',
state: 'MOVING_TO_CAMERA',
status: 'info',
});
if (state.scenario.id === 'close_items' && state.itemIndex === 0) {
next = appendEvent(next, {
itemId: item.id,
type: 'warning',
message: 'Queue/spacing warning: next item detected too close, processing sequentially',
command: 'QUEUE_HOLD_NEXT_ITEM',
state: 'MOVING_TO_CAMERA',
status: 'warning',
});
}
for (const warning of classification.warnings) {
next = appendEvent(next, {
itemId: item.id,
type: 'warning',
message: warning,
category: classification.category,
command: 'RULE_BASED_FALLBACK',
state: 'MOVING_TO_CAMERA',
status: 'warning',
});
}
return next;
}
function completeCurrentItem(state: SimulationState): SimulationState {
if (!state.currentItem) {
return state;
}
const cycleTimeMs = state.simTimeMs - state.currentItem.startedAtMs;
const success = state.currentItem.classification.category === state.currentItem.item.expectedCategory;
const metrics = recordCycle(state.metrics, cycleTimeMs, success);
let next = appendEvent(
{
...state,
currentItem: {
...state.currentItem,
cycleTimeMs,
},
metrics,
},
{
itemId: state.currentItem.item.id,
type: 'routing',
message: `Cycle completed in ${(cycleTimeMs / 1000).toFixed(1)}s`,
category: state.currentItem.classification.category,
command: 'CYCLE_COMPLETE',
status: success ? 'success' : 'error',
},
);
next = {
...next,
activeRoute: undefined,
};
return transitionTo(next, 'RETURN_HOME');
}
/** OZON Track 3 nominal conveyor speed (m/s). */
export const NOMINAL_CONVEYOR_SPEED_MPS = 1;
function targetSpeedFor(state: SimulationState): number {
if (state.machineState === 'FAULT' || state.machineState === 'EMERGENCY_STOP') {
return 0;
}
if (!state.running) {
return 0;
}
return state.scenario.id === 'close_items' ? 0.75 : NOMINAL_CONVEYOR_SPEED_MPS;
}
function deriveSensorsAndActuators(state: SimulationState): SimulationState {
const item = state.currentItem?.item;
const classification = state.currentItem?.classification;
const cameraActive = state.machineState === 'DETECTING';
const laserActive = state.machineState === 'DETECTING' || state.machineState === 'MOVING_TO_GATE';
const ultrasoundActive = state.machineState === 'WAITING_AT_GATE' || state.machineState === 'CLASSIFYING';
const route = classification?.category;
const routeToC = state.machineState === 'ROUTE_TO_C';
const routeToD = state.machineState === 'ROUTE_TO_D';
return {
...state,
gate: {
open: state.machineState === 'ROUTE_TO_B' || state.machineState === 'IDLE',
},
actuators: {
pusherC: routeToC ? 'extended' : state.machineState === 'RETURN_HOME' && route === 'C' ? 'retracting' : 'idle',
pusherD: routeToD ? 'extended' : state.machineState === 'RETURN_HOME' && route === 'D' ? 'retracting' : 'idle',
},
sensors: {
camera: {
kind: 'camera',
label: 'Camera / pseudo-CV',
active: cameraActive,
lastValue: item ? `bbox ${item.dimensionsMm.width}x${item.dimensionsMm.depth} mm` : 'idle',
latencyMs: item ? Math.round(38 + (1 - item.confidence) * 80) : 0,
lastEventTimestampMs: cameraActive ? state.simTimeMs : state.sensors.camera.lastEventTimestampMs,
bbox: item ? { x: 0, y: 0, width: item.dimensionsMm.width, height: item.dimensionsMm.depth } : undefined,
confidence: item?.confidence,
cvLatencyMs: item ? Math.round(38 + (1 - item.confidence) * 80) : 0,
},
laser: {
kind: 'laser',
label: 'Laser height sensor',
active: laserActive,
lastValue: item ? `${item.dimensionsMm.height} mm` : 'idle',
latencyMs: item ? 14 : 0,
lastEventTimestampMs: laserActive ? state.simTimeMs : state.sensors.laser.lastEventTimestampMs,
measuredHeightMm: item?.dimensionsMm.height,
},
ultrasound: {
kind: 'ultrasound',
label: 'Ultrasound gate sensor',
active: ultrasoundActive,
lastValue: ultrasoundActive ? 'object at gate' : item ? 'tracking' : 'idle',
latencyMs: item ? 22 : 0,
lastEventTimestampMs: ultrasoundActive ? state.simTimeMs : state.sensors.ultrasound.lastEventTimestampMs,
distanceToGateMm: ultrasoundActive ? 0 : item ? 900 : undefined,
objectAtGate: ultrasoundActive,
},
},
};
}
export function createSimulation(scenario: Scenario): SimulationState {
const pid = createPidState();
return deriveSensorsAndActuators({
scenario,
systemStatus: 'PAUSED',
running: false,
machineState: 'IDLE',
itemIndex: 0,
elapsedInStateMs: 0,
simTimeMs: 0,
currentItem: undefined,
metrics: createMetrics(),
sensors: {
camera: {
kind: 'camera',
label: 'Camera / pseudo-CV',
active: false,
lastValue: 'idle',
latencyMs: 0,
lastEventTimestampMs: 0,
cvLatencyMs: 0,
},
laser: {
kind: 'laser',
label: 'Laser height sensor',
active: false,
lastValue: 'idle',
latencyMs: 0,
lastEventTimestampMs: 0,
},
ultrasound: {
kind: 'ultrasound',
label: 'Ultrasound gate sensor',
active: false,
lastValue: 'idle',
latencyMs: 0,
lastEventTimestampMs: 0,
objectAtGate: false,
},
},
gate: { open: true },
actuators: { pusherC: 'idle', pusherD: 'idle' },
pid,
events: [],
});
}
export function setRunning(state: SimulationState, running: boolean): SimulationState {
const systemStatus: SystemStatus = state.machineState === 'FAULT' ? 'FAULT' : state.machineState === 'EMERGENCY_STOP' ? 'EMERGENCY_STOP' : running ? 'RUNNING' : 'PAUSED';
return deriveSensorsAndActuators({ ...state, running, systemStatus });
}
export function stepSimulation(state: SimulationState, deltaMs: number, forceStep = false): SimulationState {
if (!state.running && !forceStep) {
return state;
}
let next: SimulationState = {
...state,
simTimeMs: state.simTimeMs + deltaMs,
elapsedInStateMs: state.elapsedInStateMs + deltaMs,
};
const shouldEmergencyStop = next.scenario.id === 'emergency_stop' && next.simTimeMs >= 1800;
if (shouldEmergencyStop && next.machineState !== 'EMERGENCY_STOP') {
next = appendEvent(next, {
itemId: next.currentItem?.item.id,
type: 'fault',
message: 'Emergency stop pressed, all movement stopped',
command: 'EMERGENCY_STOP',
status: 'error',
});
next = { ...next, machineState: 'EMERGENCY_STOP', running: false, systemStatus: 'EMERGENCY_STOP' };
}
const shouldJam = next.scenario.id === 'jam' && next.machineState === 'WAITING_AT_GATE' && next.elapsedInStateMs >= 700;
if (shouldJam) {
next = appendEvent(next, {
itemId: next.currentItem?.item.id,
type: 'fault',
message: 'Jam detected at stop-gate, conveyor stopped',
category: next.currentItem?.classification.category,
command: 'CONVEYOR_STOP_FAULT',
status: 'error',
});
next = { ...next, machineState: 'FAULT', running: false, systemStatus: 'FAULT' };
}
if (next.machineState === 'FAULT' || next.machineState === 'EMERGENCY_STOP') {
const pid = updatePid(next.pid, 0, deltaMs);
return deriveSensorsAndActuators({
...next,
pid,
metrics: {
...next.metrics,
conveyorSpeedMps: pid.actualSpeedMps,
pidTargetSpeedMps: pid.targetSpeedMps,
pidActualSpeedMps: pid.actualSpeedMps,
},
});
}
if (next.machineState === 'IDLE') {
next = startNextItem(next);
}
const duration = next.machineState in STATE_DURATIONS_MS ? STATE_DURATIONS_MS[next.machineState as keyof typeof STATE_DURATIONS_MS] : undefined;
if (duration && next.elapsedInStateMs >= duration) {
switch (next.machineState) {
case 'MOVING_TO_CAMERA':
next = transitionTo(next, 'DETECTING');
break;
case 'DETECTING':
next = transitionTo(next, 'MOVING_TO_GATE');
break;
case 'MOVING_TO_GATE':
next = transitionTo(next, 'WAITING_AT_GATE');
break;
case 'WAITING_AT_GATE':
next = transitionTo(next, 'CLASSIFYING');
break;
case 'CLASSIFYING':
if (next.currentItem) {
next = transitionTo(next, ROUTE_STATE_BY_CATEGORY[next.currentItem.classification.category]);
}
break;
case 'ROUTE_TO_B':
case 'ROUTE_TO_C':
case 'ROUTE_TO_D':
next = completeCurrentItem(next);
break;
case 'RETURN_HOME':
next = next.itemIndex < next.scenario.items.length ? startNextItem(next) : { ...next, currentItem: undefined, machineState: 'IDLE', running: false, systemStatus: 'PAUSED', elapsedInStateMs: 0 };
break;
default:
break;
}
}
const targetSpeed = targetSpeedFor(next);
const pid = updatePid(next.pid, targetSpeed, deltaMs);
const queueLength = Math.max(next.scenario.items.length - next.itemIndex, 0) + (next.currentItem ? 1 : 0);
const cvLatencyMs = next.sensors.camera.cvLatencyMs || next.metrics.cvLatencyMs;
const actuatorLatencyMs = next.actuators.pusherC !== 'idle' || next.actuators.pusherD !== 'idle' ? 115 : next.machineState === 'ROUTE_TO_B' ? 55 : 0;
const queueDelayMs = next.scenario.id === 'close_items' && queueLength > 1 ? 450 : 0;
next = {
...next,
pid,
systemStatus: next.running ? 'RUNNING' : next.systemStatus,
metrics: {
...next.metrics,
cvLatencyMs,
actuatorLatencyMs,
queueLength,
queueDelayMs,
conveyorSpeedMps: pid.actualSpeedMps,
pidTargetSpeedMps: pid.targetSpeedMps,
pidActualSpeedMps: pid.actualSpeedMps,
},
};
return deriveSensorsAndActuators(next);
}
export function stepSimulationToNextState(state: SimulationState): SimulationState {
if (state.machineState === 'FAULT' || state.machineState === 'EMERGENCY_STOP') {
return state;
}
const runningState = setRunning({ ...state, running: true, systemStatus: 'RUNNING' }, true);
let deltaMs = 1;
if (runningState.scenario.id === 'emergency_stop') {
deltaMs = Math.max(1, 1800 - runningState.simTimeMs);
} else if (runningState.scenario.id === 'jam' && runningState.machineState === 'WAITING_AT_GATE') {
deltaMs = Math.max(1, 700 - runningState.elapsedInStateMs);
} else if (runningState.machineState in STATE_DURATIONS_MS) {
const duration = STATE_DURATIONS_MS[runningState.machineState as keyof typeof STATE_DURATIONS_MS];
deltaMs = Math.max(1, duration - runningState.elapsedInStateMs);
}
const stepped = stepSimulation(runningState, deltaMs, true);
return setRunning(stepped, false);
}
export function buildCycleTimeline(state: SimulationState): CycleTimelineEntry[] {
const current = state.currentItem;
const activeRoute = current ? ROUTE_STATE_BY_CATEGORY[current.classification.category] : undefined;
let cursor = current?.startedAtMs ?? state.simTimeMs;
return CYCLE_STATE_ORDER.map((machineState) => {
const isRouteState = machineState.startsWith('ROUTE_TO_');
const skipped = isRouteState && machineState !== activeRoute;
const durationMs = STATE_DURATIONS_MS[machineState as keyof typeof STATE_DURATIONS_MS] ?? 0;
const startedAtMs = current && !skipped ? cursor : undefined;
let status: CycleTimelineEntry['status'] = current ? 'pending' : 'pending';
if (skipped) {
status = 'skipped';
} else if (current && machineState === state.machineState) {
status = 'active';
} else if (current && startedAtMs !== undefined && state.simTimeMs >= startedAtMs + durationMs) {
status = 'done';
}
if (!skipped) {
cursor += durationMs;
}
return {
state: machineState,
startedAtMs,
durationMs,
status,
};
});
}

View File

@@ -1,60 +0,0 @@
/**
* Stage 1 — physical contact contracts.
*
* Verifies the bottom-contact guarantee for real models:
* - continuous scene: pose center = surfaceY + h/2, mesh bottom-center pivot
* offset −h/2 → model bottom touches the surface exactly (epsilon 0).
* - details scene: itemPosition3D y == beltY (bottom-contact semantics,
* no 12cm float, no 2.5x visual multiplier).
*/
import { describe, it, expect } from 'vitest';
import { getPhysicalItemPose } from './physicalItemMotion';
import { BELT_TOP_Y, CAGE_FLOOR_Y } from './physicalLayout';
import { itemPosition3D, TWIN_LAYOUT } from '../components/ThreeD/itemMotion';
import { ITEMS } from '../data/items';
import type { SimulationState } from './types';
describe('Stage 1 belt/cage contact contracts', () => {
const box = ITEMS.find((i) => i.id === 'SKU-001')!;
it('item center on main belt is surfaceY + h/2 (bottom touches with bottom-center pivot)', () => {
const pose = getPhysicalItemPose({
caseId: 'case-001',
dimensionsMm: box.dimensionsMm,
targetCategory: 'B',
elapsedMs: 500, // feed phase
});
const itemHeightM = box.dimensionsMm.height / 1000;
expect(pose.surface).toBe('main_belt');
expect(pose.position[1]).toBeCloseTo(BELT_TOP_Y + itemHeightM / 2, 6);
// bottom-center pivot at −h/2 → bottom at BELT_TOP_Y (contact epsilon = 0)
expect(pose.position[1] - itemHeightM / 2).toBeCloseTo(BELT_TOP_Y, 6);
});
it('settled item in C cage rests on the cage floor, not through it', () => {
const pose = getPhysicalItemPose({
caseId: 'case-004',
slotIndex: 0,
dimensionsMm: box.dimensionsMm,
targetCategory: 'C',
elapsedMs: Number.MAX_SAFE_INTEGER / 4, // settled
});
const itemHeightM = box.dimensionsMm.height / 1000;
expect(pose.surface).toBe('c_cage_floor');
expect(pose.position[1] - itemHeightM / 2).toBeCloseTo(CAGE_FLOOR_Y, 6);
});
it('details scene uses bottom-contact belt height (no visual float)', () => {
const sim = { machineState: 'IDLE', elapsedInStateMs: 0 } as SimulationState;
const [, y] = itemPosition3D(sim);
expect(y).toBeCloseTo(TWIN_LAYOUT.beltY, 6);
expect(y).toBeCloseTo(BELT_TOP_Y, 6);
});
it('details scene has no VISUAL_SCALE_MULTIPLIER distortion (true physical scale)', async () => {
// Static guard: the multiplier must not be reintroduced.
const source = await import('../components/ThreeD/Item3D.tsx?raw');
expect(source.default).not.toMatch(/VISUAL_SCALE_MULTIPLIER\s*=/);
expect(source.default).toMatch(/getRenderedItemDimensions/);
});
});

View File

@@ -32,13 +32,12 @@ describe('Stage 2C CAD assembly params', () => {
expect(aabb.max[1]).toBeLessThan(0.8);
});
it('runtime loads conveyor-clean.glb and does not mount generated mechanism assets', () => {
it('runtime loads conveyor-clean.glb as the sole conveyor asset URL', () => {
expect(conveyorSource).toMatch(
/CONVEYOR_CAD_URL\s*=\s*['"]\/models\/sorter\/conveyor-clean\.glb['"]/,
);
expect(conveyorSource).not.toMatch(/mechanism-final\.glb/);
expect(conveyorSource).not.toMatch(/mechanism-mount-final\.glb/);
expect(conveyorSource).not.toMatch(/conveyor-web\.glb/);
const urls = [...conveyorSource.matchAll(/['"]\/models\/sorter\/[^'"]+['"]/g)].map((m) => m[0]);
expect(urls.every((u) => u.includes('conveyor-clean.glb'))).toBe(true);
});
});

View File

@@ -1,30 +1,30 @@
import AppNav from '../components/AppNav';
import {
CONFIRMED_COMPONENT_POLICY,
CAD_PROVENANCE,
CLASSIFIER_BOUNDS,
CONFIRMED_LAYOUT,
CURRENT_BLOCKERS,
DATA_ACQUISITION_SEQUENCE,
GATE_STATUS_BOARD,
OWNER_INPUT_FORM_NOTE,
CURRENT_LIMITATIONS,
DIVERTER_KINEMATICS,
OFFICIAL_SOURCE_MATRIX,
PHYSICS_STATUS,
PRODUCTION_STATUS,
ROLLER_DIAMETER_CONFLICT,
ROUTE_MAPPING,
RUNTIME_FLOW,
VALIDATION_BOARD,
} from '../data/productionStatusSummary';
const SECTIONS = [
{ id: 'about', title: '1. О проекте' },
{ id: 'simulation', title: '2. Веб-симуляция' },
{ id: 'production-goal', title: '3. Производственная цель' },
{ id: 'architecture', title: '4. Архитектура системы' },
{ id: 'author-cad', title: '5. Авторский CAD' },
{ id: 'diverter', title: '6. Производственный diverter' },
{ id: 'electronics', title: '7. Электроника и BOM' },
{ id: 'sensors', title: '8. Датчики' },
{ id: 'motor-encoder', title: '9. Двигатель и энкодер' },
{ id: 'production-inputs', title: '10. Производственные исходные данные' },
{ id: 'blockers', title: '11. Текущие блокеры' },
{ id: 'measurement-pack', title: '12. Пакет обмеров' },
{ id: 'gates', title: '13. Статусы Gate' },
{ id: 'limits', title: '14. Ограничения и допущения' },
{ id: 'about', title: '1. Цель проекта' },
{ id: 'runtime-flow', title: '2. Runtime flow' },
{ id: 'layout', title: '3. Активная линия' },
{ id: 'classifier', title: '4. Классификация' },
{ id: 'routes', title: '5. Маршруты B/C/D' },
{ id: 'diverter', title: '6. Diverter state machine' },
{ id: 'cad', title: '7. CAD provenance' },
{ id: 'physics', title: '8. Физика' },
{ id: 'validation', title: '9. Validation status' },
{ id: 'official', title: '10. Official-source matrix' },
{ id: 'limits', title: '11. Known limitations' },
] as const;
function TocList({ onNavigate }: { onNavigate?: () => void }) {
@@ -75,7 +75,7 @@ export default function DocumentationPage() {
</span>
<div>
<h1 className="docs-title">Документация</h1>
<p className="docs-subtitle">OZON Tech Sorter — проектная и инженерная сводка</p>
<p className="docs-subtitle">Текущее состояние веб-симуляции и инженерный статус</p>
</div>
</div>
<AppNav variant="solid" />
@@ -98,165 +98,162 @@ export default function DocumentationPage() {
<main className="docs-main">
<section className="docs-status-banner" data-testid="docs-production-status">
<div className="docs-status-label">Текущий производственный статус</div>
<div className="docs-status-label">Текущий статус</div>
<div className="docs-status-value">{PRODUCTION_STATUS.acquisitionPackStatus}</div>
<p className="docs-status-note">
Пакет сбора данных готов. Это не означает готовность production design, выбор двигателя,
энкодера, утверждение diverter или готовность CAD.
Web twin: {PRODUCTION_STATUS.webTwinStatus}. Unit tests {PRODUCTION_STATUS.unitTests},
build {PRODUCTION_STATUS.productionBuild}. Contact physics:{' '}
{PRODUCTION_STATUS.contactPhysics}. Official compliance:{' '}
{PRODUCTION_STATUS.officialCompliance}.
</p>
</section>
<section id="about" className="docs-section">
<h2>{SECTIONS[0].title}</h2>
<p>
Проект — цифровой двойник и инженерный контур линии сортировки Ozon Tech Sorter:
конвейер, классификация товаров по категориям B/C/D, stop-gate и будущий производственный
diverter. Веб-интерфейс показывает непрерывную симуляцию; производственный CAD diverter
пока не создан.
Цифровой двойник линии сортировки Ozon Tech: конвейер, камера/классификация, физическая
маршрутизация и три приёмные категории (B / C / D). Страница <code>/</code> — рабочая
веб-симуляция; эта страница — каноническая сводка текущего состояния.
</p>
</section>
<section id="simulation" className="docs-section">
<section id="runtime-flow" className="docs-section">
<h2>{SECTIONS[1].title}</h2>
<p>
Главная страница <code>/</code> — действующая веб-симуляция: CAD-конвейер, товары, движение,
классификация, маршруты B/C/D, камеры и элементы управления. Runtime опирается на
подтверждённую геометрию twin и не заменяет физический обмер линии.
</p>
<p>{RUNTIME_FLOW.join(' → ')}</p>
</section>
<section id="production-goal" className="docs-section">
<section id="layout" className="docs-section">
<h2>{SECTIONS[2].title}</h2>
<p>
Цель — промышленная линия в рабочей зоне{' '}
<strong>
{CONFIRMED_LAYOUT.workspaceMm.length} × {CONFIRMED_LAYOUT.workspaceMm.width} мм
</strong>
, конвейер шириной {CONFIRMED_LAYOUT.conveyorWidthMm} мм и высотой верха ленты{' '}
{CONFIRMED_LAYOUT.conveyorHeightMm} мм. Web digital twin должен в дальнейшем
генерироваться из production CAD, а не из неподтверждённых допущений.
</p>
</section>
<section id="architecture" className="docs-section">
<h2>{SECTIONS[3].title}</h2>
<ul>
<li>Источник геометрии конвейера — авторский CAD / замороженный GLB twin.</li>
<li>Классификация и маршрутизация — domain-логика симуляции (не меняется этой UI-задачей).</li>
<li>Link027 / Link029 — роль <strong>{CONFIRMED_LAYOUT.link027029Role}</strong>, не diverter.</li>
<li>Авторский CAD diverter: <strong>{CONFIRMED_LAYOUT.authorDiverter}</strong>.</li>
<li>
Последовательность данных: {DATA_ACQUISITION_SEQUENCE.join(' → ')}.
Рабочая зона (чертёж): {CONFIRMED_LAYOUT.workspaceMm.length} ×{' '}
{CONFIRMED_LAYOUT.workspaceMm.width} мм; лента {CONFIRMED_LAYOUT.conveyorWidthMm} мм /
высота верха {CONFIRMED_LAYOUT.conveyorHeightMm} мм.
</li>
<li>Модули CAD: {CONFIRMED_LAYOUT.modules.join(', ')}.</li>
<li>Приёмники: {CONFIRMED_LAYOUT.receivers.join(', ')}.</li>
</ul>
</section>
<section id="author-cad" className="docs-section">
<h2>{SECTIONS[4].title}</h2>
<section id="classifier" className="docs-section">
<h2>{SECTIONS[3].title}</h2>
<p>
Авторский файл конвейера <code>3d_models/conveer.FCStd</code> и runtime GLB{' '}
<code>public/models/sorter/conveyor-clean.glb</code> заморожены по checksum. Изменения
байтов этих файлов в рамках UI-задачи запрещены. Point A по чертежу: центр линии на
{` ${CONFIRMED_LAYOUT.pointACenterlineFromWorkspaceBottomMm} мм`} от низа рабочей зоны;
Point A X, junction и ROOT_BIND требуют физического подтверждения.
Status: <code>{CLASSIFIER_BOUNDS.status}</code>
</p>
<ul>
<li>Min: {CLASSIFIER_BOUNDS.display.min}</li>
<li>Max: {CLASSIFIER_BOUNDS.display.max}</li>
<li>Roundness: {CLASSIFIER_BOUNDS.display.roundness}</li>
<li>Order: {CLASSIFIER_BOUNDS.checkOrder}</li>
</ul>
<p>
OFFICIAL_SOURCE_REFERENCE: <code>{CLASSIFIER_BOUNDS.officialSourceReference}</code>
{CLASSIFIER_BOUNDS.officialSourceParsedThisPass
? ''
: ' — PDF not re-parsed in this documentation pass; bounds match current code/tests.'}
</p>
</section>
<section id="routes" className="docs-section">
<h2>{SECTIONS[4].title}</h2>
<div className="docs-table-scroll">
<table className="docs-table">
<thead>
<tr>
<th>Category</th>
<th>Physical route</th>
<th>CAD diverter</th>
<th>Angle</th>
</tr>
</thead>
<tbody>
{ROUTE_MAPPING.map((row) => (
<tr key={row.category}>
<td>{row.category}</td>
<td>
<code>{row.physicalRoute}</code>
</td>
<td>{row.activeDiverter}</td>
<td>{row.signedAngleDeg}°</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
<section id="diverter" className="docs-section">
<h2>{SECTIONS[5].title}</h2>
<p>
Производственный CAD diverter создавать нельзя, пока не заполнены обмеры и не сняты
геометрические блокеры. Линейный angled pusher отклонён; rotary swing-arm остаётся
кандидатом и не утверждён. Архитектура diverter на этой странице не выбирается.
</p>
</section>
<section id="electronics" className="docs-section">
<h2>{SECTIONS[6].title}</h2>
<p>
Gate 2C (production electrical): статус{' '}
<code>{PRODUCTION_STATUS.electricalGateStatus}</code>. В текущем BOM нет принятых
production-компонентов; прототипные позиции (в т.ч. MG996R) не переносятся в production
без замены. Силовая архитектура и шкаф требуют измерений и решений владельца.
</p>
</section>
<section id="sensors" className="docs-section">
<h2>{SECTIONS[7].title}</h2>
<p>
VL53L0X: <strong>{CONFIRMED_COMPONENT_POLICY.vl53l0x}</strong> — не использовать как
производственный или safety-датчик. Производственная сенсорика не зафиксирована.
</p>
</section>
<section id="motor-encoder" className="docs-section">
<h2>{SECTIONS[8].title}</h2>
<p>{DIVERTER_KINEMATICS.phases.join(' → ')}</p>
<ul>
<li>Двигатель / редуктор / драйвер: {CONFIRMED_COMPONENT_POLICY.productionMotor}.</li>
<li>Энкодер: {CONFIRMED_COMPONENT_POLICY.productionEncoder} (BLOCKED_BY_MOTOR_SPEC).</li>
<li>MG996R: {CONFIRMED_COMPONENT_POLICY.mg996r}.</li>
<li>Rotation duration: {DIVERTER_KINEMATICS.rotationDurationSec.toFixed(2)} s</li>
<li>Safety margin: {DIVERTER_KINEMATICS.openingSafetyMarginSec.toFixed(2)} s</li>
<li>Contact plane S: {DIVERTER_KINEMATICS.contactPlaneS}</li>
<li>Clear plane S: {DIVERTER_KINEMATICS.clearPlaneS.toFixed(4)}</li>
<li>Route command bound to productId; one active product at a time</li>
<li>Close after rear-clear of clear plane</li>
<li>
Invented sorter drive mesh active:{' '}
{DIVERTER_KINEMATICS.generatedMechanismActive ? 'YES' : 'NO'}
</li>
</ul>
<p>
Выбор коммерческой модели двигателя или энкодера на этой странице не выполняется —
сначала заполняется форма идентификации двигателя из пакета обмеров.
</p>
</section>
<section id="production-inputs" className="docs-section">
<h2>{SECTIONS[9].title}</h2>
<p>{OWNER_INPUT_FORM_NOTE}</p>
<p>
Подтверждённые размеры рабочей зоны и конвейера см. выше. Неподтверждённые величины
(диаметры роликов после обмера, массы SKU, токи, safety PL/SIL) не выдаются за факты.
</p>
<div className="docs-conflict" data-testid="docs-roller-conflict">
<strong>Конфликт диаметров роликов</strong>
<ul>
<li>Author CAD idler: {ROLLER_DIAMETER_CONFLICT.authorCadIdlerMm} мм</li>
<li>Runtime idler: {ROLLER_DIAMETER_CONFLICT.runtimeIdlerMm} мм</li>
<li>Runtime drive: {ROLLER_DIAMETER_CONFLICT.runtimeDriveMm} мм</li>
</ul>
<p>Статус: {ROLLER_DIAMETER_CONFLICT.status} — требуется физический обмер.</p>
</div>
<section id="cad" className="docs-section">
<h2>{SECTIONS[6].title}</h2>
<ul>
<li>
Author: <code>{CAD_PROVENANCE.authorFcstd}</code>
<br />
SHA-256: <code>{CAD_PROVENANCE.authorSha256}</code>
</li>
<li>
Runtime: <code>{CAD_PROVENANCE.runtimeGlb}</code>
<br />
SHA-256: <code>{CAD_PROVENANCE.runtimeSha256}</code>
</li>
<li>Author servo/holder nodes used in sorter module only.</li>
<li>Invented sorter drive mesh inactive; author CAD diverters only.</li>
<li>Horn / transmission in GLB: {CAD_PROVENANCE.hornTransmissionInGlb}.</li>
</ul>
</section>
<section id="blockers" className="docs-section" data-testid="docs-blockers">
<h2>{SECTIONS[10].title}</h2>
<ul className="docs-blocker-list">
{CURRENT_BLOCKERS.map((b) => (
<li key={b}>{b}</li>
<section id="physics" className="docs-section">
<h2>{SECTIONS[7].title}</h2>
<h3>IMPLEMENTED</h3>
<ul>
{PHYSICS_STATUS.implemented.map((x) => (
<li key={x}>{x}</li>
))}
</ul>
<h3>NOT FULLY VALIDATED</h3>
<ul>
{PHYSICS_STATUS.notFullyValidated.map((x) => (
<li key={x}>{x}</li>
))}
</ul>
<h3>PLANNED</h3>
<ul>
{PHYSICS_STATUS.planned.map((x) => (
<li key={x}>{x}</li>
))}
</ul>
</section>
<section id="measurement-pack" className="docs-section">
<h2>{SECTIONS[11].title}</h2>
<p>
Gate 2D подготовил пакет: протокол обмеров, контрольные точки P0–P12, shot list фото,
формы двигателя / энкодера / SKU / скорости / throughput / power / safety и главный{' '}
<code>OWNER_PRODUCTION_INPUT_FORM</code>. Статус пакета:{' '}
<strong>{PRODUCTION_STATUS.acquisitionPackStatus}</strong>.
</p>
<p>
Артефакты пакета хранятся вне публичного runtime (ignored path) и не подключаются из
браузера напрямую.
</p>
</section>
<section id="gates" className="docs-section" data-testid="docs-gates">
<h2>{SECTIONS[12].title}</h2>
<section id="validation" className="docs-section" data-testid="docs-gates">
<h2>{SECTIONS[8].title}</h2>
<div className="docs-table-scroll" data-testid="docs-table-scroll">
<table className="docs-table">
<thead>
<tr>
<th>Gate</th>
<th>Check</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{GATE_STATUS_BOARD.map((row) => (
<tr key={row.gate}>
<td>{row.gate}</td>
{VALIDATION_BOARD.map((row) => (
<tr key={row.item}>
<td>{row.item}</td>
<td>
<code>{row.status}</code>
</td>
@@ -267,14 +264,42 @@ export default function DocumentationPage() {
</div>
</section>
<section id="limits" className="docs-section">
<h2>{SECTIONS[13].title}</h2>
<ul>
<li>Неутверждённые значения runtime не считаются production truth.</li>
<li>MG996R и VL53L0X не являются production/safety решениями.</li>
<li>Production CAD diverter и Gate 3 не начаты.</li>
<li>Расчёты на неподтверждённых диаметрах роликов / ROOT_BIND запрещены.</li>
<li>Эта страница — сводка; она не заменяет заполненный owner measurement pack.</li>
<section id="official" className="docs-section">
<h2>{SECTIONS[9].title}</h2>
<div className="docs-table-scroll">
<table className="docs-table">
<thead>
<tr>
<th>SOURCE</th>
<th>PURPOSE</th>
<th>PRESENT</th>
<th>CANONICAL</th>
<th>USAGE</th>
</tr>
</thead>
<tbody>
{OFFICIAL_SOURCE_MATRIX.map((row) => (
<tr key={row.source}>
<td>
<code>{row.source}</code>
</td>
<td>{row.purpose}</td>
<td>{row.present ? 'YES' : 'NO'}</td>
<td>{row.canonical ? 'YES' : 'NO'}</td>
<td>{row.usage}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
<section id="limits" className="docs-section" data-testid="docs-blockers">
<h2>{SECTIONS[10].title}</h2>
<ul className="docs-blocker-list">
{CURRENT_LIMITATIONS.map((b) => (
<li key={b}>{b}</li>
))}
</ul>
</section>
</main>