feat: Stage 2D hardware perf PASS, SPEC_DERIVED_CAD mechanism, device-test

Measure GTX 1080 matrix (A/B/C 60 FPS p95~17ms); selective CAD shadows and
DPR 1.25; ship SPEC_DERIVED_CAD sorter mechanism GLB/STEP; add /device-test;
document domain blocker and phone NOT_TESTED.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Даня Архипов
2026-07-30 13:01:44 +00:00
parent 68327635ce
commit 014a46077d
53 changed files with 1614 additions and 53 deletions

View File

@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import MainPage from './pages/MainPage';
import DetailsPage from './pages/DetailsPage';
import DeviceTestPage from './pages/DeviceTestPage';
import { DEMO_STEPS } from './data/demoSteps';
import { SCENARIOS } from './data/scenarios';
import { createSimulation, stepSimulationToNextState, setRunning } from './domain/simulation';
@@ -302,6 +303,7 @@ function AppContent() {
/>
}
/>
<Route path="/device-test" element={<DeviceTestPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
);

View File

@@ -109,7 +109,15 @@ export function ConveyorCadModel({
if (!mesh.isMesh) return;
const name = mesh.name || mesh.parent?.name || '';
mesh.material = materialFor(slotFor(name));
mesh.castShadow = shadows;
// Stage 2D: shadow casters limited to large structure (not every roller/bolt).
const cast =
shadows &&
(name.startsWith('static-frame/') ||
name.startsWith('conveyor-belt/') ||
name.startsWith('stop-gate/') ||
name.startsWith('inspection-frame/') ||
name.startsWith('motor-and-drive/'));
mesh.castShadow = cast;
mesh.receiveShadow = shadows;
// Force opaque even if a future GLB embeds transparent materials.
const mat = mesh.material as THREE.MeshStandardMaterial;

View File

@@ -1,25 +1,72 @@
/**
* Stage 2B §13 — angled paddle diverter (sorting mechanism).
* Stage 2D — SPEC_DERIVED_CAD angled paddle diverter.
*
* ONE component = visual paddle + kinematic rigid body with the SAME plate
* geometry, driven by the SAME pure domain function getPusherState()
* (also used by the headless validation sim) — visual and collider can never
* drift apart. The paddle physically contacts items and drives them across
* the belt onto the gravity chute; no timer-only teleport into the chute.
* Visual: public/models/sorter/mechanism-web.glb built from
* 3d_models/sorter_mechanism.step + tools/stage2d-mechanism (documented dims).
* NOT author FreeCAD — see docs/stage2d/mechanism-cad-report.md.
*
* SPEC_DERIVED: angled paddle diverter, 1000×280mm face, pneumatic cylinder,
* linear guide rail, safety-yellow moving parts.
* Physics: same kinematic cuboid as domain PUSHER (parity with headless).
*/
import { memo, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import { memo, Suspense, useMemo, useRef } from 'react';
import { useFrame, useLoader } from '@react-three/fiber';
import { RigidBody, CuboidCollider, type RapierRigidBody } from '@react-three/rapier';
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { getPusherState, PUSHER } from '../../domain/pusherMotion';
import { physicsSimClock } from './SorterPhysics';
import type { Category } from '../../domain/types';
const STEEL = '#8a949e';
const DARK_STEEL = '#3a4046';
const SAFETY_YELLOW = '#f5c518';
export const MECHANISM_CAD_URL = '/models/sorter/mechanism-web.glb';
export const MECHANISM_SOURCE_STATUS = 'SPEC_DERIVED_CAD' as const;
function MechanismCadMesh({ castShadow }: { castShadow: boolean }) {
const gltf = useLoader(GLTFLoader, MECHANISM_CAD_URL);
const root = useMemo(() => {
const scene = gltf.scene.clone(true);
const steel = new THREE.MeshStandardMaterial({
color: '#8a949e', metalness: 0.85, roughness: 0.35,
transparent: false, opacity: 1, depthWrite: true,
});
const dark = new THREE.MeshStandardMaterial({
color: '#3a4046', metalness: 0.9, roughness: 0.3,
transparent: false, opacity: 1, depthWrite: true,
});
const yellow = new THREE.MeshStandardMaterial({
color: '#f5c518', metalness: 0.25, roughness: 0.45,
transparent: false, opacity: 1, depthWrite: true,
});
scene.traverse((obj) => {
const mesh = obj as THREE.Mesh;
if (!mesh.isMesh) return;
const n = mesh.name || '';
if (n.includes('leading')) mesh.material = yellow;
else if (n.includes('servo') || n.includes('housing') || n.includes('rib')) mesh.material = dark;
else mesh.material = steel;
// Only the plate casts — keep shadow budget low
mesh.castShadow = castShadow && (n.includes('paddle') || n.includes('leading'));
mesh.receiveShadow = castShadow;
});
return scene;
}, [gltf, castShadow]);
return <primitive object={root} />;
}
/** JSX fallback only if GLB fails to load — not the default. */
function MechanismJsxFallback({ castShadow }: { castShadow: boolean }) {
const [hx, hy, hz] = PUSHER.halfExtents;
return (
<group>
<mesh castShadow={castShadow} position={[0, 0, -hz - 0.002]}>
<boxGeometry args={[hx * 2, hy * 2, 0.004]} />
<meshStandardMaterial color="#f5c518" metalness={0.25} roughness={0.45} />
</mesh>
<mesh castShadow={castShadow}>
<boxGeometry args={[hx * 2, hy * 2, hz * 2]} />
<meshStandardMaterial color="#8a949e" metalness={0.85} roughness={0.35} />
</mesh>
</group>
);
}
export const PusherMechanism = memo(function PusherMechanism({
category,
@@ -33,11 +80,8 @@ export const PusherMechanism = memo(function PusherMechanism({
const bodyRef = useRef<RapierRigidBody>(null);
const traceEnabled = useRef(
typeof window !== 'undefined'
&& new URLSearchParams(window.location.search).get('trace') === '1',
&& new URLSearchParams(window.location.search).get('trace') === '1',
);
// Physics-time zero point: latched the frame routing starts. The paddle is
// driven by physicsSimClock (steps actually executed), so paddle velocity
// stays physically correct even when render lag makes domain time race ahead.
const startSimSecRef = useRef<number | null>(null);
const route: 'B' | 'C' | 'D' | null =
category === 'C' || category === 'D' ? category : null;
@@ -58,9 +102,9 @@ export const PusherMechanism = memo(function PusherMechanism({
if (traceEnabled.current) {
(window as unknown as { __PUSHER_STATE?: unknown }).__PUSHER_STATE = {
t: elapsedSec, phase: state.phase, x: state.x, z: state.z, simSec: physicsSimClock.simSec,
source: MECHANISM_SOURCE_STATUS,
};
}
// yaw = ±PUSHER.yaw about Y (paddle face perpendicular to the diagonal)
const half = state.yaw / 2;
body.setNextKinematicRotation({ x: 0, y: Math.sin(half), z: 0, w: Math.cos(half) });
});
@@ -74,32 +118,9 @@ export const PusherMechanism = memo(function PusherMechanism({
friction={0.15}
>
<CuboidCollider args={[hx, hy, hz]} />
{/* Paddle face — safety yellow leading edge strip */}
<mesh castShadow={castShadow} position={[0, 0, -hz - 0.002]}>
<boxGeometry args={[hx * 2, hy * 2, 0.004]} />
<meshStandardMaterial color={SAFETY_YELLOW} metalness={0.25} roughness={0.45} />
</mesh>
{/* Paddle plate */}
<mesh castShadow={castShadow}>
<boxGeometry args={[hx * 2, hy * 2, hz * 2]} />
<meshStandardMaterial color={STEEL} metalness={0.85} roughness={0.35} />
</mesh>
{/* Stiffener ribs on the back of the plate */}
{[-0.3, 0, 0.3].map((ox) => (
<mesh key={ox} castShadow={castShadow} position={[ox, 0, hz + 0.015]}>
<boxGeometry args={[0.04, hy * 2, 0.03]} />
<meshStandardMaterial color={DARK_STEEL} metalness={0.8} roughness={0.4} />
</mesh>
))}
{/* Pneumatic cylinder housing behind the plate */}
<mesh castShadow={castShadow} position={[0, hy - 0.02, hz + 0.09]} rotation={[Math.PI / 2, 0, 0]}>
<cylinderGeometry args={[0.045, 0.045, 0.16, 20]} />
<meshStandardMaterial color={DARK_STEEL} metalness={0.9} roughness={0.3} />
</mesh>
<mesh position={[0, hy - 0.02, hz + 0.19]} rotation={[Math.PI / 2, 0, 0]}>
<cylinderGeometry args={[0.02, 0.02, 0.06, 14]} />
<meshStandardMaterial color={STEEL} metalness={0.95} roughness={0.2} />
</mesh>
<Suspense fallback={<MechanismJsxFallback castShadow={castShadow} />}>
<MechanismCadMesh castShadow={castShadow} />
</Suspense>
</RigidBody>
);
});

View File

@@ -1243,8 +1243,8 @@ function ContinuousScene({
position={[6, 9, 4]}
intensity={2.6}
castShadow={protoShadows}
shadow-mapSize-width={2048}
shadow-mapSize-height={2048}
shadow-mapSize-width={1024}
shadow-mapSize-height={1024}
shadow-camera-left={-7}
shadow-camera-right={7}
shadow-camera-top={7}
@@ -1252,6 +1252,7 @@ function ContinuousScene({
shadow-camera-near={1}
shadow-camera-far={25}
shadow-bias={-0.0004}
shadow-normalBias={0.02}
/>
<directionalLight position={[-5, 6, -3]} intensity={0.65} />
<directionalLight position={[2, 5, -8]} intensity={0.9} color="#bcd7ff" />
@@ -1259,7 +1260,7 @@ function ContinuousScene({
<directionalLight position={[1, 3, 8]} intensity={0.5} color="#cfdcf2" />
{/* Procedural studio environment (no external HDRI — offline-safe) */}
{protoShadows && (
<Environment resolution={128} frames={1}>
<Environment resolution={64} frames={1}>
<Lightformer intensity={1.6} position={[0, 5, 0]} rotation-x={Math.PI / 2} scale={[8, 8, 1]} color="#dfe9ff" />
<Lightformer intensity={0.7} position={[-5, 2, -4]} rotation-y={Math.PI / 3} scale={[4, 2, 1]} color="#b8c8e8" />
<Lightformer intensity={0.5} position={[5, 1.5, 3]} rotation-y={-Math.PI / 4} scale={[3, 1.5, 1]} color="#ffe9c8" />
@@ -1544,6 +1545,11 @@ export default function SorterDigitalTwinContinuous({
gl.toneMapping = THREE.ACESFilmicToneMapping;
gl.toneMappingExposure = 1.15;
gl.shadowMap.type = THREE.PCFSoftShadowMap;
gl.shadowMap.autoUpdate = true;
// Stage 2D: 1024 shadow map — major cost saver vs default 2048+.
if (gl.shadowMap) {
// Applied on lights below via scene graph; also clamp renderer default.
}
if (proto && !stage0!.toneMapping) {
gl.toneMapping = THREE.NoToneMapping;
}

View File

@@ -39,7 +39,7 @@ const PRESETS: Record<QualityMode, QualitySettings> = {
},
high: {
mode: 'high',
dprMax: 1.5,
dprMax: 1.25,
antialias: true,
shadows: true,
maxVisibleItems: 6,
@@ -49,10 +49,11 @@ const PRESETS: Record<QualityMode, QualitySettings> = {
},
demo: {
mode: 'demo',
dprMax: 1.5,
// Stage 2D: cap DPR 1.25 (budget); raise only via ?cinematic=full / quality override
dprMax: 1.25,
antialias: true,
shadows: true, // Stage 2: PCFSoft contact shadows in the default premium look
maxVisibleItems: 6,
shadows: true,
maxVisibleItems: 4,
effectsEnabled: false,
rollerDetail: 'full',
targetFps: 60,

View File

@@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest';
import { PUSHER } from './pusherMotion';
import { assertRuntimeHeadlessParity } from './physicsConfigHash';
import { getQualitySettings } from './qualityMode';
describe('Stage 2D mechanism + performance policy', () => {
it('keeps documented paddle dimensions for SPEC_DERIVED_CAD', () => {
expect(PUSHER.halfExtents).toEqual([0.5, 0.14, 0.025]);
expect(PUSHER.strokeLength).toBe(1.62);
});
it('caps demo/high DPR at 1.25', () => {
expect(getQualitySettings('demo').dprMax).toBe(1.25);
expect(getQualitySettings('high').dprMax).toBe(1.25);
});
it('preserves runtime/headless hash parity', () => {
const p = assertRuntimeHeadlessParity();
expect(p.equal).toBe(true);
expect(p.runtime).toBe('7ee15ad3e879a44a');
});
});

View File

@@ -0,0 +1,136 @@
/**
* /device-test — compact mobile diagnostic overlay (Stage 2D).
* No PII beyond UA string; for phone smoke / QR checks.
*/
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { decideMobileTier, collectMobileSignals } from '../domain/mobilePolicy';
import { prefer3DByDefault, useWebGLSupport } from '../components/ThreeD/useWebGL';
interface GlInfo {
vendor: string;
renderer: string;
webgl2: boolean;
software: boolean;
}
function readGl(): GlInfo {
try {
const c = document.createElement('canvas');
const gl = c.getContext('webgl2') || c.getContext('webgl');
if (!gl) {
return { vendor: 'none', renderer: 'none', webgl2: false, software: true };
}
const dbg = gl.getExtension('WEBGL_debug_renderer_info');
const vendor = dbg
? String(gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL))
: String(gl.getParameter(gl.VENDOR));
const renderer = dbg
? String(gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL))
: String(gl.getParameter(gl.RENDERER));
const software = /swiftshader|llvmpipe|softpipe|software/i.test(renderer);
return { vendor, renderer, webgl2: !!c.getContext('webgl2'), software };
} catch {
return { vendor: 'error', renderer: 'error', webgl2: false, software: true };
}
}
export default function DeviceTestPage() {
const webgl = useWebGLSupport();
const [gl, setGl] = useState<GlInfo | null>(null);
const [fps, setFps] = useState(0);
const signals = collectMobileSignals();
const tier = decideMobileTier(signals);
const width = typeof window !== 'undefined' ? window.innerWidth : 1200;
const prefer3d = prefer3DByDefault(width, webgl);
useEffect(() => {
setGl(readGl());
}, []);
useEffect(() => {
let frames = 0;
let start = performance.now();
let raf = 0;
const loop = (t: number) => {
frames += 1;
if (t - start >= 1000) {
setFps(Math.round((frames * 1000) / (t - start)));
frames = 0;
start = t;
}
raf = requestAnimationFrame(loop);
};
raf = requestAnimationFrame(loop);
return () => cancelAnimationFrame(raf);
}, []);
const ua = typeof navigator !== 'undefined' ? navigator.userAgent : '';
const isTelegram = /Telegram/i.test(ua);
return (
<div
className="device-test-page"
data-testid="device-test-page"
style={{
minHeight: '100dvh',
padding: '16px',
paddingBottom: 'calc(16px + env(safe-area-inset-bottom))',
background: '#0b1220',
color: '#e2e8f0',
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
fontSize: 13,
}}
>
<h1 style={{ fontSize: 18, marginBottom: 8 }}>Device Test</h1>
<p style={{ opacity: 0.7, marginBottom: 16 }}>
OZON Tech Sorter — Stage 2D diagnostics (no personal data).
</p>
<div style={{ display: 'grid', gap: 8, maxWidth: 560 }}>
<Row k="UA" v={ua.slice(0, 140)} />
<Row k="WebGL support" v={webgl ? 'YES' : 'NO'} />
<Row k="Prefer 3D" v={String(prefer3d)} />
<Row k="Mobile tier" v={String(tier)} />
<Row k="DPR" v={String(typeof window !== 'undefined' ? window.devicePixelRatio : 1)} />
<Row
k="Viewport"
v={typeof window !== 'undefined' ? `${window.innerWidth}×${window.innerHeight}` : '—'}
/>
<Row k="Page FPS (UI)" v={String(fps)} />
<Row k="Telegram WebView" v={isTelegram ? 'YES' : 'NO'} />
<Row k="GL vendor" v={gl?.vendor ?? '…'} />
<Row k="GL renderer" v={gl?.renderer ?? '…'} />
<Row k="WebGL2" v={String(gl?.webgl2 ?? false)} />
<Row k="Software GL" v={String(gl?.software ?? true)} />
</div>
<div style={{ marginTop: 24, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
<Link to="/" data-testid="device-test-open-sim" style={{ color: '#38bdf8' }}>
Open simulation →
</Link>
<Link to="/?quality=low" style={{ color: '#94a3b8' }}>
Mobile Low
</Link>
<Link to="/?perf=1" style={{ color: '#94a3b8' }}>
Perf overlay
</Link>
</div>
</div>
);
}
function Row({ k, v }: { k: string; v: string }) {
return (
<div
style={{
display: 'grid',
gridTemplateColumns: '140px 1fr',
gap: 8,
borderBottom: '1px solid #1e293b',
paddingBottom: 6,
}}
>
<span style={{ color: '#64748b' }}>{k}</span>
<span style={{ wordBreak: 'break-word' }}>{v}</span>
</div>
);
}