Spaces:
Running
Running
Download frontend/src/components/3DTrace.js from xenecode/Jaguar_Project: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/spaces/xenecode/Jaguar_Project/resolve/main/frontend/src/components/3DTrace.js
- Command line
-
hf download hf://spaces/xenecode/Jaguar_Project/frontend/src/components/3DTrace.js
-
curl -L -o 3DTrace.js https://huggingface.co/spaces/xenecode/Jaguar_Project/resolve/main/frontend/src/components/3DTrace.js
11.7 kB
| import { useEffect, useRef } from 'react'; | |
| import * as THREE from 'three'; | |
| import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; | |
| import URDFLoader from 'urdf-loader'; | |
| import PropTypes from 'prop-types'; | |
| import { createIKSolver, JOINT_NAMES } from './scene/kinematics'; | |
| import { createScanCell } from './scene/scanCell'; | |
| import { createDemoScan } from './scene/demoScan'; | |
| // FR5 model: from the FAIR-INNOVATION/frcobot_ros2 fairino_description package | |
| const ROBOT_PACKAGE_URL = `${process.env.PUBLIC_URL}/robots/fr5`; | |
| const URDF_URL = `${ROBOT_PACKAGE_URL}/fairino5_v6.urdf`; | |
| // The URDF wrist3_link frame is on the joint axis; the flange is 100 mm ahead (verified against the controller's TCP) | |
| const FLANGE_OFFSET = 0.1; | |
| const MAX_TRACE_POINTS = 600; | |
| const MIN_TRACE_STEP = 0.001; // don't add movements smaller than 1 mm to the trace | |
| const JOINT_SMOOTHING = 12; // the larger this is, the faster the robot catches up to the target angle | |
| const READOUT_INTERVAL = 0.1; // update the joint readout 10 times per second | |
| // If the demo starts before live data arrives, the robot starts from the controller's standby pose rather than the URDF's zero pose (arm horizontal) | |
| const HOME_ANGLES = [0, -90, 90, -90, -90, 0].map(THREE.MathUtils.degToRad); | |
| // The camera looks at the scan area and the table; during the demo it sways slowly around this angle | |
| const CAMERA_POSITION = [0.2, 0.85, 1.2]; | |
| const CAMERA_TARGET = [-0.4, 0.4, 0.1]; | |
| const SWAY_AMPLITUDE = 0.45; // rad | |
| const SWAY_SPEED = 0.25; | |
| const SWAY_PAUSE_AFTER_INTERACTION = 6; // s | |
| function ThreeDTrace({ containerRef, joints, demo = false, scanActive = false, partHeld = false, readoutRef }) { | |
| const targetJointsRef = useRef(null); | |
| const stateRef = useRef({ demo, scanActive, partHeld }); | |
| // The controller sends degrees, the URDF expects radians | |
| useEffect(() => { | |
| if (!joints) return; | |
| targetJointsRef.current = JOINT_NAMES.map((name) => | |
| THREE.MathUtils.degToRad(joints[name] ?? 0) | |
| ); | |
| }, [joints]); | |
| useEffect(() => { | |
| stateRef.current = { demo, scanActive, partHeld }; | |
| }, [demo, scanActive, partHeld]); | |
| useEffect(() => { | |
| const container = containerRef.current; | |
| if (!container) return undefined; | |
| // Scene - matte background | |
| const scene = new THREE.Scene(); | |
| scene.background = new THREE.Color(0x16181b); | |
| // Scene unit is meters (same as the URDF) | |
| const camera = new THREE.PerspectiveCamera( | |
| 45, | |
| container.clientWidth / container.clientHeight, | |
| 0.01, | |
| 50 | |
| ); | |
| camera.position.set(...CAMERA_POSITION); | |
| const renderer = new THREE.WebGLRenderer({ antialias: true }); | |
| renderer.setSize(container.clientWidth, container.clientHeight); | |
| renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); | |
| renderer.shadowMap.enabled = true; | |
| renderer.shadowMap.type = THREE.PCFSoftShadowMap; | |
| container.appendChild(renderer.domElement); | |
| const controls = new OrbitControls(camera, renderer.domElement); | |
| controls.target.set(...CAMERA_TARGET); | |
| controls.enableDamping = true; | |
| controls.dampingFactor = 0.08; | |
| controls.maxPolarAngle = Math.PI / 2; // don't go below the floor | |
| controls.minDistance = 0.3; | |
| controls.maxDistance = 4; | |
| controls.update(); | |
| // Floor: 10 cm grid and robot shadow | |
| scene.add(new THREE.GridHelper(2, 20, 0x5c626b, 0x2c3036)); | |
| const ground = new THREE.Mesh( | |
| new THREE.PlaneGeometry(4, 4), | |
| new THREE.ShadowMaterial({ opacity: 0.35 }) | |
| ); | |
| ground.rotation.x = -Math.PI / 2; | |
| ground.receiveShadow = true; | |
| scene.add(ground); | |
| scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 1.2)); | |
| const keyLight = new THREE.DirectionalLight(0xffffff, 2); | |
| keyLight.position.set(1.5, 2.5, 1); | |
| keyLight.castShadow = true; | |
| keyLight.shadow.mapSize.set(2048, 2048); | |
| Object.assign(keyLight.shadow.camera, { left: -1.5, right: 1.5, top: 1.5, bottom: -1.5, near: 0.1, far: 10 }); | |
| scene.add(keyLight); | |
| // Robot base frame: the URDF and controller are Z-up, three.js is Y-up | |
| const robotBase = new THREE.Group(); | |
| robotBase.rotation.x = -Math.PI / 2; | |
| robotBase.add(new THREE.AxesHelper(0.2)); | |
| scene.add(robotBase); | |
| // Tables, parts, laser profiler | |
| const scanCell = createScanCell(robotBase); | |
| // Trace line - fixed-size buffer, not recreated every frame | |
| const tracePositions = new Float32Array(MAX_TRACE_POINTS * 3); | |
| const traceGeometry = new THREE.BufferGeometry(); | |
| traceGeometry.setAttribute('position', new THREE.BufferAttribute(tracePositions, 3)); | |
| traceGeometry.setDrawRange(0, 0); | |
| const traceLine = new THREE.Line( | |
| traceGeometry, | |
| new THREE.LineBasicMaterial({ color: 0xf97316 }) | |
| ); | |
| traceLine.frustumCulled = false; | |
| scene.add(traceLine); | |
| let traceCount = 0; | |
| const pushTracePoint = (point) => { | |
| if (traceCount === MAX_TRACE_POINTS) { | |
| tracePositions.copyWithin(0, 3); | |
| traceCount -= 1; | |
| } | |
| point.toArray(tracePositions, traceCount * 3); | |
| traceCount += 1; | |
| traceGeometry.setDrawRange(0, traceCount); | |
| traceGeometry.attributes.position.needsUpdate = true; | |
| }; | |
| // Robot model | |
| let robot = null; | |
| let flange = null; | |
| let ik = null; | |
| let demoScan = null; | |
| let disposed = false; | |
| const manager = new THREE.LoadingManager(); | |
| manager.onLoad = () => { | |
| robot?.traverse((child) => { | |
| if (child.isMesh) { | |
| child.castShadow = true; | |
| child.receiveShadow = true; | |
| } | |
| }); | |
| }; | |
| const loader = new URDFLoader(manager); | |
| loader.packages = { fairino_description: ROBOT_PACKAGE_URL }; | |
| loader.load( | |
| URDF_URL, | |
| (loadedRobot) => { | |
| if (disposed) return; | |
| robot = loadedRobot; | |
| flange = new THREE.Object3D(); | |
| flange.position.z = FLANGE_OFFSET; | |
| flange.add( | |
| new THREE.Mesh( | |
| new THREE.SphereGeometry(0.008, 16, 12), | |
| new THREE.MeshBasicMaterial({ color: 0xf97316 }) | |
| ) | |
| ); | |
| robot.links.wrist3_link.add(flange); | |
| robotBase.add(robot); | |
| scanCell.attachGripper(flange); | |
| ik = createIKSolver({ robot, tip: flange, base: robotBase }); | |
| demoScan = createDemoScan({ ik, cell: scanCell }); | |
| if (process.env.NODE_ENV === 'development') { | |
| window.__jaguarScene = { robot, robotBase, flange, ik, scanCell, camera, controls }; | |
| } | |
| }, | |
| undefined, | |
| (error) => console.error('Failed to load robot model:', error) | |
| ); | |
| // Camera sway during the demo; it pauses for a while once the user rotates the scene | |
| const baseAzimuth = controls.getAzimuthalAngle(); | |
| let elapsed = 0; | |
| let lastInteraction = -Infinity; | |
| controls.addEventListener('start', () => { | |
| lastInteraction = Infinity; | |
| }); | |
| controls.addEventListener('end', () => { | |
| lastInteraction = elapsed; | |
| }); | |
| const updateCameraSway = (isDemo) => { | |
| controls.autoRotate = isDemo && elapsed - lastInteraction > SWAY_PAUSE_AFTER_INTERACTION; | |
| if (!controls.autoRotate) return; | |
| // A positive speed decreases the azimuth | |
| const azimuth = controls.getAzimuthalAngle(); | |
| if (azimuth > baseAzimuth + SWAY_AMPLITUDE) controls.autoRotateSpeed = SWAY_SPEED; | |
| else if (azimuth < baseAzimuth - SWAY_AMPLITUDE) controls.autoRotateSpeed = -SWAY_SPEED; | |
| }; | |
| controls.autoRotateSpeed = SWAY_SPEED; | |
| // Animation loop | |
| const clock = new THREE.Clock(); | |
| const tip = new THREE.Vector3(); | |
| const lastTip = new THREE.Vector3(Infinity, Infinity, Infinity); | |
| let posed = false; | |
| let frameId; | |
| let demoRunning = false; | |
| let lastMode = stateRef.current.demo; | |
| let readoutElapsed = READOUT_INTERVAL; | |
| const resetTrace = () => { | |
| traceCount = 0; | |
| traceGeometry.setDrawRange(0, 0); | |
| lastTip.set(Infinity, Infinity, Infinity); | |
| }; | |
| // The joint readout is written directly to the DOM instead of through React: avoids 10 renders per second | |
| const updateReadout = () => { | |
| const root = readoutRef?.current; | |
| if (!root || !robot) return; | |
| JOINT_NAMES.forEach((name) => { | |
| const node = root.querySelector(`[data-joint="${name}"]`); | |
| if (node) node.textContent = THREE.MathUtils.radToDeg(robot.joints[name].angle).toFixed(1); | |
| }); | |
| }; | |
| const animate = () => { | |
| frameId = requestAnimationFrame(animate); | |
| const dt = Math.min(clock.getDelta(), 0.1); | |
| elapsed += dt; | |
| const { demo: isDemo, scanActive: laserLive, partHeld: holdingLive } = stateRef.current; | |
| // Clear the old trace when switching between demo and live data, so the two paths don't mix | |
| if (isDemo !== lastMode) { | |
| resetTrace(); | |
| lastMode = isDemo; | |
| } | |
| updateCameraSway(isDemo); | |
| if (robot) { | |
| if (isDemo) { | |
| if (!demoRunning) { | |
| demoScan.start(posed ? ik.getAngles() : HOME_ANGLES); | |
| demoRunning = true; | |
| } | |
| ik.setAngles(demoScan.update(dt)); | |
| } else { | |
| if (demoRunning) { | |
| demoScan.stop(); | |
| demoRunning = false; | |
| } | |
| const target = targetJointsRef.current; | |
| if (target) { | |
| // Jump straight to position on the first data point, then follow smoothly | |
| const k = posed ? 1 - Math.exp(-dt * JOINT_SMOOTHING) : 1; | |
| posed = true; | |
| JOINT_NAMES.forEach((name, i) => { | |
| const joint = robot.joints[name]; | |
| joint.setJointValue(joint.angle + (target[i] - joint.angle) * k); | |
| }); | |
| } | |
| // The laser is on during a real scan; the scene computes whether the part actually passes through the laser | |
| scanCell.setLaser(laserLive, laserLive); | |
| scanCell.setLiveHold(holdingLive); | |
| } | |
| scene.updateMatrixWorld(); | |
| scanCell.update(); | |
| flange.getWorldPosition(tip); | |
| if (tip.distanceTo(lastTip) > MIN_TRACE_STEP) { | |
| pushTracePoint(tip); | |
| lastTip.copy(tip); | |
| } | |
| readoutElapsed += dt; | |
| if (readoutElapsed >= READOUT_INTERVAL) { | |
| readoutElapsed = 0; | |
| updateReadout(); | |
| } | |
| } | |
| controls.update(); | |
| renderer.render(scene, camera); | |
| }; | |
| animate(); | |
| // When the panel size changes (window, touchscreen rotation, etc.) | |
| const resizeObserver = new ResizeObserver(() => { | |
| if (!container.clientWidth || !container.clientHeight) return; | |
| camera.aspect = container.clientWidth / container.clientHeight; | |
| camera.updateProjectionMatrix(); | |
| renderer.setSize(container.clientWidth, container.clientHeight); | |
| }); | |
| resizeObserver.observe(container); | |
| return () => { | |
| disposed = true; | |
| scanCell.dispose(); | |
| if (window.__jaguarScene?.robot === robot) delete window.__jaguarScene; | |
| cancelAnimationFrame(frameId); | |
| resizeObserver.disconnect(); | |
| controls.dispose(); | |
| scene.traverse((obj) => { | |
| obj.geometry?.dispose(); | |
| [].concat(obj.material ?? []).forEach((material) => material.dispose()); | |
| }); | |
| renderer.dispose(); | |
| container.removeChild(renderer.domElement); | |
| }; | |
| }, [containerRef, readoutRef]); | |
| return null; | |
| } | |
| ThreeDTrace.propTypes = { | |
| containerRef: PropTypes.object.isRequired, | |
| joints: PropTypes.shape({ | |
| j1: PropTypes.number, | |
| j2: PropTypes.number, | |
| j3: PropTypes.number, | |
| j4: PropTypes.number, | |
| j5: PropTypes.number, | |
| j6: PropTypes.number, | |
| }), | |
| demo: PropTypes.bool, | |
| scanActive: PropTypes.bool, | |
| partHeld: PropTypes.bool, | |
| readoutRef: PropTypes.object, | |
| }; | |
| export default ThreeDTrace; | |