fix(3d): unified conveyorNetwork, physical B receiver, C/D containment, belt sync, real STL

This commit is contained in:
root
2026-07-09 17:18:32 +02:00
parent 1528cfce10
commit 8e9ae4f62b
53 changed files with 1101 additions and 170 deletions

View File

@@ -22,6 +22,7 @@ const ITEM_MATERIALS: Record<string, { color: string; roughness: number; metalne
'SKU-006': { color: '#f8fafc', roughness: 0.42 },
'SKU-007': { color: '#7dd3fc', roughness: 0.28 },
'SKU-008': { color: '#cbd5e1', roughness: 0.35, metalness: 0.15 },
'SKU-011': { color: '#cbd5e1', roughness: 0.35, metalness: 0.15 },
};
function STLGeometry({ path, scale, color, accentColor, emissiveIntensity, roughness, metalness }: any) {
@@ -92,14 +93,14 @@ export function PhysicalPlaybackItem({
elapsedMs
});
const { position, rotation, isSettled, phase } = pose;
const { position, rotation, isSettled, phase, surface } = pose;
const isRouting = phase === 'routing';
// Item rests on a moving/transport surface (shadow makes sense there).
const onTransport = surface === 'main_belt'
|| surface === 'inspection_station'
|| surface === 'routing_junction'
|| surface === 'b_receiver';
// Do not render B items that are settled (they exit the factory)
if (isSettled && caseData.expectedCategory === 'B') {
return null;
}
// Before spawn, don't show
if (elapsedMs < 0) return null;
@@ -121,8 +122,8 @@ export function PhysicalPlaybackItem({
<FallbackPrimitive type={fallbackType} color={material.color} accentColor={accentColor} emissiveIntensity={emissiveIntensity} roughness={material.roughness} metalness={material.metalness ?? 0.05} w={dims.width} h={dims.height} d={dims.depth} />
)}
{/* Shadow on belt (only if on belt or chute) */}
{!isSettled && (
{/* Contact shadow only while riding a transport surface */}
{onTransport && (
<mesh position={[0, -dims.height / 2 + 0.001, 0]} rotation={[-Math.PI / 2, 0, 0]}>
<circleGeometry args={[Math.max(dims.width, dims.depth) / 2 + 0.01, 16]} />
<meshStandardMaterial color="#475569" transparent opacity={0.15} />

View File

@@ -53,6 +53,9 @@ import {
ROLL_CAGE,
getRenderedItemDimensions,
getItemYOnBelt,
B_RECEIVER,
CAGE_FLOOR_Y,
CONVEYOR_SPEED_MPS,
} from '../../domain/physicalLayout';
export interface SorterDigitalTwinContinuousProps {
@@ -225,21 +228,20 @@ function Roller({ position, speedFactor }: { position: [number, number, number];
);
}
/** Moving stripe on conveyor belt - subtle texture movement at 1 m/s */
function BeltStripe({ offset, speedFactor }: { offset: number; speedFactor: number }) {
const meshRef = useRef<Mesh>(null);
const posRef = useRef(offset);
useFrame((_, delta) => {
if (meshRef.current && speedFactor > 0) {
posRef.current += delta * speedFactor * 1.0; // 1 m/s
if (posRef.current > CONVEYOR_END_X) posRef.current = CONVEYOR_START_X;
meshRef.current.position.x = posRef.current;
}
});
/**
* Moving stripe on conveyor belt.
* Position is DETERMINISTIC from playback time (offset = time * 1 m/s), so the
* belt animation shares the exact tempo/direction of the item, is FPS-independent,
* freezes on pause and resets on stop.
*/
function BeltStripe({ baseOffset, elapsedMs }: { baseOffset: number; elapsedMs: number }) {
const beltLen = CONVEYOR_END_X - CONVEYOR_START_X;
const shift = ((elapsedMs / 1000) * CONVEYOR_SPEED_MPS) % beltLen;
let x = baseOffset + shift;
if (x > CONVEYOR_END_X) x -= beltLen;
return (
<mesh ref={meshRef} position={[offset, BELT_Y + 0.001, 0]}>
<mesh position={[x, BELT_Y + 0.001, 0]}>
<boxGeometry args={[0.08, 0.002, CONVEYOR_WIDTH_M - 0.06]} />
<meshStandardMaterial
color={COLORS.beltStripe}
@@ -515,7 +517,7 @@ function SupportLeg({ x }: { x: number }) {
* Conveyor belt - realistic roller conveyor
* Belt top surface at 0.7m (BELT_TOP_Y)
*/
function ConveyorBelt({ speedFactor, pulseActive }: { speedFactor: number; pulseActive: boolean }) {
function ConveyorBelt({ speedFactor, pulseActive, elapsedMs }: { speedFactor: number; pulseActive: boolean; elapsedMs: number }) {
const rollerCount = Math.floor(CONVEYOR_LENGTH / ROLLER_SPACING_M);
const rollerPositions = useMemo(() => {
@@ -546,9 +548,9 @@ function ConveyorBelt({ speedFactor, pulseActive }: { speedFactor: number; pulse
/>
</mesh>
{/* Belt stripes (animated) - subtle texture movement */}
{/* Belt stripes — deterministic movement synced to item (offset = time * 1 m/s) */}
{[-4, -2.5, -1, 0.5, 2, 3.5].map((offset, i) => (
<BeltStripe key={i} offset={offset} speedFactor={speedFactor} />
<BeltStripe key={i} baseOffset={offset} elapsedMs={elapsedMs} />
))}
{/* Side guards - brushed metal above belt */}
@@ -641,6 +643,62 @@ function ZoneMarker({ position, label, color, active }: {
);
}
/**
* B receiving zone — physical downstream receiving tray after the sorter.
* A short 0.5m-wide tray at belt height (0.7m) with low side walls and an end
* stop, so B items visibly land and remain instead of vanishing into thin air.
*/
function BReceiver({ active }: { active: boolean }) {
const { startX, endX, y, width, wallHeight } = B_RECEIVER;
const len = endX - startX;
const centerX = (startX + endX) / 2;
const emissive = active ? 0.35 : 0.05;
const legY = y / 2;
return (
<group>
{/* Tray floor at belt height */}
<mesh position={[centerX, y - 0.02, 0]} receiveShadow>
<boxGeometry args={[len, 0.04, width]} />
<meshStandardMaterial color="#334155" metalness={0.3} roughness={0.7} />
</mesh>
{/* Side walls */}
{[-1, 1].map((s) => (
<mesh key={s} position={[centerX, y + wallHeight / 2, s * (width / 2)]}>
<boxGeometry args={[len, wallHeight, 0.02]} />
<meshStandardMaterial color={COLORS.routeB} transparent opacity={0.55} emissive={COLORS.routeB} emissiveIntensity={emissive} />
</mesh>
))}
{/* End stop wall */}
<mesh position={[endX, y + wallHeight / 2, 0]}>
<boxGeometry args={[0.03, wallHeight, width]} />
<meshStandardMaterial color={COLORS.routeB} transparent opacity={0.6} emissive={COLORS.routeB} emissiveIntensity={emissive} />
</mesh>
{/* Support legs */}
{[startX + 0.2, endX - 0.2].map((lx) => (
[-1, 1].map((s) => (
<mesh key={`${lx}-${s}`} position={[lx, legY, s * (width / 2 - 0.05)]}>
<boxGeometry args={[0.04, y, 0.04]} />
<meshStandardMaterial color={COLORS.conveyorFrame} metalness={0.5} roughness={0.4} />
</mesh>
))
))}
{/* Label */}
<Html position={[centerX, y + wallHeight + 0.18, 0]} center>
<div style={{
color: active ? COLORS.routeB : '#64748b',
fontSize: '20px',
fontWeight: 800,
textShadow: active ? `0 0 8px ${COLORS.routeB}` : 'none',
userSelect: 'none',
}}>
B
</div>
</Html>
</group>
);
}
/** Roll cage for C/D zones - realistic wireframe cage with wheels */
function RollCage({ position, label, color, active }: {
position: [number, number, number];
@@ -659,6 +717,12 @@ function RollCage({ position, label, color, active }: {
<planeGeometry args={[width + 0.2, depth + 0.2]} />
<meshStandardMaterial color={color} transparent opacity={active ? 0.25 : 0.08} />
</mesh>
{/* Solid interior floor where items rest */}
<mesh position={[0, CAGE_FLOOR_Y - 0.005, 0]} receiveShadow>
<boxGeometry args={[width - frameThickness, 0.01, depth - frameThickness]} />
<meshStandardMaterial color="#1e293b" metalness={0.3} roughness={0.7} />
</mesh>
{/* Cage frame - bottom rectangle */}
<mesh position={[0, wheelRadius * 2 + ft / 2, depth / 2 - ft / 2]}>
@@ -1317,7 +1381,7 @@ function ContinuousScene({
</mesh>
{/* Conveyor - belt top at 0.7m */}
<ConveyorBelt speedFactor={speedFactor} pulseActive={showPulse} />
<ConveyorBelt speedFactor={speedFactor} pulseActive={showPulse} elapsedMs={totalElapsedMs} />
{/* Zone A - spawn point */}
<ZoneMarker
@@ -1327,13 +1391,8 @@ function ContinuousScene({
active={playback.currentPhase === 'spawn'}
/>
{/* Zone B - main sorter exit */}
<ZoneMarker
position={[ZONES.B.x, 0.01, ZONES.B.z]}
label="B"
color={COLORS.routeB}
active={activeRoute === 'B'}
/>
{/* Zone B - physical receiving tray at end of sorter */}
<BReceiver active={activeRoute === 'B'} />
{/* Zone C - roll cage for oversized items */}
<RollCage

View File

@@ -53,6 +53,34 @@ describe('modelAssets', () => {
});
});
describe('demo STL coverage', () => {
it('uses real STL for every available demo model', () => {
const stlMap: Record<string, string> = {
'SKU-001': '/models/box-300.stl',
'SKU-002': '/models/lunchbox.stl',
'SKU-004': '/models/box-400.stl',
'SKU-006': '/models/plate.stl',
'SKU-007': '/models/bottle.stl',
'SKU-008': '/models/cylinder.stl',
'SKU-011': '/models/cylinder.stl', // c_priority round item
};
for (const [id, path] of Object.entries(stlMap)) {
const asset = getModelAsset(id);
expect(asset?.loaderType).toBe('stl');
expect(asset?.frontendAssetPath).toBe(path);
}
});
it('keeps fallbacks explicit and only for heavy/missing STL', () => {
const fallbackIds = ['SKU-003', 'SKU-005', 'SKU-009', 'SKU-010'];
for (const id of fallbackIds) {
const asset = getModelAsset(id);
expect(asset?.loaderType).toBe('procedural');
expect(asset?.notes).toBeTruthy();
}
});
});
describe('getModelAsset', () => {
it('should return asset for valid item ID', () => {
const asset = getModelAsset('SKU-006');

View File

@@ -158,11 +158,11 @@ export const MODEL_ASSETS: ModelAsset[] = [
displayName: 'Oversized round',
categoryScenario: 'C',
dimensions: { width: 500, depth: 300, height: 300 },
sourceFile: 'N/A',
frontendAssetPath: undefined,
loaderType: 'procedural',
sourceFile: 'input_info/extracted/Stl/Цилиндр.stl',
frontendAssetPath: '/models/cylinder.stl',
loaderType: 'stl',
fallbackPrimitive: 'cylinder',
notes: 'No STL available for oversized round, using procedural cylinder.',
notes: 'Uses available round STL (cylinder.stl, 106 KB) for the oversized-round C-priority case.',
},
];

View File

@@ -0,0 +1,76 @@
import { describe, it, expect } from 'vitest';
import {
SURFACES,
getSurface,
isWithinBounds,
surfaceLength,
pathForCategory,
type SurfaceName,
} from './conveyorNetwork';
const ALL: SurfaceName[] = [
'main_belt',
'inspection_station',
'routing_junction',
'b_receiver',
'chute_c',
'chute_d',
'c_cage_floor',
'd_cage_floor',
];
describe('conveyorNetwork', () => {
it('defines every required surface', () => {
for (const name of ALL) {
expect(SURFACES[name]).toBeDefined();
expect(getSurface(name).name).toBe(name);
}
});
it('every surface has finite coordinates and bounds', () => {
for (const name of ALL) {
const s = SURFACES[name];
for (const v of [...s.start, ...s.end, s.surfaceY, s.width, s.speedMps]) {
expect(Number.isFinite(v)).toBe(true);
}
const b = s.bounds;
for (const v of [b.minX, b.maxX, b.minZ, b.maxZ]) {
expect(Number.isFinite(v)).toBe(true);
}
expect(b.maxX).toBeGreaterThanOrEqual(b.minX);
expect(b.maxZ).toBeGreaterThanOrEqual(b.minZ);
}
});
it('main belt runs at 1 m/s and cages/junctions are static', () => {
expect(SURFACES.main_belt.speedMps).toBe(1);
expect(SURFACES.routing_junction.speedMps).toBe(1);
expect(SURFACES.c_cage_floor.speedMps).toBe(0);
expect(SURFACES.d_cage_floor.speedMps).toBe(0);
expect(SURFACES.inspection_station.speedMps).toBe(0);
});
it('chutes move slower than the belt but are not static', () => {
expect(SURFACES.chute_c.speedMps).toBeGreaterThan(0);
expect(SURFACES.chute_c.speedMps).toBeLessThan(SURFACES.main_belt.speedMps);
});
it('provides an ordered path per category', () => {
expect(pathForCategory('B')).toEqual(['main_belt', 'inspection_station', 'routing_junction', 'b_receiver']);
expect(pathForCategory('C')).toEqual(['main_belt', 'inspection_station', 'routing_junction', 'chute_c', 'c_cage_floor']);
expect(pathForCategory('D')).toEqual(['main_belt', 'inspection_station', 'routing_junction', 'chute_d', 'd_cage_floor']);
});
it('bounds check works', () => {
const c = SURFACES.c_cage_floor.bounds;
const cx = (c.minX + c.maxX) / 2;
const cz = (c.minZ + c.maxZ) / 2;
expect(isWithinBounds('c_cage_floor', cx, cz)).toBe(true);
expect(isWithinBounds('c_cage_floor', c.maxX + 1, cz)).toBe(false);
});
it('chutes have real length (item slides, does not teleport)', () => {
expect(surfaceLength('chute_c')).toBeGreaterThan(0.5);
expect(surfaceLength('chute_d')).toBeGreaterThan(0.5);
});
});

View File

@@ -0,0 +1,231 @@
/**
* Conveyor Network — единый источник правды для физических поверхностей 3D сцены.
*
* Описывает физическую сеть транспортировки:
* conveyor A → inspection station → routing junction →
* B receiving zone | chute C → C roll-cage floor | chute D → D roll-cage floor
*
* Все координаты в метрах (1 Three.js unit = 1 meter).
* Скорости в м/с. Никакой рандомизации и покадровых инкрементов — только геометрия.
*/
import type { Category } from './types';
import {
ZONES,
BELT_TOP_Y,
CONVEYOR_SPEED_MPS,
MAIN_BELT_WIDTH_M,
CHUTE_C_WIDTH_M,
CHUTE_D_WIDTH_M,
CHUTE_END_Y,
CAGE_FLOOR_Y,
ROLL_CAGE,
B_RECEIVER,
} from './physicalLayout';
export type SurfaceName =
| 'main_belt'
| 'inspection_station'
| 'routing_junction'
| 'b_receiver'
| 'chute_c'
| 'chute_d'
| 'c_cage_floor'
| 'd_cage_floor';
export type Vec3 = [number, number, number];
export interface SurfaceBounds {
minX: number;
maxX: number;
minZ: number;
maxZ: number;
}
export interface Surface {
name: SurfaceName;
/** Entry point of the surface (item enters here). */
start: Vec3;
/** Exit point of the surface (item leaves here). */
end: Vec3;
/** Top surface height where the item bottom rests. */
surfaceY: number;
/** Physical width of the surface in meters. */
width: number;
/** Transport speed along the surface in m/s (0 for a static bin/junction). */
speedMps: number;
/** Axis-aligned bounds (containment check). */
bounds: SurfaceBounds;
/** Destination category, if this surface belongs to a routing branch. */
targetCategory?: Category;
}
const A = ZONES.A; // spawn
const CAMERA = ZONES.CAMERA; // inspection
const GATE = ZONES.GATE; // routing junction
const C = ZONES.C; // cage C center
const D = ZONES.D; // cage D center
/** Half-extents of a roll cage along X (width) and Z (depth). */
const CAGE_HALF_X = ROLL_CAGE.width / 2; // 0.6
const CAGE_HALF_Z = ROLL_CAGE.depth / 2; // 0.4
/** Chute entry sits at the junction on the belt edge toward the cage. */
const CHUTE_C_ENTRY: Vec3 = [GATE.x, BELT_TOP_Y, MAIN_BELT_WIDTH_M / 2];
const CHUTE_C_EXIT: Vec3 = [C.x, CHUTE_END_Y, C.z - CAGE_HALF_Z]; // front edge of cage C
const CHUTE_D_ENTRY: Vec3 = [GATE.x, BELT_TOP_Y, -MAIN_BELT_WIDTH_M / 2];
const CHUTE_D_EXIT: Vec3 = [D.x, CHUTE_END_Y, D.z + CAGE_HALF_Z]; // front edge of cage D
/** Chute transport speed (slower than belt, gravity-fed slide, still not a flight). */
export const CHUTE_SPEED_MPS = 0.5;
export const SURFACES: Record<SurfaceName, Surface> = {
main_belt: {
name: 'main_belt',
start: [A.x, BELT_TOP_Y, 0],
end: [CAMERA.x, BELT_TOP_Y, 0],
surfaceY: BELT_TOP_Y,
width: MAIN_BELT_WIDTH_M,
speedMps: CONVEYOR_SPEED_MPS,
bounds: { minX: A.x, maxX: CAMERA.x, minZ: -MAIN_BELT_WIDTH_M / 2, maxZ: MAIN_BELT_WIDTH_M / 2 },
},
inspection_station: {
name: 'inspection_station',
start: [CAMERA.x, BELT_TOP_Y, 0],
end: [CAMERA.x, BELT_TOP_Y, 0],
surfaceY: BELT_TOP_Y,
width: MAIN_BELT_WIDTH_M,
speedMps: 0, // dwell for detection
bounds: { minX: CAMERA.x - 0.4, maxX: CAMERA.x + 0.4, minZ: -MAIN_BELT_WIDTH_M / 2, maxZ: MAIN_BELT_WIDTH_M / 2 },
},
routing_junction: {
name: 'routing_junction',
start: [CAMERA.x, BELT_TOP_Y, 0],
end: [GATE.x, BELT_TOP_Y, 0],
surfaceY: BELT_TOP_Y,
width: MAIN_BELT_WIDTH_M,
speedMps: CONVEYOR_SPEED_MPS,
bounds: { minX: CAMERA.x, maxX: GATE.x, minZ: -MAIN_BELT_WIDTH_M / 2, maxZ: MAIN_BELT_WIDTH_M / 2 },
},
b_receiver: {
name: 'b_receiver',
start: [GATE.x, BELT_TOP_Y, 0],
end: [B_RECEIVER.restX, BELT_TOP_Y, 0],
surfaceY: B_RECEIVER.y,
width: B_RECEIVER.width,
speedMps: CONVEYOR_SPEED_MPS,
bounds: {
minX: B_RECEIVER.startX,
maxX: B_RECEIVER.endX,
minZ: -B_RECEIVER.width / 2,
maxZ: B_RECEIVER.width / 2,
},
targetCategory: 'B',
},
chute_c: {
name: 'chute_c',
start: CHUTE_C_ENTRY,
end: CHUTE_C_EXIT,
surfaceY: BELT_TOP_Y,
width: CHUTE_C_WIDTH_M,
speedMps: CHUTE_SPEED_MPS,
bounds: {
minX: Math.min(CHUTE_C_ENTRY[0], CHUTE_C_EXIT[0]) - 0.1,
maxX: Math.max(CHUTE_C_ENTRY[0], CHUTE_C_EXIT[0]) + 0.1,
minZ: Math.min(CHUTE_C_ENTRY[2], CHUTE_C_EXIT[2]),
maxZ: Math.max(CHUTE_C_ENTRY[2], CHUTE_C_EXIT[2]),
},
targetCategory: 'C',
},
chute_d: {
name: 'chute_d',
start: CHUTE_D_ENTRY,
end: CHUTE_D_EXIT,
surfaceY: BELT_TOP_Y,
width: CHUTE_D_WIDTH_M,
speedMps: CHUTE_SPEED_MPS,
bounds: {
minX: Math.min(CHUTE_D_ENTRY[0], CHUTE_D_EXIT[0]) - 0.1,
maxX: Math.max(CHUTE_D_ENTRY[0], CHUTE_D_EXIT[0]) + 0.1,
minZ: Math.min(CHUTE_D_ENTRY[2], CHUTE_D_EXIT[2]),
maxZ: Math.max(CHUTE_D_ENTRY[2], CHUTE_D_EXIT[2]),
},
targetCategory: 'D',
},
c_cage_floor: {
name: 'c_cage_floor',
start: [C.x, CAGE_FLOOR_Y, C.z],
end: [C.x, CAGE_FLOOR_Y, C.z],
surfaceY: CAGE_FLOOR_Y,
width: ROLL_CAGE.width,
speedMps: 0,
bounds: {
minX: C.x - CAGE_HALF_X,
maxX: C.x + CAGE_HALF_X,
minZ: C.z - CAGE_HALF_Z,
maxZ: C.z + CAGE_HALF_Z,
},
targetCategory: 'C',
},
d_cage_floor: {
name: 'd_cage_floor',
start: [D.x, CAGE_FLOOR_Y, D.z],
end: [D.x, CAGE_FLOOR_Y, D.z],
surfaceY: CAGE_FLOOR_Y,
width: ROLL_CAGE.width,
speedMps: 0,
bounds: {
minX: D.x - CAGE_HALF_X,
maxX: D.x + CAGE_HALF_X,
minZ: D.z - CAGE_HALF_Z,
maxZ: D.z + CAGE_HALF_Z,
},
targetCategory: 'D',
},
};
export function getSurface(name: SurfaceName): Surface {
return SURFACES[name];
}
/** Linear interpolation between two 3D points. */
export function lerp3(a: Vec3, b: Vec3, t: number): Vec3 {
const clamped = Math.max(0, Math.min(1, t));
return [
a[0] + (b[0] - a[0]) * clamped,
a[1] + (b[1] - a[1]) * clamped,
a[2] + (b[2] - a[2]) * clamped,
];
}
/** Euclidean length of a surface from start to end (meters). */
export function surfaceLength(name: SurfaceName): number {
const s = SURFACES[name];
const dx = s.end[0] - s.start[0];
const dy = s.end[1] - s.start[1];
const dz = s.end[2] - s.start[2];
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
/** True if a point lies within the (padded) horizontal bounds of a surface. */
export function isWithinBounds(name: SurfaceName, x: number, z: number): boolean {
const b = SURFACES[name].bounds;
return x >= b.minX && x <= b.maxX && z >= b.minZ && z <= b.maxZ;
}
/** Heading (Y rotation) of a surface's travel direction, in radians. */
export function surfaceHeading(name: SurfaceName): number {
const s = SURFACES[name];
return Math.atan2(s.end[2] - s.start[2], s.end[0] - s.start[0]);
}
/** Ordered surfaces an item traverses for a given destination category. */
export function pathForCategory(category: Category): SurfaceName[] {
if (category === 'C') {
return ['main_belt', 'inspection_station', 'routing_junction', 'chute_c', 'c_cage_floor'];
}
if (category === 'D') {
return ['main_belt', 'inspection_station', 'routing_junction', 'chute_d', 'd_cage_floor'];
}
return ['main_belt', 'inspection_station', 'routing_junction', 'b_receiver'];
}

View File

@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest';
import { getPhysicalItemPose } from './physicalItemMotion';
import { ZONES, BELT_TOP_Y, CONVEYOR_SPEED_MPS } from './physicalLayout';
import { ZONES, BELT_TOP_Y, CONVEYOR_SPEED_MPS, CAGE_FLOOR_Y } from './physicalLayout';
import { SURFACES } from './conveyorNetwork';
describe('physicalItemMotion', () => {
const defaultInput = {
@@ -8,40 +9,97 @@ describe('physicalItemMotion', () => {
dimensionsMm: { width: 300, depth: 200, height: 200 }, // 0.2m height
targetCategory: 'B' as any,
elapsedMs: 0,
slotIndex: 0
slotIndex: 0,
};
const halfH = 0.1; // half of 0.2m
it('starts at spawn point on the belt', () => {
it('starts at spawn point on the main belt', () => {
const pose = getPhysicalItemPose({ ...defaultInput, elapsedMs: 0 });
expect(pose.surface).toBe('belt');
expect(pose.position[0]).toBe(ZONES.A.x);
expect(pose.position[1]).toBe(BELT_TOP_Y + 0.1); // 0.7 + 0.1
expect(pose.surface).toBe('main_belt');
expect(pose.position[0]).toBeCloseTo(ZONES.A.x, 5);
expect(pose.position[1]).toBeCloseTo(BELT_TOP_Y + halfH, 5);
expect(pose.phase).toBe('feed');
});
it('moves at 1 m/s along the belt during move_to_detection', () => {
// move_to_detection starts at 300ms
it('moves exactly 1 m in 1 s along the main belt', () => {
const start = getPhysicalItemPose({ ...defaultInput, elapsedMs: 300 }); // feed start
const later = getPhysicalItemPose({ ...defaultInput, elapsedMs: 1300 }); // +1s
const delta = later.position[0] - start.position[0];
expect(delta).toBeCloseTo(1.0 * CONVEYOR_SPEED_MPS, 2);
expect(later.surface).toBe('main_belt');
});
it('item bottom rests exactly on the belt surface', () => {
const pose = getPhysicalItemPose({ ...defaultInput, elapsedMs: 1300 });
const distance = 1000 / 1000 * CONVEYOR_SPEED_MPS; // 1.0 m
expect(pose.position[0]).toBeCloseTo(ZONES.A.x + distance, 2);
expect(pose.surface).toBe('belt');
const bottomY = pose.position[1] - halfH;
expect(bottomY).toBeCloseTo(BELT_TOP_Y, 5);
});
it('stays in C cage for category C after routing is complete', () => {
// 9800ms is the total duration
const pose = getPhysicalItemPose({ ...defaultInput, targetCategory: 'C', elapsedMs: 10000 });
expect(pose.isSettled).toBe(true);
expect(pose.surface).toBe('c_cage');
expect(pose.position[0]).toBeCloseTo(ZONES.C.x - 0.2, 1);
expect(pose.position[2]).toBeCloseTo(ZONES.C.z - 0.1, 1);
expect(pose.position[1]).toBeCloseTo(0.1 + 0.1, 2); // floor + half height
it('is deterministic for the same input', () => {
const a = getPhysicalItemPose({ ...defaultInput, targetCategory: 'C', elapsedMs: 7200 });
const b = getPhysicalItemPose({ ...defaultInput, targetCategory: 'C', elapsedMs: 7200 });
expect(a).toEqual(b);
});
it('stays in D cage for category D after routing is complete', () => {
const pose = getPhysicalItemPose({ ...defaultInput, targetCategory: 'D', elapsedMs: 10000 });
it('B final pose is inside the b_receiver bounds', () => {
const pose = getPhysicalItemPose({ ...defaultInput, targetCategory: 'B', elapsedMs: 20000 });
expect(pose.surface).toBe('b_receiver');
expect(pose.isSettled).toBe(true);
expect(pose.surface).toBe('d_cage');
expect(pose.position[0]).toBeCloseTo(ZONES.D.x - 0.2, 1);
expect(pose.position[2]).toBeCloseTo(ZONES.D.z - 0.1, 1);
const b = SURFACES.b_receiver.bounds;
expect(pose.position[0]).toBeGreaterThanOrEqual(b.minX);
expect(pose.position[0]).toBeLessThanOrEqual(b.maxX);
expect(pose.position[2]).toBeGreaterThanOrEqual(b.minZ);
expect(pose.position[2]).toBeLessThanOrEqual(b.maxZ);
});
it('C final pose is inside the c_cage bounds', () => {
const pose = getPhysicalItemPose({ ...defaultInput, targetCategory: 'C', elapsedMs: 20000 });
expect(pose.surface).toBe('c_cage_floor');
expect(pose.isSettled).toBe(true);
const b = SURFACES.c_cage_floor.bounds;
expect(pose.position[0]).toBeGreaterThanOrEqual(b.minX);
expect(pose.position[0]).toBeLessThanOrEqual(b.maxX);
expect(pose.position[2]).toBeGreaterThanOrEqual(b.minZ);
expect(pose.position[2]).toBeLessThanOrEqual(b.maxZ);
expect(pose.position[1]).toBeCloseTo(CAGE_FLOOR_Y + halfH, 5);
});
it('D final pose is inside the d_cage bounds', () => {
const pose = getPhysicalItemPose({ ...defaultInput, targetCategory: 'D', elapsedMs: 20000 });
expect(pose.surface).toBe('d_cage_floor');
expect(pose.isSettled).toBe(true);
const b = SURFACES.d_cage_floor.bounds;
expect(pose.position[0]).toBeGreaterThanOrEqual(b.minX);
expect(pose.position[0]).toBeLessThanOrEqual(b.maxX);
expect(pose.position[2]).toBeGreaterThanOrEqual(b.minZ);
expect(pose.position[2]).toBeLessThanOrEqual(b.maxZ);
});
it('settled item remains fixed as time increases', () => {
const t1 = getPhysicalItemPose({ ...defaultInput, targetCategory: 'C', elapsedMs: 12000 });
const t2 = getPhysicalItemPose({ ...defaultInput, targetCategory: 'C', elapsedMs: 30000 });
expect(t1.position).toEqual(t2.position);
expect(t1.isSettled).toBe(true);
expect(t2.isSettled).toBe(true);
});
it('never produces NaN/Infinity positions across the whole timeline', () => {
for (const cat of ['B', 'C', 'D'] as const) {
for (let t = 0; t <= 12000; t += 100) {
const pose = getPhysicalItemPose({ ...defaultInput, targetCategory: cat, elapsedMs: t });
for (const v of [...pose.position, ...pose.rotation]) {
expect(Number.isFinite(v)).toBe(true);
}
}
}
});
it('routes C down the chute before settling', () => {
const pose = getPhysicalItemPose({ ...defaultInput, targetCategory: 'C', elapsedMs: 7000 });
expect(pose.surface).toBe('chute_c');
expect(pose.phase).toBe('routing');
// On the chute the item is below belt height but above cage floor.
expect(pose.position[1]).toBeLessThan(BELT_TOP_Y + halfH);
expect(pose.position[1]).toBeGreaterThan(CAGE_FLOOR_Y);
});
});

View File

@@ -1,18 +1,28 @@
import { Category, DimensionsMm } from './types';
import {
CONVEYOR_SPEED_MPS,
BELT_TOP_Y,
ZONES,
ROLL_CAGE,
} from './physicalLayout';
import { CASE_PHASES } from './continuousPlayback';
/**
* Physical Item Motion — детерминированная поза товара.
*
* ЕДИНСТВЕННЫЙ источник движения товара. Вся геометрия берётся из conveyorNetwork.
* Поза считается только от elapsedMs (время внутри кейса). Нет рандома,
* нет покадровых инкрементов, нет отдельной "скорости товара".
*/
export type SurfaceType = "belt" | "chute_c" | "chute_d" | "b_line" | "c_cage" | "d_cage";
export type MotionPhase = "feed" | "inspection" | "decision" | "routing" | "settled";
import type { Category, DimensionsMm } from './types';
import { CASE_PHASES } from './continuousPlayback';
import {
SURFACES,
lerp3,
surfaceHeading,
type SurfaceName,
type Vec3,
} from './conveyorNetwork';
import { B_RECEIVER, CAGE_FLOOR_Y, ROLL_CAGE } from './physicalLayout';
export type SurfaceType = SurfaceName;
export type MotionPhase = 'feed' | 'inspection' | 'decision' | 'routing' | 'settled';
export interface PhysicalItemPose {
position: [number, number, number];
rotation: [number, number, number];
position: Vec3;
rotation: Vec3;
surface: SurfaceType;
phase: MotionPhase;
isSettled: boolean;
@@ -27,118 +37,126 @@ export interface PoseInput {
elapsedMs: number;
}
export function getPhysicalItemPose(input: PoseInput): PhysicalItemPose {
const { dimensionsMm, targetCategory, elapsedMs, slotIndex = 0 } = input;
const category = targetCategory || 'B';
const itemHeightM = dimensionsMm.height / 1000;
const beltY = BELT_TOP_Y + itemHeightM / 2;
// Reconstruct phase start times from CASE_PHASES
let cumulativeMs = 0;
/** Cumulative phase start times reconstructed once from CASE_PHASES. */
function phaseStarts() {
let cumulative = 0;
const starts: Record<string, number> = {};
for (const p of CASE_PHASES) {
starts[p.phase] = cumulativeMs;
cumulativeMs += p.durationMs;
starts[p.phase] = cumulative;
cumulative += p.durationMs;
}
const totalDuration = cumulativeMs; // 9800
return { starts, total: cumulative };
}
// Fallback safe defaults
let posX: number = ZONES.A.x;
let posY = beltY;
let posZ = 0;
/** Pose for a point at parameter t (0..1) along a surface, item resting on top. */
function poseOnSurface(name: SurfaceName, t: number, itemHeightM: number): { pos: Vec3; rotY: number } {
const s = SURFACES[name];
const p = lerp3(s.start, s.end, t);
// Item bottom sits on the surface: center = surfaceTop + half height.
return {
pos: [p[0], p[1] + itemHeightM / 2, p[2]],
rotY: surfaceHeading(name),
};
}
/** Deterministic slot position inside a cage (grid, stays within bounds). */
function cageSlot(name: SurfaceName, slotIndex: number, itemHeightM: number): { pos: Vec3; rotY: number } {
const b = SURFACES[name].bounds;
const cx = (b.minX + b.maxX) / 2;
const cz = (b.minZ + b.maxZ) / 2;
// 3 columns × 2 rows grid inside the cage footprint.
const col = slotIndex % 3; // 0,1,2
const row = Math.floor(slotIndex / 3) % 2; // 0,1
const offsetX = (col - 1) * (ROLL_CAGE.width / 3.2); // ~±0.375
const offsetZ = (row - 0.5) * (ROLL_CAGE.depth / 2.4); // ~±0.17
return {
pos: [cx + offsetX, CAGE_FLOOR_Y + itemHeightM / 2, cz + offsetZ],
rotY: (slotIndex % 4) * (Math.PI / 8), // small fixed yaw variety, deterministic
};
}
/** Deterministic rest position inside the B receiver tray (stacks backwards). */
function bReceiverSlot(slotIndex: number, itemHeightM: number): { pos: Vec3; rotY: number } {
const spacing = 0.55;
let x = B_RECEIVER.restX - (slotIndex % 4) * spacing;
if (x < B_RECEIVER.startX + 0.3) x = B_RECEIVER.startX + 0.3;
return {
pos: [x, B_RECEIVER.y + itemHeightM / 2, 0],
rotY: 0,
};
}
export function getPhysicalItemPose(input: PoseInput): PhysicalItemPose {
const { dimensionsMm, targetCategory, elapsedMs, slotIndex = 0 } = input;
const category: 'B' | 'C' | 'D' = (targetCategory as 'B' | 'C' | 'D') || 'B';
const itemHeightM = dimensionsMm.height / 1000;
const { starts, total } = phaseStarts();
const feedStart = starts['move_to_detection'];
const inspectStart = starts['detection'];
const junctionStart = starts['measurement'];
const routingStart = starts['routing'];
const clearStart = starts['clear_gap'];
let pos: Vec3;
let rotY = 0;
let surface: SurfaceType = 'belt';
let phase: MotionPhase = 'feed';
let surface: SurfaceType;
let phase: MotionPhase;
let isSettled = false;
if (elapsedMs <= starts['move_to_detection']) {
phase = 'feed';
posX = ZONES.A.x;
} else if (elapsedMs <= starts['detection']) {
phase = 'feed';
const dt = (elapsedMs - starts['move_to_detection']) / 1000;
posX = ZONES.A.x + dt * CONVEYOR_SPEED_MPS;
} else if (elapsedMs <= starts['measurement']) {
phase = 'inspection';
posX = ZONES.CAMERA.x;
} else if (elapsedMs <= starts['routing']) {
phase = 'decision';
// Total movement time in this block: measurement (1000), classification (1000), command_sent (1000)
// Distance from CAMERA to GATE = 1.5 - (-1.5) = 3.0m at 1m/s = 3000ms.
const dt = (elapsedMs - starts['measurement']) / 1000;
posX = ZONES.CAMERA.x + dt * CONVEYOR_SPEED_MPS;
} else {
// Routing, exit, clear_gap, or settled
const routingStart = starts['routing'];
const routingDuration = CASE_PHASES.find(p => p.phase === 'routing')!.durationMs; // 2500
if (category === 'B') {
const dt = (elapsedMs - routingStart) / 1000;
posX = Math.min(ZONES.GATE.x + dt * CONVEYOR_SPEED_MPS, ZONES.B.x);
surface = 'b_line';
if (posX >= ZONES.B.x) {
phase = 'settled';
isSettled = elapsedMs >= totalDuration;
} else {
phase = 'routing';
}
if (elapsedMs <= feedStart) {
// Spawn dwell at belt entry (A).
const r = poseOnSurface('main_belt', 0, itemHeightM);
pos = r.pos; rotY = r.rotY; surface = 'main_belt'; phase = 'feed';
} else if (elapsedMs <= inspectStart) {
// Feed along the main belt A → inspection.
const t = (elapsedMs - feedStart) / (inspectStart - feedStart);
const r = poseOnSurface('main_belt', t, itemHeightM);
pos = r.pos; rotY = r.rotY; surface = 'main_belt'; phase = 'feed';
} else if (elapsedMs <= junctionStart) {
// Dwell under the inspection station.
const r = poseOnSurface('inspection_station', 0, itemHeightM);
pos = r.pos; rotY = r.rotY; surface = 'inspection_station'; phase = 'inspection';
} else if (elapsedMs <= routingStart) {
// Travel to the routing junction.
const t = (elapsedMs - junctionStart) / (routingStart - junctionStart);
const r = poseOnSurface('routing_junction', t, itemHeightM);
pos = r.pos; rotY = r.rotY; surface = 'routing_junction'; phase = 'decision';
} else if (category === 'B') {
// B: travel along the receiving tray, then rest inside it.
const travelSpan = clearStart - routingStart;
const t = (elapsedMs - routingStart) / travelSpan;
if (t < 1) {
const r = poseOnSurface('b_receiver', t, itemHeightM);
pos = r.pos; rotY = r.rotY; surface = 'b_receiver'; phase = 'routing';
} else {
// C or D
const isC = category === 'C';
const targetZ = isC ? ZONES.C.z : ZONES.D.z;
const targetX = isC ? ZONES.C.x : ZONES.D.x;
const t = Math.max(0, Math.min((elapsedMs - routingStart) / routingDuration, 1.0));
if (t < 1.0) {
phase = 'routing';
surface = isC ? 'chute_c' : 'chute_d';
// Slide down the chute
posX = ZONES.GATE.x + (targetX - ZONES.GATE.x) * t;
posZ = targetZ * t;
// Y drops from belt to cage floor
const cageFloorY = 0.1; // approximate from ROLL_CAGE
const targetY = cageFloorY + itemHeightM / 2;
posY = beltY - (beltY - targetY) * (t * t); // slight ease-in
// Slight rotation to face chute
const angle = Math.atan2(targetZ, targetX - ZONES.GATE.x);
rotY = -angle * t;
} else {
phase = 'settled';
isSettled = elapsedMs >= totalDuration;
surface = isC ? 'c_cage' : 'd_cage';
// Inside cage. Slot index offset to prevent perfect overlap.
const cageCenterX = targetX;
const cageCenterZ = targetZ;
const cageFloorY = 0.1;
// Deterministic offset based on slotIndex
// Cage size is 1.2 x 0.8
const offsetX = ((slotIndex % 3) - 1) * 0.2;
const offsetZ = ((Math.floor(slotIndex / 3) % 2) - 0.5) * 0.2;
posX = cageCenterX + offsetX;
posZ = cageCenterZ + offsetZ;
posY = cageFloorY + itemHeightM / 2;
// Final scattered rotation
rotY = (slotIndex * 45) * Math.PI / 180;
}
const r = bReceiverSlot(slotIndex, itemHeightM);
pos = r.pos; rotY = r.rotY; surface = 'b_receiver'; phase = 'settled';
isSettled = elapsedMs >= total;
}
} else {
// C / D: slide down the chute, then settle on the cage floor.
const chuteName: SurfaceName = category === 'C' ? 'chute_c' : 'chute_d';
const cageName: SurfaceName = category === 'C' ? 'c_cage_floor' : 'd_cage_floor';
const travelSpan = clearStart - routingStart;
const t = (elapsedMs - routingStart) / travelSpan;
if (t < 1) {
const r = poseOnSurface(chuteName, t, itemHeightM);
pos = r.pos; rotY = r.rotY; surface = chuteName; phase = 'routing';
} else {
const r = cageSlot(cageName, slotIndex, itemHeightM);
pos = r.pos; rotY = r.rotY; surface = cageName; phase = 'settled';
isSettled = elapsedMs >= total;
}
}
// If case is entirely finished, force settled
if (elapsedMs >= totalDuration && phase !== 'settled') {
isSettled = true;
phase = 'settled';
// Guarantee no NaN/Infinity escapes.
if (!Number.isFinite(pos[0]) || !Number.isFinite(pos[1]) || !Number.isFinite(pos[2])) {
pos = [SURFACES.main_belt.start[0], SURFACES.main_belt.surfaceY + itemHeightM / 2, 0];
}
return {
position: [posX, posY, posZ],
position: pos,
rotation: [0, rotY, 0],
surface,
phase,

View File

@@ -131,6 +131,32 @@ export const ROLL_CAGE = {
frameThickness: 0.03, // 30mm frame tube
};
/** Interior floor height of the roll cage where items rest (just above wheels). */
export const CAGE_FLOOR_Y = ROLL_CAGE.wheelRadius * 2; // 0.08m
// =========================================================
// Physical surface widths (per OZON spec)
// =========================================================
export const MAIN_BELT_WIDTH_M = CONVEYOR_WIDTH_M; // 0.5m
export const CHUTE_C_WIDTH_M = 0.5; // 500mm chute
export const CHUTE_D_WIDTH_M = 0.5; // 500mm chute
export const CHUTE_SLOPE_START_Y = BELT_TOP_Y; // 0.7m at junction
export const CHUTE_END_Y = CAGE_FLOOR_Y + 0.05; // safe entry height into cage
// =========================================================
// B receiving zone (short downstream receiving tray after sorter)
// Physical tray at belt height with low side walls and an end stop,
// so B items visibly land and remain instead of vanishing.
// =========================================================
export const B_RECEIVER = {
startX: ZONES.GATE.x + 0.7, // 2.2m — begins after routing junction
endX: ZONES.B.x + 0.4, // 4.4m — end stop
y: BELT_TOP_Y, // 0.7m top surface
width: CONVEYOR_WIDTH_M, // 0.5m
wallHeight: 0.12, // 120mm side/end walls
restX: ZONES.B.x, // 4.0m — where the item comes to rest
};
// =========================================================
// Item positioning and scaling
// =========================================================