Duc Do commited on
Upload 254 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .agents/AGENTS.mdAdded+2
- .agents/rules/ai-log-hook.mdAdded+37
- .agents/rules/caveman.mdAdded+13
- .agents/workflows/log.mdAdded+36
- .ai-log/.gitkeepAdded
- .claude/settings.jsonAdded+38
- .codex/hooks.jsonAdded+27
- .cursor/hooks.jsonAdded+15
- .envAdded+16
- .env.exampleAdded+15
- .gemini/settings.jsonAdded+42
- .github/hooks/hooks.jsonAdded+21
- .gitignoreAdded+41
- .history/frontend/app_20260627225036.jsAdded+675
- .history/frontend/app_20260627231401.jsAdded+511
- .history/frontend/app_20260627231409.jsAdded+511
- .history/frontend/app_20260627231430.jsAdded+511
- .history/frontend/app_20260627231706.jsAdded+1177
- .history/frontend/index_20260627225036.cssAdded+595
- .history/frontend/index_20260627225036.htmlAdded+125
- .history/frontend/index_20260627231836.htmlAdded+1177
- .history/frontend/index_20260627231838.htmlAdded+125
- .history/frontend/index_20260627231852.htmlAdded+388
- .history/frontend/index_20260627232058.cssAdded+569
- .history/frontend/index_20260627232102.cssAdded+569
- .history/frontend/index_20260627232122.cssAdded+937
- .history/frontend/interactive_server_20260627225036.pyAdded+524
- .history/frontend/interactive_server_20260627232008.pyAdded+569
- .pytest_cache/.gitignoreAdded+2
- .pytest_cache/CACHEDIR.TAGAdded+4
- .pytest_cache/README.mdAdded+8
- .pytest_cache/v/cache/lastfailedAdded+3
- .pytest_cache/v/cache/nodeidsAdded+53
- .pytest_cache/v/cache/stepwiseAdded+1
- DockerfileAdded+45
- EVAL_EVIDENCES.mdAdded+163
- GeoFIK/README.mdAdded+295
- GeoFIK/example_geofik.cppAdded+273
- GeoFIK/frames.pngAdded
- GeoFIK/geofik.cppAdded+2108
- GeoFIK/geofik.hAdded+201
- JOURNAL.mdAdded
- README.md+117-10
- README_LLM_PANDA.mdAdded+265
- SYSTEM_ANALYSIS.mdAdded+230
- SYSTEM_DESIGN.mdAdded+337
- TrajOpt_Implementation_Guide.mdAdded+181
- WORKLOG.mdAdded+67
- __pycache__/main.cpython-310.pycAdded
- debug_log.txtAdded
12
- DO NOT delete any files in the repository unless the user gives an explicit and unambiguous command to do so. If the command is ambiguous, ignore the request to delete or ask for confirmation.12345678910111213141516171819202122232425262728293031323334353637---
description: "AI usage logging is fully automatic — do NOT call any log_* script manually"
activation: always-on
---
# AI Usage Logging — Automatic
Logging prompt vào `.ai-log/session.jsonl` đã được **tự động hoá hoàn toàn**. Bạn (AI agent) **KHÔNG** cần — và **KHÔNG** nên — chạy bất kỳ lệnh logging nào sau mỗi task.
## Cơ chế
Khi student `git push`:
1. Pre-push hook chạy `scripts/log_antigravity.py --auto`, đọc trực tiếp transcript của các conversation Antigravity từ `~/.gemini/antigravity-ide/brain/<conv>/.system_generated/logs/transcript.jsonl` và sweep mọi prompt (`USER_INPUT` + `USER_EXPLICIT`) thuộc về repo hiện tại trong 24 giờ gần nhất.
2. Pre-push hook chạy `scripts/submit_log.py`, đẩy `.ai-log/session.jsonl` lên grading server.
Toàn bộ prompt user đã gõ trong Antigravity IDE được capture **nguyên văn từ disk**, không cần AI tự tóm tắt.
## Không làm những việc sau
- ❌ **KHÔNG** gọi `scripts/log_antigravity.py "<summary>" "<model>"` sau mỗi task. Lệnh này đã bị deprecate; nếu vô tình gọi sẽ tạo log entry giả mạo dạng "TaskComplete" không phải prompt thật của user.
- ❌ **KHÔNG** chạy `scripts/log_manual.py` cho Antigravity — chỉ dùng nó cho ChatGPT / web tool (xem `.agents/workflows/log.md`).
- ❌ **KHÔNG** sửa hoặc xoá file trong `.ai-log/` — chúng được pre-push hook và submit script quản lý.
## Khi nào cần can thiệp
- Nếu pre-push hook báo lỗi → báo lại cho user, đừng tự ý bypass `--no-verify`.
- Nếu student dùng tool không nằm trong list auto-hook (ChatGPT, Gemini Web, v.v.) → trỏ họ tới `.agents/workflows/log.md` để log thủ công.
## Cài đặt một lần sau khi clone repo
```bash
# Linux / macOS / Git Bash
bash scripts/setup_hooks.sh
# Windows PowerShell
powershell -ExecutionPolicy Bypass -File scripts\setup_hooks.ps1
```12345678910111213---
description: "Enforces a highly compressed, caveman-style communication style to save tokens and improve response speed"
activation: always-on
---
# Caveman Communication Style
To save tokens and optimize speed, you MUST communicate with the user using a primitive, highly compressed, and direct style ("caveman style"):
- Avoid conversational filler, polite greetings, pleasantries, transitions, and sign-offs.
- Keep all explanations as brief, direct, and minimal as possible.
- Use short, clipped sentences.
- Prioritize showing code changes, command outputs, or results directly without preambles or post-ambles.
- If user requests detailed explanations, provide them, but otherwise stay extremely concise.123456789101112131415161718192021222324252627282930313233343536---
description: "Ghi log AI thủ công — CHỈ dùng cho web tool (ChatGPT, Gemini Web, Claude.ai, v.v.). KHÔNG dùng cho Antigravity."
---
# Ghi log AI thủ công (chỉ web tool)
Antigravity IDE, Claude Code, Cursor, Codex, Copilot, Gemini CLI đã **tự động log** qua hook hoặc qua `log_antigravity.py` chạy trong pre-push. **Không cần** chạy lệnh dưới đây cho các tool đó.
Workflow này chỉ dành cho khi bạn dùng **tool web không có hook** — ví dụ ChatGPT, Gemini Web, Claude.ai, Perplexity, v.v.
## Cách chạy
**Linux / macOS / Git Bash:**
```bash
# Interactive mode (script sẽ hỏi tool + prompt)
bash scripts/_pyrun.sh scripts/log_manual.py
# One-line mode
bash scripts/_pyrun.sh scripts/log_manual.py --tool "<tên tool>" --prompt "<mô tả việc đã làm>"
```
**Windows (cmd.exe / PowerShell):**
```cmd
scripts\_pyrun.cmd scripts\log_manual.py
scripts\_pyrun.cmd scripts\log_manual.py --tool "<tên tool>" --prompt "<mô tả việc đã làm>"
```
## Ví dụ
```bash
bash scripts/_pyrun.sh scripts/log_manual.py --tool chatgpt --prompt "Brainstorm UI layout for verify page"
bash scripts/_pyrun.sh scripts/log_manual.py --tool gemini-web --prompt "Research risk scoring algorithms"
bash scripts/_pyrun.sh scripts/log_manual.py --tool claude-web --prompt "Explain OAuth2 PKCE flow"
```
Entry sẽ được append vào `.ai-log/session.jsonl` và submit cùng các log auto khác trong lần `git push` kế tiếp.1234567891011121314151617181920212223242526272829303132333435363738{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=claude",
"shell": "bash"
}
]
}
],
"PostToolUse": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=claude",
"shell": "bash"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=claude",
"shell": "bash"
}
]
}
]
}
}123456789101112131415161718192021222324252627{
"version": "1.0",
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"name": "log-prompt",
"command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=codex",
"timeout": 10
}
]
}
],
"Stop": [
{
"hooks": [
{
"name": "log-stop",
"command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=codex",
"timeout": 10
}
]
}
]
}
}123456789101112131415{
"version": 1,
"hooks": {
"beforeSubmitPrompt": [
{
"command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=cursor"
}
],
"stop": [
{
"command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=cursor"
}
]
}
}12345678910111213141516# Choose one or both providers
OPENAI_API_KEY=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
OPENAI_BASE_URL=https://openrouter.ai/api/v1
OPENAI_MODEL=deepseek/deepseek-v4-flash
# Default model
DEFAULT_MODEL=claude-sonnet-4-20250514
# DEFAULT_MODEL=gpt-4o
# Logging
LOG_LEVEL=INFO
# AI Hook Logging (set by instructor)
AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
AI_LOG_DIR=.ai-log123456789101112131415# Choose one or both providers
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
# Default model
DEFAULT_MODEL=claude-sonnet-4-20250514
# DEFAULT_MODEL=gpt-4o
# Logging
LOG_LEVEL=INFO
# AI Hook Logging (set by instructor)
AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
AI_LOG_API_KEY=f3p1dEOhD_z8qjjtbeCtb2t9ASMEliz-4juZfWe3ZPgCtPZp-LjWthBfeNU8d5dP
AI_LOG_DIR=.ai-log123456789101112131415161718192021222324252627282930313233343536373839404142{
"hooks": {
"BeforeAgent": [
{
"hooks": [
{
"name": "log-prompt",
"type": "command",
"command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=gemini",
"timeout": 10000
}
]
}
],
"AfterModel": [
{
"matcher": ".*",
"hooks": [
{
"name": "log-model",
"type": "command",
"command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=gemini",
"timeout": 10000
}
]
}
],
"SessionEnd": [
{
"matcher": ".*",
"hooks": [
{
"name": "log-session-end",
"type": "command",
"command": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=gemini",
"timeout": 10000
}
]
}
]
}
}123456789101112131415161718192021{
"version": 1,
"hooks": {
"userPromptSubmitted": [
{
"type": "command",
"bash": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=copilot",
"powershell": "scripts\\_pyrun.cmd scripts\\log_hook.py --tool=copilot",
"timeoutSec": 10
}
],
"sessionEnd": [
{
"type": "command",
"bash": "bash scripts/_pyrun.sh scripts/log_hook.py --tool=copilot",
"powershell": "scripts\\_pyrun.cmd scripts\\log_hook.py --tool=copilot",
"timeoutSec": 10
}
]
}
}1234567891011121314151617181920212223242526272829303132333435363738394041# Environment
.env
# Python
__pycache__/
*.py[cod]
*$py.class
venv/
.venv/
pybullet_env/
build/
*.egg-info/
.pytest_cache/
.mypy_cache/
# OS
.DS_Store
# AI logs — tracked structure, ignored content
.ai-log/*.jsonl
.ai-log/**/*.jsonl
# Simulation outputs
outputs/
# Large local object assets
assets/objects/
# PyBullet local/install artifacts
pybullet/
pybullet_data/
bullet3/
*.pyd
# Large external packages and zips
pybullet-object-models.zip
pybullet-object-models/
test_log/
scratch/
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675// ─── WebSocket and Visualizer Setup ────────────────────────────────────────
const canvas = document.getElementById('pybullet-viewport');
// Three.js Core Variables
let renderer, scene, camera, controls;
let robotGroup, tableMesh, trayMesh;
const slotHelpers = [];
const joints = {};
const ycbMeshes = {};
const OBJ_LOADER = new THREE.OBJLoader();
const MTL_LOADER = new THREE.MTLLoader();
let socket = null;
let currentPrompt = '';
function initVisualizer() {
// Set default coordinate system to Z-up
THREE.Object3D.DefaultUp.set(0, 0, 1);
// Renderer
renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
const width = canvas.clientWidth || window.innerWidth;
const height = canvas.clientHeight || window.innerHeight;
renderer.setSize(width, height, false);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.shadowMap.enabled = true;
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color('#f1f5f9'); // Light smoke gray background
// Camera
camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100);
// Position camera to look down at the table, matching PyBullet default view
camera.position.set(1.2, -1.2, 1.2);
// Controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.target.set(0.5, 0.0, 0.2);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.maxPolarAngle = Math.PI / 2 - 0.02; // do not go below table plane
controls.update();
// Lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.85);
dirLight.position.set(2, -2, 4);
dirLight.castShadow = true;
dirLight.shadow.mapSize.width = 1024;
dirLight.shadow.mapSize.height = 1024;
dirLight.shadow.camera.near = 0.5;
dirLight.shadow.camera.far = 15;
scene.add(dirLight);
const dirLight2 = new THREE.DirectionalLight(0xaaccff, 0.35);
dirLight2.position.set(-2, 2, 2);
scene.add(dirLight2);
// Floor plane
const planeGeo = new THREE.PlaneGeometry(10, 10);
const planeMat = new THREE.MeshStandardMaterial({ color: 0xe2e8f0, roughness: 0.85 });
const plane = new THREE.Mesh(planeGeo, planeMat);
plane.receiveShadow = true;
scene.add(plane);
// Caro background / Grid Helper
const gridHelper = new THREE.GridHelper(10, 100, 0x94a3b8, 0xcbd5e1);
gridHelper.rotation.x = Math.PI / 2;
gridHelper.position.z = 0.001;
scene.add(gridHelper);
// Axes helper (X: Red, Y: Green, Z: Blue)
const axesHelper = new THREE.AxesHelper(0.5);
axesHelper.position.z = 0.002;
scene.add(axesHelper);
// Start animation loop
animate();
}
function animate() {
requestAnimationFrame(animate);
if (controls) controls.update();
renderer.render(scene, camera);
}
// Window resizing
window.addEventListener('resize', () => {
const width = canvas.clientWidth;
const height = canvas.clientHeight;
if (canvas.width !== width || canvas.height !== height) {
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
});
// ─── Three.js Scene Construction ────────────────────────────────────────────
function createTable(tableConfig) {
if (tableMesh) scene.remove(tableMesh);
const ext = tableConfig.half_extents;
const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2);
const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3));
const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 });
tableMesh = new THREE.Mesh(geo, mat);
tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]);
tableMesh.castShadow = true;
tableMesh.receiveShadow = true;
scene.add(tableMesh);
}
function createTray(trayConfig) {
if (trayMesh) scene.remove(trayMesh);
const ext = trayConfig.half_extents;
const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2);
const color = new THREE.Color().fromArray(trayConfig.color.slice(0, 3));
const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.7 });
trayMesh = new THREE.Mesh(geo, mat);
trayMesh.position.set(trayConfig.position[0], trayConfig.position[1], trayConfig.position[2] - ext[2]);
trayMesh.castShadow = true;
trayMesh.receiveShadow = true;
scene.add(trayMesh);
}
function createSlotHelpers(slots) {
slotHelpers.forEach(mesh => scene.remove(mesh));
slotHelpers.length = 0;
const geom = new THREE.RingGeometry(0.045, 0.05, 32);
const mat = new THREE.MeshBasicMaterial({ color: 0x3b82f6, side: THREE.DoubleSide, transparent: true, opacity: 0.45 });
Object.entries(slots).forEach(([name, pos]) => {
const ring = new THREE.Mesh(geom, mat);
ring.position.set(pos[0], pos[1], pos[2] + 0.001); // slightly above table
scene.add(ring);
slotHelpers.push(ring);
});
}
function initRobotStructure() {
if (robotGroup) scene.remove(robotGroup);
robotGroup = new THREE.Group();
scene.add(robotGroup);
joints.joint1 = new THREE.Group();
joints.joint2 = new THREE.Group();
joints.joint3 = new THREE.Group();
joints.joint4 = new THREE.Group();
joints.joint5 = new THREE.Group();
joints.joint6 = new THREE.Group();
joints.joint7 = new THREE.Group();
joints.joint8 = new THREE.Group();
joints.handJoint = new THREE.Group();
joints.fingerJoint1 = new THREE.Group();
joints.fingerJoint2 = new THREE.Group();
const link0 = new THREE.Group();
const link1 = new THREE.Group();
const link2 = new THREE.Group();
const link3 = new THREE.Group();
const link4 = new THREE.Group();
const link5 = new THREE.Group();
const link6 = new THREE.Group();
const link7 = new THREE.Group();
const link8 = new THREE.Group();
const hand = new THREE.Group();
const leftFinger = new THREE.Group();
const rightFinger = new THREE.Group();
robotGroup.add(link0);
link0.add(joints.joint1);
joints.joint1.position.set(0, 0, 0.333);
joints.joint1.add(link1);
link1.add(joints.joint2);
joints.joint2.position.set(0, 0, 0);
joints.joint2.rotation.set(-1.57079632679, 0, 0);
joints.joint2.add(link2);
link2.add(joints.joint3);
joints.joint3.position.set(0, -0.316, 0);
joints.joint3.rotation.set(1.57079632679, 0, 0);
joints.joint3.add(link3);
link3.add(joints.joint4);
joints.joint4.position.set(0.0825, 0, 0);
joints.joint4.rotation.set(1.57079632679, 0, 0);
joints.joint4.add(link4);
link4.add(joints.joint5);
joints.joint5.position.set(-0.0825, 0.384, 0);
joints.joint5.rotation.set(-1.57079632679, 0, 0);
joints.joint5.add(link5);
link5.add(joints.joint6);
joints.joint6.position.set(0, 0, 0);
joints.joint6.rotation.set(1.57079632679, 0, 0);
joints.joint6.add(link6);
link6.add(joints.joint7);
joints.joint7.position.set(0.088, 0, 0);
joints.joint7.rotation.set(1.57079632679, 0, 0);
joints.joint7.add(link7);
link7.add(joints.joint8);
joints.joint8.position.set(0, 0, 0.107);
joints.joint8.add(link8);
link8.add(joints.handJoint);
joints.handJoint.position.set(0, 0, 0);
joints.handJoint.rotation.set(0, 0, -0.785398163397);
joints.handJoint.add(hand);
hand.add(joints.fingerJoint1);
joints.fingerJoint1.position.set(0, 0, 0.0584);
joints.fingerJoint1.add(leftFinger);
hand.add(joints.fingerJoint2);
joints.fingerJoint2.position.set(0, 0, 0.0584);
joints.fingerJoint2.add(rightFinger);
const defaultPandaMaterial = new THREE.MeshStandardMaterial({
color: 0xdddddd,
roughness: 0.35,
metalness: 0.15
});
const loadModel = (parent, objPath, mtlPath = null, rotateRightFinger = false) => {
const applyRotation = (obj) => {
if (rotateRightFinger) {
obj.rotation.z = Math.PI;
}
parent.add(obj);
};
if (mtlPath) {
MTL_LOADER.load(mtlPath, (materials) => {
materials.preload();
const objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.load(objPath, (obj) => {
obj.traverse(child => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
applyRotation(obj);
});
});
} else {
const objLoader = new THREE.OBJLoader();
objLoader.load(objPath, (obj) => {
obj.traverse(child => {
if (child.isMesh) {
child.material = defaultPandaMaterial;
child.castShadow = true;
child.receiveShadow = true;
}
});
applyRotation(obj);
});
}
};
loadModel(link0, '/assets/panda/meshes/collision/link0.obj');
loadModel(link1, '/assets/panda/meshes/visual/link1.obj', '/assets/panda/meshes/visual/link1.mtl');
loadModel(link2, '/assets/panda/meshes/visual/link2.obj', '/assets/panda/meshes/visual/link2.mtl');
loadModel(link3, '/assets/panda/meshes/visual/link3.obj', '/assets/panda/meshes/visual/link3.mtl');
loadModel(link4, '/assets/panda/meshes/visual/link4.obj', '/assets/panda/meshes/visual/link4.mtl');
loadModel(link5, '/assets/panda/meshes/visual/link5.obj', '/assets/panda/meshes/visual/link5.mtl');
loadModel(link6, '/assets/panda/meshes/visual/link6.obj', '/assets/panda/meshes/visual/link6.mtl');
loadModel(link7, '/assets/panda/meshes/collision/link7.obj');
loadModel(hand, '/assets/panda/meshes/visual/hand.obj', '/assets/panda/meshes/visual/hand.mtl');
loadModel(leftFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl');
loadModel(rightFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl', true);
}
function loadYcbObjects(objectsConfig) {
// Clear old meshes/groups from scene
Object.values(ycbMeshes).forEach(group => scene.remove(group));
for (const key in ycbMeshes) delete ycbMeshes[key];
Object.entries(objectsConfig).forEach(([name, config]) => {
const folder = config.folder;
let objFile = "";
let mtlFile = "";
if (folder === "YcbBanana" || folder === "YcbTomatoSoupCan" || folder === "YcbCrackerBox" || folder === "YcbMustardBottle" || folder === "YcbPottedMeatCan") {
objFile = `/assets/ycb/${folder}/textured_simple_reoriented.obj`;
mtlFile = `/assets/ycb/${folder}/textured_simple_reoriented.mtl`;
} else if (folder === "YcbChipsCan") {
objFile = `/assets/ycb/${folder}/textured.obj`;
mtlFile = `/assets/ycb/${folder}/textured.mtl`;
}
if (!objFile) return;
// Create a parent group to represent the object's body link pose
const objectGroup = new THREE.Group();
objectGroup.position.fromArray(config.initial_pos);
objectGroup.quaternion.fromArray(config.initial_ori);
scene.add(objectGroup);
ycbMeshes[name] = objectGroup;
// 1. Load Visual Mesh
MTL_LOADER.load(mtlFile, (materials) => {
materials.preload();
const objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.load(objFile, (visObj) => {
visObj.traverse(child => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
// Position, rotate and scale relative to parent group
if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos);
if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori);
if (config.vis_scale) visObj.scale.fromArray(config.vis_scale);
objectGroup.add(visObj);
});
});
// 2. Load Collision Mesh (Semi-transparent Blue)
const collObjFile = `/assets/ycb/${folder}/collision_vhacd.obj`;
const collLoader = new THREE.OBJLoader();
collLoader.load(collObjFile, (collObj) => {
collObj.traverse(child => {
if (child.isMesh) {
child.material = new THREE.MeshStandardMaterial({
color: 0x0000ff, // blue
transparent: true,
opacity: 0.5, // semi-transparent
roughness: 0.4,
metalness: 0.1
});
child.castShadow = true;
child.receiveShadow = true;
}
});
// Position, rotate and scale relative to parent group
if (config.coll_local_pos) collObj.position.fromArray(config.coll_local_pos);
if (config.coll_local_ori) collObj.quaternion.fromArray(config.coll_local_ori);
if (config.coll_scale) collObj.scale.fromArray(config.coll_scale);
objectGroup.add(collObj);
});
});
}
function updateSimulationState(jointsData, objectsData) {
if (jointsData && jointsData.length >= 11) {
joints.joint1.rotation.z = jointsData[0];
joints.joint2.rotation.z = jointsData[1];
joints.joint3.rotation.z = jointsData[2];
joints.joint4.rotation.z = jointsData[3];
joints.joint5.rotation.z = jointsData[4];
joints.joint6.rotation.z = jointsData[5];
joints.joint7.rotation.z = jointsData[6];
// Prismatic fingers:
joints.fingerJoint1.position.y = jointsData[9];
joints.fingerJoint2.position.y = -jointsData[10];
}
if (objectsData) {
Object.entries(objectsData).forEach(([name, data]) => {
const group = ycbMeshes[name];
if (group) {
group.position.fromArray(data.pos);
group.quaternion.fromArray(data.ori);
}
});
}
}
let reconnectTimeout = null;
function connectWebSocket() {
if (reconnectTimeout) {
clearTimeout(reconnectTimeout);
reconnectTimeout = null;
}
const guiToggle = document.getElementById('gui-toggle');
const showGui = guiToggle ? guiToggle.checked : false;
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=${showGui}`;
updateBadgeStatus('disconnected');
socket = new WebSocket(wsUrl);
socket.onopen = () => {
console.log("WebSocket connected.");
updateBadgeStatus('connected');
writeLog("🔌 Kết nối thành công đến Backend server.", "success");
};
socket.onmessage = (event) => {
const msg = JSON.parse(event.data);
handleSocketMessage(msg);
};
socket.onclose = () => {
console.log("WebSocket disconnected.");
updateBadgeStatus('disconnected');
writeLog("❌ Mất kết nối đến Backend server. Đang thử kết nối lại...", "error");
reconnectTimeout = setTimeout(connectWebSocket, 3000);
};
socket.onerror = (err) => {
console.error("WebSocket Error: ", err);
};
}
function handleSocketMessage(msg) {
switch(msg.type) {
case 'init':
createTable(msg.table);
createTray(msg.tray);
createSlotHelpers(msg.slots);
loadYcbObjects(msg.objects);
initRobotStructure();
break;
case 'state':
updateSimulationState(msg.joints, msg.objects);
break;
case 'log':
writeLog(msg.message, getLogClass(msg.message));
updatePipelineUI(msg.message);
break;
case 'plan':
displayPlan(msg.plan);
break;
case 'result':
showRearrangementScore(msg.score_display);
unlockInput();
break;
}
}
// ─── UI Updates and Interactions ────────────────────────────────────────────
const badge = document.getElementById('connection-badge');
const logConsole = document.getElementById('log-console');
const planList = document.getElementById('plan-list');
const chatInput = document.getElementById('chat-input');
const submitBtn = document.getElementById('submit-btn');
const mockToggle = document.getElementById('mock-toggle');
const guiToggle = document.getElementById('gui-toggle');
const resetBtn = document.getElementById('reset-btn');
const scoreModal = document.getElementById('score-modal');
const scoreContent = document.getElementById('score-md-content');
const closeModalBtn = document.getElementById('close-modal-btn');
function updateBadgeStatus(status) {
if (status === 'connected') {
badge.className = 'badge online';
badge.textContent = 'Connected';
} else {
badge.className = 'badge offline';
badge.textContent = 'Disconnected';
}
}
function writeLog(text, className = 'info') {
const entry = document.createElement('div');
entry.className = `log-entry ${className}`;
entry.textContent = `> ${text}`;
// Remove placeholder
const placeholder = logConsole.querySelector('.placeholder-text');
if (placeholder) placeholder.remove();
logConsole.appendChild(entry);
logConsole.scrollTop = logConsole.scrollHeight;
}
function getLogClass(message) {
if (message.includes('✅')) return 'success';
if (message.includes('❌')) return 'error';
if (message.includes('⚠️')) return 'warn';
if (message.includes('🚀') || message.includes('⏳')) return 'info';
return '';
}
function updatePipelineUI(message) {
const stepLlm = document.getElementById('step-llm');
const stepVal = document.getElementById('step-val');
const stepExec = document.getElementById('step-exec');
const stepScore = document.getElementById('step-score');
if (message.includes('[1/5]')) {
setActiveStep(stepLlm);
} else if (message.includes('✅ [1]')) {
setCompletedStep(stepLlm);
} else if (message.includes('❌ [1]')) {
setErrorStep(stepLlm);
unlockInput();
}
else if (message.includes('[2/5]')) {
setActiveStep(stepVal);
} else if (message.includes('✅ [2]')) {
setCompletedStep(stepVal);
} else if (message.includes('❌ [2]') || message.includes('⚠️ [2]')) {
if (message.includes('❌')) {
setErrorStep(stepVal);
unlockInput();
} else {
stepVal.className = 'status-step active warn';
}
}
else if (message.includes('[3/5]')) {
setActiveStep(stepExec);
} else if (message.includes('Thực thi thành công')) {
setCompletedStep(stepExec);
} else if (message.includes('Thực thi kết thúc có bước lỗi')) {
setErrorStep(stepExec);
}
else if (message.includes('[5/5]')) {
setActiveStep(stepScore);
} else if (message.includes('Rearrangement Evaluation Report') || message.includes('result')) {
setCompletedStep(stepScore);
unlockInput();
}
}
function setActiveStep(el) {
el.className = 'status-step active';
}
function setCompletedStep(el) {
el.className = 'status-step completed';
}
function setErrorStep(el) {
el.className = 'status-step error';
}
function displayPlan(plan) {
planList.innerHTML = '';
plan.forEach(step => {
const item = document.createElement('div');
item.className = 'plan-item';
item.id = `plan-step-${step.step}`;
const argsStr = Object.entries(step.args)
.map(([k, v]) => `${k}:${v}`)
.join(', ');
item.innerHTML = `
<span><b>Step ${step.step}:</b> ${step.skill}(${step.object})</span>
<span style="font-size: 0.75rem; opacity: 0.8;">${argsStr}</span>
`;
planList.appendChild(item);
});
}
function showRearrangementScore(markdownText) {
let html = markdownText
.replace(/### (.*)/g, '<h3>$1</h3>')
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/- (.*)/g, '<li>$1</li>')
.replace(/\n\n/g, '<br>')
.replace(/✅/g, '<span style="color:#10b981">✅</span>')
.replace(/⚠️/g, '<span style="color:#f59e0b">⚠️</span>')
.replace(/❌/g, '<span style="color:#ef4444">❌</span>');
scoreContent.innerHTML = html;
scoreModal.classList.remove('hidden');
}
function lockInput() {
chatInput.disabled = true;
submitBtn.disabled = true;
resetBtn.disabled = true;
mockToggle.disabled = true;
if (guiToggle) guiToggle.disabled = true;
}
function unlockInput() {
chatInput.disabled = false;
submitBtn.disabled = false;
resetBtn.disabled = false;
mockToggle.disabled = false;
if (guiToggle) guiToggle.disabled = false;
}
// ─── Event Listeners ───────────────────────────────────────────────────────
document.getElementById('chat-form').addEventListener('submit', (e) => {
e.preventDefault();
const prompt = chatInput.value.trim();
if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return;
currentPrompt = prompt;
chatInput.value = '';
logConsole.innerHTML = '';
planList.innerHTML = '<p class="placeholder-text">Đang tải kế hoạch...</p>';
['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => {
document.getElementById(id).className = 'status-step';
});
writeLog(`Gửi yêu cầu: "${prompt}"`, "info");
lockInput();
socket.send(JSON.stringify({
type: 'run',
prompt: prompt,
mock: mockToggle.checked
}));
});
// Preset buttons
document.querySelectorAll('.preset-badge').forEach(badge => {
badge.addEventListener('click', () => {
chatInput.value = badge.dataset.prompt;
chatInput.focus();
});
});
// Reset Button
resetBtn.addEventListener('click', () => {
if (!socket || socket.readyState !== WebSocket.OPEN) return;
logConsole.innerHTML = '';
planList.innerHTML = '<p class="placeholder-text">Chưa có kế hoạch...</p>';
['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => {
document.getElementById(id).className = 'status-step';
});
socket.send(JSON.stringify({
type: 'reset'
}));
});
// Close score modal
closeModalBtn.addEventListener('click', () => {
scoreModal.classList.add('hidden');
unlockInput();
});
// GUI Toggle checkbox event listener
if (guiToggle) {
guiToggle.addEventListener('change', () => {
writeLog("Thay đổi thiết lập hiển thị cửa sổ PyBullet. Đang kết nối lại...", "info");
if (socket) {
socket.onclose = null; // Prevent the automatic reconnect handler from running
socket.close();
}
connectWebSocket();
});
}
// Start visualizer and connect
initVisualizer();
connectWebSocket();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511import sys
import os
import json
import asyncio
import math
import time
import threading
from typing import Optional
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import uvicorn
import cv2
import numpy as np
import pybullet as pb
# Ensure project source root is in path
PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if PROJECT_SRC not in sys.path:
sys.path.insert(0, PROJECT_SRC)
from dotenv import load_dotenv
load_dotenv()
from main import PandaSimulation, _YCB_CATALOG
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
from llm_panda.plan_verifier import PlanVerifier
from llm_panda import config
import pybullet_data
from pybullet_object_models import ycb_objects
app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
# Serve static files from the frontend directory itself
static_dir = os.path.dirname(__file__)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
# Mount robot meshes and YCB object assets
panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda")
ycb_data_path = ycb_objects.getDataPath()
app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda")
app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb")
@app.get("/")
async def get():
html_file = os.path.join(static_dir, "index.html")
if os.path.exists(html_file):
with open(html_file, "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read(), status_code=200)
return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
# Global variables to track the current active simulation, lock, and thread lock
current_sim: Optional[PandaSimulation] = None
executor_lock = asyncio.Lock()
pybullet_lock = threading.RLock()
def get_init_payload(sim: PandaSimulation) -> dict:
"""Gathers the initial static geometry and YCB object definitions."""
with pybullet_lock:
objects_info = {}
if sim and sim.scene:
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
cls = sim.scene.get_class(oid)
folder = ""
for cat_name, cat_cls, cat_folder in _YCB_CATALOG:
if cat_name == name:
folder = cat_folder
break
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
# Query visual shape data for exact dimensions/scales and offsets
visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client)
vis_scale = [1.0, 1.0, 1.0]
vis_local_pos = [0.0, 0.0, 0.0]
vis_local_ori = [0.0, 0.0, 0.0, 1.0]
if visual_data:
vd = visual_data[0]
vis_scale = list(vd[3])
vis_local_pos = list(vd[5])
vis_local_ori = list(vd[6])
# Query collision shape data for offsets and scale
# Query collision shape data for CoM-to-link offset
collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client)
coll_scale = [1.0, 1.0, 1.0]
coll_local_pos = [0.0, 0.0, 0.0]
coll_local_ori = [0.0, 0.0, 0.0, 1.0]
if collision_data:
cd = collision_data[0]
coll_scale = list(cd[3])
coll_local_pos = list(cd[5])
coll_local_ori = list(cd[6])
# Query visual shape data for exact dimensions/scales and offsets relative to link
visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client)
vis_scale = [1.0, 1.0, 1.0]
vis_local_pos = [0.0, 0.0, 0.0]
vis_local_ori = [0.0, 0.0, 0.0, 1.0]
if visual_data:
vd = visual_data[0]
vis_scale = list(vd[3])
# Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual
vis_pos_com, vis_ori_com = pb.multiplyTransforms(
coll_local_pos, coll_local_ori,
list(vd[5]), list(vd[6])
)
vis_local_pos = list(vis_pos_com)
vis_local_ori = list(vis_ori_com)
objects_info[name] = {
"class": cls,
"folder": folder,
"initial_pos": list(pos),
"initial_ori": list(ori),
"vis_scale": vis_scale,
"vis_local_pos": vis_local_pos,
"vis_local_ori": vis_local_ori,
"coll_scale": coll_scale,
"coll_local_pos": coll_local_pos,
"coll_local_ori": coll_local_ori
}
return {
"type": "init",
"table": {
"center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z],
"half_extents": list(config.TABLE_HALF_EXTENTS),
"color": list(config.TABLE_COLOR),
"top_z": config.TABLE_TOP_Z
},
"tray": {
"position": list(config.TRAY_POSITION),
"half_extents": list(config.TRAY_HALF_EXTENTS),
"color": list(config.TRAY_COLOR)
},
"slots": {name: list(pos) for name, pos in config.SLOTS.items()},
"objects": objects_info
}
def get_simulation_state_payload(sim: PandaSimulation) -> dict:
"""Gathers the current robot joint positions and YCB object poses."""
with pybullet_lock:
if sim is None or sim.client is None or not pb.isConnected(sim.client):
return {}
# Read all joints (12 joints including arm joints and gripper fingers)
num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client)
joints_state = []
for i in range(num_joints):
pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client)
joints_state.append(pos)
# Read objects pos/ori
objects_state = {}
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
objects_state[name] = {
"pos": list(pos),
"ori": list(ori)
}
return {
"type": "state",
"joints": joints_state,
"objects": objects_state
}
def set_pybullet_window_visibility(visible: bool):
"""Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen."""
import sys
if sys.platform != "win32":
return False
import ctypes
import time
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
for _ in range(30):
found_hwnd = []
def foreach_window(hwnd, lParam):
length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
title = buff.value
if "bullet physics examplebrowser" in title.lower():
found_hwnd.append(hwnd)
return False
return True
ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0)
if found_hwnd:
hwnd = found_hwnd[0]
# Ensure the window is shown/restored from minimized state first (SW_SHOW = 5)
ctypes.windll.user32.ShowWindow(hwnd, 5)
# SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004
if visible:
# Move window to visible region
ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004)
else:
# Move window far off-screen to hide it without destroying OpenGL context
ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004)
print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True)
return True
time.sleep(0.1)
return False
def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool):
"""Calculates rearrangement score based on final object locations and collisions."""
with pybullet_lock:
score = 100
details = []
# Check target placement if we had a plan
target_location = None
target_object = None
for step in plan:
if step.get("function") in ("place_at", "place_down", "move_to"):
args = step.get("args", {})
if "location_id" in args:
target_location = args["location_id"]
if step.get("function") == "pick_up":
target_object = step.get("args", {}).get("object_id")
if target_object and target_location:
obj_id = sim.scene.name_to_id(target_object)
if obj_id is not None:
pos, _ = pb.getBasePositionAndOrientation(obj_id)
current_loc = sim.scene.classify_location(pos)
if current_loc == target_location:
details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm")
else:
details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm")
score -= 50
else:
details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm")
score -= 50
else:
details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.")
# Knock detection
knocked_count = 0
for oid in sim.scene.object_ids:
if oid == sim.scene.name_to_id(target_object):
continue
pos, _ = pb.getBasePositionAndOrientation(oid)
loc = sim.scene.classify_location(pos)
if loc == "elsewhere":
name = sim.scene.get_name(oid)
details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm")
score -= 15
knocked_count += 1
if knocked_count == 0:
details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm")
else:
score = max(0, score)
# Execution success
if executed_successfully:
details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm")
else:
details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm")
score -= 30
score = max(0, min(100, score))
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
return score, md
def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None):
"""Runs the planning, validation, execution with image streaming, and scoring."""
global current_sim
def log(message: str, step: Optional[int] = None):
try:
print(f"[WS Log] {message}", flush=True)
except Exception:
pass
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "log", "message": message, "step": step}),
loop
)
# Step 1: Planning
log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...")
if use_mock:
planner = RuleBasedPlanner()
log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)")
else:
api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY")
if not api_key:
log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.")
return
planner = RemoteLLMPlanner()
log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})")
with pybullet_lock:
current_sim.agent = LLMAgent(planner=planner)
# Define reachability check for scene state
def reachability_fn(oid):
cls = current_sim.scene.get_class(oid)
try:
grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls)
return current_sim.controller.is_reachable(grasp_pos, grasp_ori)
except Exception:
return False
carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None
scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name)
state_text = json.dumps(scene_state, indent=2)
try:
with pybullet_lock:
plan = current_sim.agent.plan(user_prompt, state_text)
log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.")
except Exception as e:
log(f"❌ [1] Lập kế hoạch thất bại: {e}")
return
# Send steps to client
plan_steps = []
for idx, step in enumerate(plan, 1):
func = step.get("function")
args = step.get("args", {})
obj = args.get("object_id") or args.get("location_id") or ""
plan_steps.append({
"step": idx,
"skill": func,
"object": obj,
"args": args
})
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "plan", "plan": plan_steps}),
loop
)
if not plan:
log("⚠️ [1] Kế hoạch rỗng.")
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, [], True)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
return
# Step 2: Validation
log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...")
try:
with pybullet_lock:
warnings = PlanVerifier.check(plan, scene_state)
if not warnings:
log("✅ [2] Kế hoạch hợp lệ.")
else:
log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.")
for w in warnings:
log(f" - {w}")
except Exception as e:
log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}")
return
# Step 3: PyBullet Execution (Live!)
log("⏳ [3/5] Đang thực thi hành động của robot...")
# Hook pb.stepSimulation to capture states during movements
original_step = pb.stepSimulation
last_stream_time = [0.0]
throttle_interval = 0.033 if current_sim.gui else 0.066
def wrapped_step():
original_step()
if not current_sim.gui:
# Sleep slightly in headless mode to simulate arm speed and avoid freezing
time.sleep(0.001)
curr_time = time.time()
if curr_time - last_stream_time[0] >= throttle_interval:
last_stream_time[0] = curr_time
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(
websocket.send_json(state_payload),
loop
)
with pybullet_lock:
pb.stepSimulation = wrapped_step
executed_successfully = True
try:
# Trigger an initial simulation state transmission
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
for i, step in enumerate(plan, 1):
log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}")
with pybullet_lock:
current_sim._execute(step, verbose=True)
log("✅ [3] Thực thi thành công toàn bộ kế hoạch.")
except Exception as e:
log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
executed_successfully = False
finally:
with pybullet_lock:
pb.stepSimulation = original_step
# Send a final state to ensure visual sync
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
# Step 5: Scoring
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
global current_sim
await websocket.accept()
loop = asyncio.get_running_loop()
# Retrieve user's desktop display preference from client query params
client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
# Force gui = False to run PyBullet completely headless (DIRECT mode)
gui = False
camera_state = {
"target": [0.5, 0.0, 0.3],
"dist": 1.3,
"yaw": 45.0,
"pitch": -35.0
}
async with executor_lock:
def init_sim():
global current_sim
with pybullet_lock:
is_connected = False
if current_sim is not None and current_sim.client is not None:
try:
is_connected = pb.isConnected(current_sim.client)
except Exception:
is_connected = False
if is_connected and current_sim.gui == gui:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
for _ in range(5):
pb.stepSimulation(physicsClientId=current_sim.client)
else:
if is_connected:
try:
current_sim.disconnect()
except Exception as e:
print(f"[Teardown Error] {e}")
current_sim = PandaSimulation(gui=gui, seed=0)
await asyncio.to_thread(init_sim)
# Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
# Send static scene configuration
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
await websocket.send_json(init_payload)
# Send the first simulation state to sync objects and joints
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
try:
while True:
data = await websocket.receive_text()
payload = json.loads(data)
p_type = payload.get("type")
if p_type == "run":
prompt = payload.get("prompt", "")
use_mock = payload.get("mock", False)
asyncio.create_task(
asyncio.to_thread(
run_pipeline_threadsafe,
websocket,
prompt,
loop,
use_mock
)
)
elif p_type == "reset":
async with executor_lock:
def reset_sim():
with pybullet_lock:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
await asyncio.to_thread(reset_sim)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
pass
except WebSocketDisconnect:
print("Client disconnected")
except Exception as e:
print(f"WS Exception: {e}")
if __name__ == "__main__":
uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511import sys
import os
import json
import asyncio
import math
import time
import threading
from typing import Optional
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import uvicorn
import cv2
import numpy as np
import pybullet as pb
# Ensure project source root is in path
PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if PROJECT_SRC not in sys.path:
sys.path.insert(0, PROJECT_SRC)
from dotenv import load_dotenv
load_dotenv()
from main import PandaSimulation, _YCB_CATALOG
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
from llm_panda.plan_verifier import PlanVerifier
from llm_panda import config
import pybullet_data
from pybullet_object_models import ycb_objects
app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
# Serve static files from the frontend directory itself
static_dir = os.path.dirname(__file__)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
# Mount robot meshes and YCB object assets
panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda")
ycb_data_path = ycb_objects.getDataPath()
app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda")
app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb")
@app.get("/")
async def get():
html_file = os.path.join(static_dir, "index.html")
if os.path.exists(html_file):
with open(html_file, "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read(), status_code=200)
return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
# Global variables to track the current active simulation, lock, and thread lock
current_sim: Optional[PandaSimulation] = None
executor_lock = asyncio.Lock()
pybullet_lock = threading.RLock()
def get_init_payload(sim: PandaSimulation) -> dict:
"""Gathers the initial static geometry and YCB object definitions."""
with pybullet_lock:
objects_info = {}
if sim and sim.scene:
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
cls = sim.scene.get_class(oid)
folder = ""
for cat_name, cat_cls, cat_folder in _YCB_CATALOG:
if cat_name == name:
folder = cat_folder
break
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
# Query visual shape data for exact dimensions/scales and offsets
visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client)
vis_scale = [1.0, 1.0, 1.0]
vis_local_pos = [0.0, 0.0, 0.0]
vis_local_ori = [0.0, 0.0, 0.0, 1.0]
if visual_data:
vd = visual_data[0]
vis_scale = list(vd[3])
vis_local_pos = list(vd[5])
vis_local_ori = list(vd[6])
# Query collision shape data for offsets and scale
# Query collision shape data for CoM-to-link offset
collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client)
coll_scale = [1.0, 1.0, 1.0]
coll_local_pos = [0.0, 0.0, 0.0]
coll_local_ori = [0.0, 0.0, 0.0, 1.0]
if collision_data:
cd = collision_data[0]
coll_scale = list(cd[3])
coll_local_pos = list(cd[5])
coll_local_ori = list(cd[6])
# Query visual shape data for exact dimensions/scales and offsets relative to link
visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client)
vis_scale = [1.0, 1.0, 1.0]
vis_local_pos = [0.0, 0.0, 0.0]
vis_local_ori = [0.0, 0.0, 0.0, 1.0]
if visual_data:
vd = visual_data[0]
vis_scale = list(vd[3])
# Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual
vis_pos_com, vis_ori_com = pb.multiplyTransforms(
coll_local_pos, coll_local_ori,
list(vd[5]), list(vd[6])
)
vis_local_pos = list(vis_pos_com)
vis_local_ori = list(vis_ori_com)
objects_info[name] = {
"class": cls,
"folder": folder,
"initial_pos": list(pos),
"initial_ori": list(ori),
"vis_scale": vis_scale,
"vis_local_pos": vis_local_pos,
"vis_local_ori": vis_local_ori,
"coll_scale": coll_scale,
"coll_local_pos": coll_local_pos,
"coll_local_ori": coll_local_ori
}
return {
"type": "init",
"table": {
"center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z],
"half_extents": list(config.TABLE_HALF_EXTENTS),
"color": list(config.TABLE_COLOR),
"top_z": config.TABLE_TOP_Z
},
"tray": {
"position": list(config.TRAY_POSITION),
"half_extents": list(config.TRAY_HALF_EXTENTS),
"color": list(config.TRAY_COLOR)
},
"slots": {name: list(pos) for name, pos in config.SLOTS.items()},
"objects": objects_info
}
def get_simulation_state_payload(sim: PandaSimulation) -> dict:
"""Gathers the current robot joint positions and YCB object poses."""
with pybullet_lock:
if sim is None or sim.client is None or not pb.isConnected(sim.client):
return {}
# Read all joints (12 joints including arm joints and gripper fingers)
num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client)
joints_state = []
for i in range(num_joints):
pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client)
joints_state.append(pos)
# Read objects pos/ori
objects_state = {}
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
objects_state[name] = {
"pos": list(pos),
"ori": list(ori)
}
return {
"type": "state",
"joints": joints_state,
"objects": objects_state
}
def set_pybullet_window_visibility(visible: bool):
"""Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen."""
import sys
if sys.platform != "win32":
return False
import ctypes
import time
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
for _ in range(30):
found_hwnd = []
def foreach_window(hwnd, lParam):
length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
title = buff.value
if "bullet physics examplebrowser" in title.lower():
found_hwnd.append(hwnd)
return False
return True
ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0)
if found_hwnd:
hwnd = found_hwnd[0]
# Ensure the window is shown/restored from minimized state first (SW_SHOW = 5)
ctypes.windll.user32.ShowWindow(hwnd, 5)
# SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004
if visible:
# Move window to visible region
ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004)
else:
# Move window far off-screen to hide it without destroying OpenGL context
ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004)
print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True)
return True
time.sleep(0.1)
return False
def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool):
"""Calculates rearrangement score based on final object locations and collisions."""
with pybullet_lock:
score = 100
details = []
# Check target placement if we had a plan
target_location = None
target_object = None
for step in plan:
if step.get("function") in ("place_at", "place_down", "move_to"):
args = step.get("args", {})
if "location_id" in args:
target_location = args["location_id"]
if step.get("function") == "pick_up":
target_object = step.get("args", {}).get("object_id")
if target_object and target_location:
obj_id = sim.scene.name_to_id(target_object)
if obj_id is not None:
pos, _ = pb.getBasePositionAndOrientation(obj_id)
current_loc = sim.scene.classify_location(pos)
if current_loc == target_location:
details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm")
else:
details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm")
score -= 50
else:
details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm")
score -= 50
else:
details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.")
# Knock detection
knocked_count = 0
for oid in sim.scene.object_ids:
if oid == sim.scene.name_to_id(target_object):
continue
pos, _ = pb.getBasePositionAndOrientation(oid)
loc = sim.scene.classify_location(pos)
if loc == "elsewhere":
name = sim.scene.get_name(oid)
details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm")
score -= 15
knocked_count += 1
if knocked_count == 0:
details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm")
else:
score = max(0, score)
# Execution success
if executed_successfully:
details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm")
else:
details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm")
score -= 30
score = max(0, min(100, score))
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
return score, md
def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None):
"""Runs the planning, validation, execution with image streaming, and scoring."""
global current_sim
def log(message: str, step: Optional[int] = None):
try:
print(f"[WS Log] {message}", flush=True)
except Exception:
pass
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "log", "message": message, "step": step}),
loop
)
# Step 1: Planning
log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...")
if use_mock:
planner = RuleBasedPlanner()
log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)")
else:
api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY")
if not api_key:
log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.")
return
planner = RemoteLLMPlanner()
log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})")
with pybullet_lock:
current_sim.agent = LLMAgent(planner=planner)
# Define reachability check for scene state
def reachability_fn(oid):
cls = current_sim.scene.get_class(oid)
try:
grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls)
return current_sim.controller.is_reachable(grasp_pos, grasp_ori)
except Exception:
return False
carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None
scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name)
state_text = json.dumps(scene_state, indent=2)
try:
with pybullet_lock:
plan = current_sim.agent.plan(user_prompt, state_text)
log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.")
except Exception as e:
log(f"❌ [1] Lập kế hoạch thất bại: {e}")
return
# Send steps to client
plan_steps = []
for idx, step in enumerate(plan, 1):
func = step.get("function")
args = step.get("args", {})
obj = args.get("object_id") or args.get("location_id") or ""
plan_steps.append({
"step": idx,
"skill": func,
"object": obj,
"args": args
})
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "plan", "plan": plan_steps}),
loop
)
if not plan:
log("⚠️ [1] Kế hoạch rỗng.")
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, [], True)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
return
# Step 2: Validation
log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...")
try:
with pybullet_lock:
warnings = PlanVerifier.check(plan, scene_state)
if not warnings:
log("✅ [2] Kế hoạch hợp lệ.")
else:
log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.")
for w in warnings:
log(f" - {w}")
except Exception as e:
log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}")
return
# Step 3: PyBullet Execution (Live!)
log("⏳ [3/5] Đang thực thi hành động của robot...")
# Hook pb.stepSimulation to capture states during movements
original_step = pb.stepSimulation
last_stream_time = [0.0]
throttle_interval = 0.033 if current_sim.gui else 0.066
def wrapped_step():
original_step()
if not current_sim.gui:
# Sleep slightly in headless mode to simulate arm speed and avoid freezing
time.sleep(0.001)
curr_time = time.time()
if curr_time - last_stream_time[0] >= throttle_interval:
last_stream_time[0] = curr_time
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(
websocket.send_json(state_payload),
loop
)
with pybullet_lock:
pb.stepSimulation = wrapped_step
executed_successfully = True
try:
# Trigger an initial simulation state transmission
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
for i, step in enumerate(plan, 1):
log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}")
with pybullet_lock:
current_sim._execute(step, verbose=True)
log("✅ [3] Thực thi thành công toàn bộ kế hoạch.")
except Exception as e:
log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
executed_successfully = False
finally:
with pybullet_lock:
pb.stepSimulation = original_step
# Send a final state to ensure visual sync
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
# Step 5: Scoring
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
global current_sim
await websocket.accept()
loop = asyncio.get_running_loop()
# Retrieve user's desktop display preference from client query params
client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
# Force gui = False to run PyBullet completely headless (DIRECT mode)
gui = False
camera_state = {
"target": [0.5, 0.0, 0.3],
"dist": 1.3,
"yaw": 45.0,
"pitch": -35.0
}
async with executor_lock:
def init_sim():
global current_sim
with pybullet_lock:
is_connected = False
if current_sim is not None and current_sim.client is not None:
try:
is_connected = pb.isConnected(current_sim.client)
except Exception:
is_connected = False
if is_connected and current_sim.gui == gui:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
for _ in range(5):
pb.stepSimulation(physicsClientId=current_sim.client)
else:
if is_connected:
try:
current_sim.disconnect()
except Exception as e:
print(f"[Teardown Error] {e}")
current_sim = PandaSimulation(gui=gui, seed=0)
await asyncio.to_thread(init_sim)
# Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
# Send static scene configuration
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
await websocket.send_json(init_payload)
# Send the first simulation state to sync objects and joints
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
try:
while True:
data = await websocket.receive_text()
payload = json.loads(data)
p_type = payload.get("type")
if p_type == "run":
prompt = payload.get("prompt", "")
use_mock = payload.get("mock", False)
asyncio.create_task(
asyncio.to_thread(
run_pipeline_threadsafe,
websocket,
prompt,
loop,
use_mock
)
)
elif p_type == "reset":
async with executor_lock:
def reset_sim():
with pybullet_lock:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
await asyncio.to_thread(reset_sim)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
pass
except WebSocketDisconnect:
print("Client disconnected")
except Exception as e:
print(f"WS Exception: {e}")
if __name__ == "__main__":
uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511import sys
import os
import json
import asyncio
import math
import time
import threading
from typing import Optional
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import uvicorn
import cv2
import numpy as np
import pybullet as pb
# Ensure project source root is in path
PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if PROJECT_SRC not in sys.path:
sys.path.insert(0, PROJECT_SRC)
from dotenv import load_dotenv
load_dotenv()
from main import PandaSimulation, _YCB_CATALOG
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
from llm_panda.plan_verifier import PlanVerifier
from llm_panda import config
import pybullet_data
from pybullet_object_models import ycb_objects
app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
# Serve static files from the frontend directory itself
static_dir = os.path.dirname(__file__)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
# Mount robot meshes and YCB object assets
panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda")
ycb_data_path = ycb_objects.getDataPath()
app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda")
app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb")
@app.get("/")
async def get():
html_file = os.path.join(static_dir, "index.html")
if os.path.exists(html_file):
with open(html_file, "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read(), status_code=200)
return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
# Global variables to track the current active simulation, lock, and thread lock
current_sim: Optional[PandaSimulation] = None
executor_lock = asyncio.Lock()
pybullet_lock = threading.RLock()
def get_init_payload(sim: PandaSimulation) -> dict:
"""Gathers the initial static geometry and YCB object definitions."""
with pybullet_lock:
objects_info = {}
if sim and sim.scene:
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
cls = sim.scene.get_class(oid)
folder = ""
for cat_name, cat_cls, cat_folder in _YCB_CATALOG:
if cat_name == name:
folder = cat_folder
break
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
# Query visual shape data for exact dimensions/scales and offsets
visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client)
vis_scale = [1.0, 1.0, 1.0]
vis_local_pos = [0.0, 0.0, 0.0]
vis_local_ori = [0.0, 0.0, 0.0, 1.0]
if visual_data:
vd = visual_data[0]
vis_scale = list(vd[3])
vis_local_pos = list(vd[5])
vis_local_ori = list(vd[6])
# Query collision shape data for offsets and scale
# Query collision shape data for CoM-to-link offset
collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client)
coll_scale = [1.0, 1.0, 1.0]
coll_local_pos = [0.0, 0.0, 0.0]
coll_local_ori = [0.0, 0.0, 0.0, 1.0]
if collision_data:
cd = collision_data[0]
coll_scale = list(cd[3])
coll_local_pos = list(cd[5])
coll_local_ori = list(cd[6])
# Query visual shape data for exact dimensions/scales and offsets relative to link
visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client)
vis_scale = [1.0, 1.0, 1.0]
vis_local_pos = [0.0, 0.0, 0.0]
vis_local_ori = [0.0, 0.0, 0.0, 1.0]
if visual_data:
vd = visual_data[0]
vis_scale = list(vd[3])
# Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual
vis_pos_com, vis_ori_com = pb.multiplyTransforms(
coll_local_pos, coll_local_ori,
list(vd[5]), list(vd[6])
)
vis_local_pos = list(vis_pos_com)
vis_local_ori = list(vis_ori_com)
objects_info[name] = {
"class": cls,
"folder": folder,
"initial_pos": list(pos),
"initial_ori": list(ori),
"vis_scale": vis_scale,
"vis_local_pos": vis_local_pos,
"vis_local_ori": vis_local_ori,
"coll_scale": coll_scale,
"coll_local_pos": coll_local_pos,
"coll_local_ori": coll_local_ori
}
return {
"type": "init",
"table": {
"center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z],
"half_extents": list(config.TABLE_HALF_EXTENTS),
"color": list(config.TABLE_COLOR),
"top_z": config.TABLE_TOP_Z
},
"tray": {
"position": list(config.TRAY_POSITION),
"half_extents": list(config.TRAY_HALF_EXTENTS),
"color": list(config.TRAY_COLOR)
},
"slots": {name: list(pos) for name, pos in config.SLOTS.items()},
"objects": objects_info
}
def get_simulation_state_payload(sim: PandaSimulation) -> dict:
"""Gathers the current robot joint positions and YCB object poses."""
with pybullet_lock:
if sim is None or sim.client is None or not pb.isConnected(sim.client):
return {}
# Read all joints (12 joints including arm joints and gripper fingers)
num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client)
joints_state = []
for i in range(num_joints):
pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client)
joints_state.append(pos)
# Read objects pos/ori
objects_state = {}
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
objects_state[name] = {
"pos": list(pos),
"ori": list(ori)
}
return {
"type": "state",
"joints": joints_state,
"objects": objects_state
}
def set_pybullet_window_visibility(visible: bool):
"""Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen."""
import sys
if sys.platform != "win32":
return False
import ctypes
import time
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
for _ in range(30):
found_hwnd = []
def foreach_window(hwnd, lParam):
length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
title = buff.value
if "bullet physics examplebrowser" in title.lower():
found_hwnd.append(hwnd)
return False
return True
ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0)
if found_hwnd:
hwnd = found_hwnd[0]
# Ensure the window is shown/restored from minimized state first (SW_SHOW = 5)
ctypes.windll.user32.ShowWindow(hwnd, 5)
# SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004
if visible:
# Move window to visible region
ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004)
else:
# Move window far off-screen to hide it without destroying OpenGL context
ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004)
print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True)
return True
time.sleep(0.1)
return False
def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool):
"""Calculates rearrangement score based on final object locations and collisions."""
with pybullet_lock:
score = 100
details = []
# Check target placement if we had a plan
target_location = None
target_object = None
for step in plan:
if step.get("function") in ("place_at", "place_down", "move_to"):
args = step.get("args", {})
if "location_id" in args:
target_location = args["location_id"]
if step.get("function") == "pick_up":
target_object = step.get("args", {}).get("object_id")
if target_object and target_location:
obj_id = sim.scene.name_to_id(target_object)
if obj_id is not None:
pos, _ = pb.getBasePositionAndOrientation(obj_id)
current_loc = sim.scene.classify_location(pos)
if current_loc == target_location:
details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm")
else:
details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm")
score -= 50
else:
details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm")
score -= 50
else:
details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.")
# Knock detection
knocked_count = 0
for oid in sim.scene.object_ids:
if oid == sim.scene.name_to_id(target_object):
continue
pos, _ = pb.getBasePositionAndOrientation(oid)
loc = sim.scene.classify_location(pos)
if loc == "elsewhere":
name = sim.scene.get_name(oid)
details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm")
score -= 15
knocked_count += 1
if knocked_count == 0:
details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm")
else:
score = max(0, score)
# Execution success
if executed_successfully:
details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm")
else:
details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm")
score -= 30
score = max(0, min(100, score))
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
return score, md
def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None):
"""Runs the planning, validation, execution with image streaming, and scoring."""
global current_sim
def log(message: str, step: Optional[int] = None):
try:
print(f"[WS Log] {message}", flush=True)
except Exception:
pass
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "log", "message": message, "step": step}),
loop
)
# Step 1: Planning
log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...")
if use_mock:
planner = RuleBasedPlanner()
log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)")
else:
api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY")
if not api_key:
log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.")
return
planner = RemoteLLMPlanner()
log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})")
with pybullet_lock:
current_sim.agent = LLMAgent(planner=planner)
# Define reachability check for scene state
def reachability_fn(oid):
cls = current_sim.scene.get_class(oid)
try:
grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls)
return current_sim.controller.is_reachable(grasp_pos, grasp_ori)
except Exception:
return False
carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None
scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name)
state_text = json.dumps(scene_state, indent=2)
try:
with pybullet_lock:
plan = current_sim.agent.plan(user_prompt, state_text)
log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.")
except Exception as e:
log(f"❌ [1] Lập kế hoạch thất bại: {e}")
return
# Send steps to client
plan_steps = []
for idx, step in enumerate(plan, 1):
func = step.get("function")
args = step.get("args", {})
obj = args.get("object_id") or args.get("location_id") or ""
plan_steps.append({
"step": idx,
"skill": func,
"object": obj,
"args": args
})
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "plan", "plan": plan_steps}),
loop
)
if not plan:
log("⚠️ [1] Kế hoạch rỗng.")
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, [], True)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
return
# Step 2: Validation
log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...")
try:
with pybullet_lock:
warnings = PlanVerifier.check(plan, scene_state)
if not warnings:
log("✅ [2] Kế hoạch hợp lệ.")
else:
log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.")
for w in warnings:
log(f" - {w}")
except Exception as e:
log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}")
return
# Step 3: PyBullet Execution (Live!)
log("⏳ [3/5] Đang thực thi hành động của robot...")
# Hook pb.stepSimulation to capture states during movements
original_step = pb.stepSimulation
last_stream_time = [0.0]
throttle_interval = 0.033 if current_sim.gui else 0.066
def wrapped_step():
original_step()
if not current_sim.gui:
# Sleep slightly in headless mode to simulate arm speed and avoid freezing
time.sleep(0.001)
curr_time = time.time()
if curr_time - last_stream_time[0] >= throttle_interval:
last_stream_time[0] = curr_time
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(
websocket.send_json(state_payload),
loop
)
with pybullet_lock:
pb.stepSimulation = wrapped_step
executed_successfully = True
try:
# Trigger an initial simulation state transmission
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
for i, step in enumerate(plan, 1):
log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}")
with pybullet_lock:
current_sim._execute(step, verbose=True)
log("✅ [3] Thực thi thành công toàn bộ kế hoạch.")
except Exception as e:
log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
executed_successfully = False
finally:
with pybullet_lock:
pb.stepSimulation = original_step
# Send a final state to ensure visual sync
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
# Step 5: Scoring
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
global current_sim
await websocket.accept()
loop = asyncio.get_running_loop()
# Retrieve user's desktop display preference from client query params
client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
# Force gui = False to run PyBullet completely headless (DIRECT mode)
gui = False
camera_state = {
"target": [0.5, 0.0, 0.3],
"dist": 1.3,
"yaw": 45.0,
"pitch": -35.0
}
async with executor_lock:
def init_sim():
global current_sim
with pybullet_lock:
is_connected = False
if current_sim is not None and current_sim.client is not None:
try:
is_connected = pb.isConnected(current_sim.client)
except Exception:
is_connected = False
if is_connected and current_sim.gui == gui:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
for _ in range(5):
pb.stepSimulation(physicsClientId=current_sim.client)
else:
if is_connected:
try:
current_sim.disconnect()
except Exception as e:
print(f"[Teardown Error] {e}")
current_sim = PandaSimulation(gui=gui, seed=0)
await asyncio.to_thread(init_sim)
# Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
# Send static scene configuration
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
await websocket.send_json(init_payload)
# Send the first simulation state to sync objects and joints
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
try:
while True:
data = await websocket.receive_text()
payload = json.loads(data)
p_type = payload.get("type")
if p_type == "run":
prompt = payload.get("prompt", "")
use_mock = payload.get("mock", False)
asyncio.create_task(
asyncio.to_thread(
run_pipeline_threadsafe,
websocket,
prompt,
loop,
use_mock
)
)
elif p_type == "reset":
async with executor_lock:
def reset_sim():
with pybullet_lock:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
await asyncio.to_thread(reset_sim)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
pass
except WebSocketDisconnect:
print("Client disconnected")
except Exception as e:
print(f"WS Exception: {e}")
if __name__ == "__main__":
uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177// ─── WebSocket and Visualizer Setup ────────────────────────────────────────
const canvas = document.getElementById('pybullet-viewport');
// Three.js Core Variables
let renderer, scene, camera, controls;
let robotGroup, tableMesh, trayMesh;
const slotHelpers = [];
const joints = {};
const ycbMeshes = {};
let transformControls = null;
let eeDummy = null;
const OBJ_LOADER = new THREE.OBJLoader();
const MTL_LOADER = new THREE.MTLLoader();
let socket = null;
let currentPrompt = '';
function initVisualizer() {
// Set default coordinate system to Z-up
THREE.Object3D.DefaultUp.set(0, 0, 1);
// Renderer
renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
const width = canvas.clientWidth || window.innerWidth;
const height = canvas.clientHeight || window.innerHeight;
renderer.setSize(width, height, false);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.shadowMap.enabled = true;
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color('#f1f5f9'); // Light smoke gray background
// Camera
camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100);
// Position camera to look down at the table, matching PyBullet default view
camera.position.set(1.2, -1.2, 1.2);
// Controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.target.set(0.5, 0.0, 0.2);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.maxPolarAngle = Math.PI / 2 - 0.02; // do not go below table plane
controls.update();
// Lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.85);
dirLight.position.set(2, -2, 4);
dirLight.castShadow = true;
dirLight.shadow.mapSize.width = 1024;
dirLight.shadow.mapSize.height = 1024;
dirLight.shadow.camera.near = 0.5;
dirLight.shadow.camera.far = 15;
scene.add(dirLight);
const dirLight2 = new THREE.DirectionalLight(0xaaccff, 0.35);
dirLight2.position.set(-2, 2, 2);
scene.add(dirLight2);
// Floor plane
const planeGeo = new THREE.PlaneGeometry(10, 10);
const planeMat = new THREE.MeshStandardMaterial({ color: 0xe2e8f0, roughness: 0.85 });
const plane = new THREE.Mesh(planeGeo, planeMat);
plane.receiveShadow = true;
scene.add(plane);
// Caro background / Grid Helper
const gridHelper = new THREE.GridHelper(10, 100, 0x94a3b8, 0xcbd5e1);
gridHelper.rotation.x = Math.PI / 2;
gridHelper.position.z = 0.001;
scene.add(gridHelper);
// Axes helper (X: Red, Y: Green, Z: Blue)
const axesHelper = new THREE.AxesHelper(0.5);
axesHelper.position.z = 0.002;
scene.add(axesHelper);
// Initialize Transform Controls
transformControls = new THREE.TransformControls(camera, renderer.domElement);
transformControls.addEventListener('dragging-changed', function (event) {
controls.enabled = !event.value;
if (!event.value && transformControls.object && transformControls.object !== eeDummy) {
const obj = transformControls.object;
if (socket && socket.readyState === WebSocket.OPEN) {
const pos = [obj.position.x, obj.position.y, obj.position.z];
const ori = [obj.quaternion.x, obj.quaternion.y, obj.quaternion.z, obj.quaternion.w];
socket.send(JSON.stringify({
type: "update_object_pose",
name: obj.name,
pos: pos,
ori: ori
}));
writeLog(`Đã đặt vật thể ${obj.name} xuống vị trí mới.`, "success");
}
}
});
transformControls.addEventListener('change', function () {
if (transformControls.object) {
const obj = transformControls.object;
if (obj === eeDummy) {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({
type: "update_robot_ee",
pos: [eeDummy.position.x, eeDummy.position.y, eeDummy.position.z]
}));
}
} else {
obj.position.x = Math.max(0.15, Math.min(0.85, obj.position.x));
obj.position.y = Math.max(-0.65, Math.min(0.65, obj.position.y));
obj.position.z = Math.max(0.02, Math.min(0.85, obj.position.z));
if (targetObjects[obj.name]) {
targetObjects[obj.name].pos.copy(obj.position);
}
}
}
});
scene.add(transformControls);
// Start animation loop
animate();
}
let targetJoints = null;
const targetObjects = {};
let isInitialStateSynced = false;
function animate() {
requestAnimationFrame(animate);
if (controls) controls.update();
// Smooth interpolation (Lerp / Slerp) to eliminate visual stutter
if (targetJoints && targetJoints.length >= 11) {
if (!isInitialStateSynced) {
// First tick or after reset: snap immediately to avoid sliding from rest position
joints.joint1.rotation.z = targetJoints[0];
joints.joint2.rotation.z = targetJoints[1];
joints.joint3.rotation.z = targetJoints[2];
joints.joint4.rotation.z = targetJoints[3];
joints.joint5.rotation.z = targetJoints[4];
joints.joint6.rotation.z = targetJoints[5];
joints.joint7.rotation.z = targetJoints[6];
joints.fingerJoint1.position.y = targetJoints[9];
joints.fingerJoint2.position.y = -targetJoints[10];
Object.entries(targetObjects).forEach(([name, target]) => {
if (transformControls && transformControls.object && transformControls.object.name === name) return;
const group = ycbMeshes[name];
if (group) {
group.position.copy(target.pos);
group.quaternion.copy(target.ori);
}
});
isInitialStateSynced = true;
} else {
// Incremental interpolation towards target poses at client framerate (60+ FPS)
const lerpFactor = 0.15; // Balanced tracking speed vs smoothness
joints.joint1.rotation.z = THREE.MathUtils.lerp(joints.joint1.rotation.z, targetJoints[0], lerpFactor);
joints.joint2.rotation.z = THREE.MathUtils.lerp(joints.joint2.rotation.z, targetJoints[1], lerpFactor);
joints.joint3.rotation.z = THREE.MathUtils.lerp(joints.joint3.rotation.z, targetJoints[2], lerpFactor);
joints.joint4.rotation.z = THREE.MathUtils.lerp(joints.joint4.rotation.z, targetJoints[3], lerpFactor);
joints.joint5.rotation.z = THREE.MathUtils.lerp(joints.joint5.rotation.z, targetJoints[4], lerpFactor);
joints.joint6.rotation.z = THREE.MathUtils.lerp(joints.joint6.rotation.z, targetJoints[5], lerpFactor);
joints.joint7.rotation.z = THREE.MathUtils.lerp(joints.joint7.rotation.z, targetJoints[6], lerpFactor);
joints.fingerJoint1.position.y = THREE.MathUtils.lerp(joints.fingerJoint1.position.y, targetJoints[9], lerpFactor);
joints.fingerJoint2.position.y = THREE.MathUtils.lerp(joints.fingerJoint2.position.y, -targetJoints[10], lerpFactor);
Object.entries(targetObjects).forEach(([name, target]) => {
if (transformControls && transformControls.object && transformControls.object.name === name) return;
const group = ycbMeshes[name];
if (group) {
group.position.lerp(target.pos, lerpFactor);
group.quaternion.slerp(target.ori, lerpFactor);
}
});
}
}
// Update joint sliders to match current animation if user is not actively dragging them
const activeEl = document.activeElement;
const isEditingSliders = activeEl && activeEl.id && activeEl.id.startsWith('slider-');
if (!isEditingSliders && targetJoints) {
const j1 = document.getElementById('slider-j1');
if (j1) j1.value = joints.joint1.rotation.z.toFixed(2);
const v1 = document.getElementById('val-j1');
if (v1) v1.textContent = joints.joint1.rotation.z.toFixed(2);
const j2 = document.getElementById('slider-j2');
if (j2) j2.value = joints.joint2.rotation.z.toFixed(2);
const v2 = document.getElementById('val-j2');
if (v2) v2.textContent = joints.joint2.rotation.z.toFixed(2);
const j3 = document.getElementById('slider-j3');
if (j3) j3.value = joints.joint3.rotation.z.toFixed(2);
const v3 = document.getElementById('val-j3');
if (v3) v3.textContent = joints.joint3.rotation.z.toFixed(2);
const j4 = document.getElementById('slider-j4');
if (j4) j4.value = joints.joint4.rotation.z.toFixed(2);
const v4 = document.getElementById('val-j4');
if (v4) v4.textContent = joints.joint4.rotation.z.toFixed(2);
const j5 = document.getElementById('slider-j5');
if (j5) j5.value = joints.joint5.rotation.z.toFixed(2);
const v5 = document.getElementById('val-j5');
if (v5) v5.textContent = joints.joint5.rotation.z.toFixed(2);
const j6 = document.getElementById('slider-j6');
if (j6) j6.value = joints.joint6.rotation.z.toFixed(2);
const v6 = document.getElementById('val-j6');
if (v6) v6.textContent = joints.joint6.rotation.z.toFixed(2);
const j7 = document.getElementById('slider-j7');
if (j7) j7.value = joints.joint7.rotation.z.toFixed(2);
const v7 = document.getElementById('val-j7');
if (v7) v7.textContent = joints.joint7.rotation.z.toFixed(2);
const jg = document.getElementById('slider-jg');
if (jg) jg.value = joints.fingerJoint1.position.y.toFixed(3);
const vg = document.getElementById('val-jg');
if (vg) vg.textContent = joints.fingerJoint1.position.y.toFixed(3);
}
// Align eeDummy position to handJoint if not being dragged
if (eeDummy && joints.handJoint && (!transformControls || !transformControls.object || transformControls.object !== eeDummy)) {
const handWorldPos = new THREE.Vector3();
joints.handJoint.getWorldPosition(handWorldPos);
eeDummy.position.copy(handWorldPos);
}
renderer.render(scene, camera);
}
// Window resizing
window.addEventListener('resize', () => {
const width = canvas.clientWidth;
const height = canvas.clientHeight;
if (canvas.width !== width || canvas.height !== height) {
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
});
// ─── Three.js Scene Construction ────────────────────────────────────────────
function createTable(tableConfig) {
if (tableMesh) scene.remove(tableMesh);
const ext = tableConfig.half_extents;
const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2);
const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3));
const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 });
tableMesh = new THREE.Mesh(geo, mat);
tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]);
tableMesh.castShadow = true;
tableMesh.receiveShadow = true;
scene.add(tableMesh);
}
function createTray(trayConfig) {
if (trayMesh) scene.remove(trayMesh);
const ext = trayConfig.half_extents;
const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2);
const color = new THREE.Color().fromArray(trayConfig.color.slice(0, 3));
const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.7 });
trayMesh = new THREE.Mesh(geo, mat);
trayMesh.position.set(trayConfig.position[0], trayConfig.position[1], trayConfig.position[2] - ext[2]);
trayMesh.castShadow = true;
trayMesh.receiveShadow = true;
scene.add(trayMesh);
}
function createSlotHelpers(slots) {
slotHelpers.forEach(mesh => scene.remove(mesh));
slotHelpers.length = 0;
const geom = new THREE.RingGeometry(0.045, 0.05, 32);
const mat = new THREE.MeshBasicMaterial({ color: 0x3b82f6, side: THREE.DoubleSide, transparent: true, opacity: 0.45 });
Object.entries(slots).forEach(([name, pos]) => {
const ring = new THREE.Mesh(geom, mat);
ring.position.set(pos[0], pos[1], pos[2] + 0.001); // slightly above table
scene.add(ring);
slotHelpers.push(ring);
});
}
function initRobotStructure() {
if (robotGroup) scene.remove(robotGroup);
robotGroup = new THREE.Group();
scene.add(robotGroup);
joints.joint1 = new THREE.Group();
joints.joint2 = new THREE.Group();
joints.joint3 = new THREE.Group();
joints.joint4 = new THREE.Group();
joints.joint5 = new THREE.Group();
joints.joint6 = new THREE.Group();
joints.joint7 = new THREE.Group();
joints.joint8 = new THREE.Group();
joints.handJoint = new THREE.Group();
joints.fingerJoint1 = new THREE.Group();
joints.fingerJoint2 = new THREE.Group();
const link0 = new THREE.Group();
const link1 = new THREE.Group();
const link2 = new THREE.Group();
const link3 = new THREE.Group();
const link4 = new THREE.Group();
const link5 = new THREE.Group();
const link6 = new THREE.Group();
const link7 = new THREE.Group();
const link8 = new THREE.Group();
const hand = new THREE.Group();
const leftFinger = new THREE.Group();
const rightFinger = new THREE.Group();
robotGroup.add(link0);
link0.add(joints.joint1);
joints.joint1.position.set(0, 0, 0.333);
joints.joint1.add(link1);
link1.add(joints.joint2);
joints.joint2.position.set(0, 0, 0);
joints.joint2.rotation.set(-1.57079632679, 0, 0);
joints.joint2.add(link2);
link2.add(joints.joint3);
joints.joint3.position.set(0, -0.316, 0);
joints.joint3.rotation.set(1.57079632679, 0, 0);
joints.joint3.add(link3);
link3.add(joints.joint4);
joints.joint4.position.set(0.0825, 0, 0);
joints.joint4.rotation.set(1.57079632679, 0, 0);
joints.joint4.add(link4);
link4.add(joints.joint5);
joints.joint5.position.set(-0.0825, 0.384, 0);
joints.joint5.rotation.set(-1.57079632679, 0, 0);
joints.joint5.add(link5);
link5.add(joints.joint6);
joints.joint6.position.set(0, 0, 0);
joints.joint6.rotation.set(1.57079632679, 0, 0);
joints.joint6.add(link6);
link6.add(joints.joint7);
joints.joint7.position.set(0.088, 0, 0);
joints.joint7.rotation.set(1.57079632679, 0, 0);
joints.joint7.add(link7);
link7.add(joints.joint8);
joints.joint8.position.set(0, 0, 0.107);
joints.joint8.add(link8);
link8.add(joints.handJoint);
joints.handJoint.position.set(0, 0, 0);
joints.handJoint.rotation.set(0, 0, -0.785398163397);
joints.handJoint.add(hand);
hand.add(joints.fingerJoint1);
joints.fingerJoint1.position.set(0, 0, 0.0584);
joints.fingerJoint1.add(leftFinger);
hand.add(joints.fingerJoint2);
joints.fingerJoint2.position.set(0, 0, 0.0584);
joints.fingerJoint2.add(rightFinger);
const defaultPandaMaterial = new THREE.MeshStandardMaterial({
color: 0xdddddd,
roughness: 0.35,
metalness: 0.15
});
const loadModel = (parent, objPath, mtlPath = null, rotateRightFinger = false) => {
const applyRotation = (obj) => {
if (rotateRightFinger) {
obj.rotation.z = Math.PI;
}
parent.add(obj);
};
if (mtlPath) {
MTL_LOADER.load(mtlPath, (materials) => {
materials.preload();
const objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.load(objPath, (obj) => {
obj.traverse(child => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
applyRotation(obj);
});
});
} else {
const objLoader = new THREE.OBJLoader();
objLoader.load(objPath, (obj) => {
obj.traverse(child => {
if (child.isMesh) {
child.material = defaultPandaMaterial;
child.castShadow = true;
child.receiveShadow = true;
}
});
applyRotation(obj);
});
}
};
loadModel(link0, '/assets/panda/meshes/collision/link0.obj');
loadModel(link1, '/assets/panda/meshes/visual/link1.obj', '/assets/panda/meshes/visual/link1.mtl');
loadModel(link2, '/assets/panda/meshes/visual/link2.obj', '/assets/panda/meshes/visual/link2.mtl');
loadModel(link3, '/assets/panda/meshes/visual/link3.obj', '/assets/panda/meshes/visual/link3.mtl');
loadModel(link4, '/assets/panda/meshes/visual/link4.obj', '/assets/panda/meshes/visual/link4.mtl');
loadModel(link5, '/assets/panda/meshes/visual/link5.obj', '/assets/panda/meshes/visual/link5.mtl');
loadModel(link6, '/assets/panda/meshes/visual/link6.obj', '/assets/panda/meshes/visual/link6.mtl');
loadModel(link7, '/assets/panda/meshes/collision/link7.obj');
loadModel(hand, '/assets/panda/meshes/visual/hand.obj', '/assets/panda/meshes/visual/hand.mtl');
loadModel(leftFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl');
loadModel(rightFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl', true);
// Create eeDummy sphere representing the end-effector target
if (eeDummy) scene.remove(eeDummy);
const dummyGeo = new THREE.SphereGeometry(0.035, 16, 16);
const dummyMat = new THREE.MeshStandardMaterial({
color: 0x3b82f6,
transparent: true,
opacity: 0.65,
roughness: 0.1,
metalness: 0.9
});
eeDummy = new THREE.Mesh(dummyGeo, dummyMat);
eeDummy.name = 'robot';
eeDummy.visible = false;
scene.add(eeDummy);
}
function loadYcbObjects(objectsConfig) {
// Clear old meshes/groups from scene
Object.values(ycbMeshes).forEach(group => scene.remove(group));
for (const key in ycbMeshes) delete ycbMeshes[key];
Object.entries(objectsConfig).forEach(([name, config]) => {
const folder = config.folder;
let objFile = "";
let mtlFile = "";
if (folder === "YcbBanana" || folder === "YcbTomatoSoupCan" || folder === "YcbCrackerBox" || folder === "YcbMustardBottle" || folder === "YcbPottedMeatCan") {
objFile = `/assets/ycb/${folder}/textured_simple_reoriented.obj`;
mtlFile = `/assets/ycb/${folder}/textured_simple_reoriented.mtl`;
} else if (folder === "YcbChipsCan") {
objFile = `/assets/ycb/${folder}/textured.obj`;
mtlFile = `/assets/ycb/${folder}/textured.mtl`;
}
if (!objFile) return;
// Create a parent group to represent the object's body link pose
const objectGroup = new THREE.Group();
objectGroup.name = name;
objectGroup.position.fromArray(config.initial_pos);
objectGroup.quaternion.fromArray(config.initial_ori);
scene.add(objectGroup);
ycbMeshes[name] = objectGroup;
// 1. Load Visual Mesh
MTL_LOADER.load(mtlFile, (materials) => {
materials.preload();
const objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.load(objFile, (visObj) => {
visObj.traverse(child => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
// Position, rotate and scale relative to parent group
if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos);
if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori);
if (config.vis_scale) visObj.scale.fromArray(config.vis_scale);
objectGroup.add(visObj);
});
});
// 2. Load Collision Mesh (Semi-transparent Blue)
const collObjFile = `/assets/ycb/${folder}/collision_vhacd.obj`;
const collLoader = new THREE.OBJLoader();
collLoader.load(collObjFile, (collObj) => {
collObj.traverse(child => {
if (child.isMesh) {
child.material = new THREE.MeshStandardMaterial({
color: 0x0000ff, // blue
transparent: true,
opacity: 0.5, // semi-transparent
roughness: 0.4,
metalness: 0.1
});
child.castShadow = true;
child.receiveShadow = true;
}
});
// Position, rotate and scale relative to parent group
if (config.coll_local_pos) collObj.position.fromArray(config.coll_local_pos);
if (config.coll_local_ori) collObj.quaternion.fromArray(config.coll_local_ori);
if (config.coll_scale) collObj.scale.fromArray(config.coll_scale);
objectGroup.add(collObj);
});
});
}
function updateSimulationState(jointsData, objectsData) {
if (jointsData && jointsData.length >= 11) {
targetJoints = jointsData;
}
if (objectsData) {
Object.entries(objectsData).forEach(([name, data]) => {
targetObjects[name] = {
pos: new THREE.Vector3().fromArray(data.pos),
ori: new THREE.Quaternion().fromArray(data.ori)
};
});
}
}
let reconnectTimeout = null;
function connectWebSocket() {
if (reconnectTimeout) {
clearTimeout(reconnectTimeout);
reconnectTimeout = null;
}
const guiToggle = document.getElementById('gui-toggle');
const showGui = guiToggle ? guiToggle.checked : false;
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=${showGui}`;
updateBadgeStatus('disconnected');
socket = new WebSocket(wsUrl);
socket.onopen = () => {
console.log("WebSocket connected.");
updateBadgeStatus('connected');
writeLog("Kết nối thành công đến Backend server.", "success");
};
socket.onmessage = (event) => {
const msg = JSON.parse(event.data);
handleSocketMessage(msg);
};
socket.onclose = () => {
console.log("WebSocket disconnected.");
updateBadgeStatus('disconnected');
writeLog("Mất kết nối đến Backend server. Đang thử kết nối lại...", "error");
reconnectTimeout = setTimeout(connectWebSocket, 3000);
};
socket.onerror = (err) => {
console.error("WebSocket Error: ", err);
};
}
function handleSocketMessage(msg) {
switch(msg.type) {
case 'init':
createTable(msg.table);
createTray(msg.tray);
createSlotHelpers(msg.slots);
loadYcbObjects(msg.objects);
initRobotStructure();
isInitialStateSynced = false; // Reset sync state for new simulations
break;
case 'state':
updateSimulationState(msg.joints, msg.objects);
break;
case 'log':
writeLog(msg.message, getLogClass(msg.message));
updatePipelineUI(msg.message);
break;
case 'plan':
displayPlan(msg.plan);
break;
case 'result':
showRearrangementScore(msg.score_display);
unlockInput();
// Add new run record to history log dynamically
const now = new Date();
const timeStr = now.toTimeString().split(' ')[0];
const scoreVal = msg.score_value !== undefined ? msg.score_value : 100;
const scoreClass = scoreVal >= 90 ? "high" : (scoreVal >= 60 ? "medium" : "low");
historyData.unshift({
time: timeStr,
operator: "Operator",
prompt: currentPrompt || "Câu lệnh nhanh",
score: scoreVal,
class: scoreClass
});
renderHistory();
// Speak speech feedback
speakFeedback(`Đã hoàn thành vận hành. Điểm rearrangement đạt ${scoreVal} điểm.`);
break;
}
}
// ─── UI Updates and Interactions ────────────────────────────────────────────
const badge = document.getElementById('connection-badge');
const logConsole = document.getElementById('log-console');
const planList = document.getElementById('plan-list');
const chatInput = document.getElementById('chat-input');
const submitBtn = document.getElementById('submit-btn');
const mockToggle = document.getElementById('mock-toggle');
const guiToggle = document.getElementById('gui-toggle');
const resetBtn = document.getElementById('reset-btn');
const scoreModal = document.getElementById('score-modal');
const scoreContent = document.getElementById('score-md-content');
const closeModalBtn = document.getElementById('close-modal-btn');
const ttsToggle = document.getElementById('tts-toggle');
const autocompletePanel = document.getElementById('autocomplete-panel');
// 1. Tab switching logic
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
btn.classList.add('active');
const tabId = btn.dataset.tab;
document.getElementById(`panel-${tabId}`).classList.add('active');
});
});
// 2. Scenario template click events
document.querySelectorAll('.scenario-card').forEach(card => {
card.addEventListener('click', () => {
const prompt = card.dataset.prompt;
chatInput.value = prompt;
chatInput.focus();
});
});
document.querySelectorAll('.preset-command-item').forEach(item => {
item.addEventListener('click', () => {
const prompt = item.dataset.prompt;
chatInput.value = prompt;
chatInput.focus();
});
});
// 3. Object Catalog Data & Render
const activeObjects = [
{ id: "banana", name: "Quả chuối (YCB)", mass: 0.066, friction: 0.8, trait: "Safe" },
{ id: "soup_can", name: "Lon súp cà chua", mass: 0.349, friction: 0.8, trait: "Safe" },
{ id: "chips_can", name: "Lon snack khoai tây", mass: 0.205, friction: 0.5, trait: "Safe" }
];
function renderObjectsTable() {
const objectsTableBody = document.getElementById('objects-table-body');
if (!objectsTableBody) return;
objectsTableBody.innerHTML = activeObjects.map(obj => `
<tr>
<td><strong>${obj.name}</strong><br><span style="font-size:0.7rem; opacity:0.6">${obj.id}</span></td>
<td>${obj.mass}</td>
<td>${obj.friction}</td>
<td><span class="tag-badge safe">${obj.trait}</span></td>
</tr>
`).join('');
}
// 4. History Logs Data & Render
const historyData = [
{ time: "14:20:15", operator: "Operator", prompt: "gắp lon snack đặt vào khay", score: 100, class: "high" },
{ time: "14:15:32", operator: "Operator", prompt: "dọn dẹp chướng ngại vật ở khay", score: 85, class: "medium" },
{ time: "14:02:10", operator: "Operator", prompt: "gắp quả chuối đặt vào Slot_2", score: 100, class: "high" }
];
function renderHistory() {
const historyList = document.getElementById('history-list');
if (!historyList) return;
historyList.innerHTML = historyData.map((item, index) => `
<div class="history-card">
<div class="history-card-header">
<span>🕒 ${item.time} - ${item.operator}</span>
<span class="history-score ${item.class}">${item.score}/100</span>
</div>
<p class="history-card-prompt">"${item.prompt}"</p>
<div class="history-card-footer">
<span style="font-size:0.7rem; opacity:0.7">API Cost: ~$0.002</span>
<div class="history-actions">
<button class="history-action-btn" onclick="runHistoryPrompt(${index})">
<svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg> Chạy lại
</button>
</div>
</div>
</div>
`).join('');
}
window.runHistoryPrompt = function(index) {
const item = historyData[index];
if (item) {
chatInput.value = item.prompt;
chatInput.focus();
document.getElementById('chat-form').dispatchEvent(new Event('submit'));
}
};
// 5. Speech Synthesis (Text-to-Speech)
function speakFeedback(text) {
if (!ttsToggle || !ttsToggle.checked) return;
// Determine language based on text content (Vietnamese by default, English if it contains mostly technical terms)
let lang = 'vi';
const textLower = text.toLowerCase();
if (textLower.includes('evaluation') || textLower.includes('score') || textLower.includes('report') || textLower.includes('step') || textLower.includes('verification')) {
lang = 'en';
}
// Call Google Translate TTS (free API) for high-quality English & Vietnamese voices
const encodedText = encodeURIComponent(text);
const ttsUrl = `https://translate.google.com/translate_tts?ie=UTF-8&tl=${lang}&client=tw-ob&q=${encodedText}`;
const audio = new Audio(ttsUrl);
audio.play().catch(err => {
console.warn("Google Translate TTS failed, falling back to local speech synthesis:", err);
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = lang === 'vi' ? 'vi-VN' : 'en-US';
utterance.rate = 1.0;
utterance.pitch = 1.0;
const voices = window.speechSynthesis.getVoices();
const matchingVoice = voices.find(voice => voice.lang.includes(lang));
if (matchingVoice) utterance.voice = matchingVoice;
window.speechSynthesis.speak(utterance);
}
});
}
// 6. Voice Recognition (Speech-to-Text)
const micBtn = document.getElementById('mic-btn');
let recognition = null;
let isRecording = false;
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
recognition = new SpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = 'vi-VN';
recognition.onstart = () => {
isRecording = true;
micBtn.classList.add('recording');
writeLog("Đang nghe giọng nói của bạn... Hãy nói đi.", "info");
speakFeedback("Tôi đang nghe.");
};
recognition.onresult = (event) => {
const resultText = event.results[0][0].transcript;
chatInput.value = resultText;
writeLog(`Nhận dạng giọng nói: "${resultText}"`, "success");
speakFeedback(`Đã nhận diện: ${resultText}`);
};
recognition.onerror = (event) => {
console.error("Speech Recognition Error: ", event.error);
writeLog("Nhận diện giọng nói gặp lỗi: " + event.error, "warn");
isRecording = false;
micBtn.classList.remove('recording');
};
recognition.onend = () => {
isRecording = false;
micBtn.classList.remove('recording');
};
micBtn.addEventListener('click', () => {
if (isRecording) {
recognition.stop();
} else {
recognition.start();
}
});
} else {
micBtn.style.display = 'none';
}
// 7. Smart Autocomplete suggestions
const autocompleteVocabulary = [
"gắp quả chuối đặt vào khay",
"gắp quả chuối đặt vào Slot_2",
"gắp quả chuối đặt vào Slot_4",
"gắp lon súp cà chua đặt vào khay",
"gắp lon súp cà chua đặt vào Slot_3",
"gắp lon snack đặt vào khay",
"gắp lon snack đặt vào Slot_6",
"dọn dẹp chướng ngại vật trên bàn",
"sắp xếp lại bàn học tập",
"cất dọn đồ vật nguy hiểm"
];
if (chatInput && autocompletePanel) {
chatInput.addEventListener('input', (e) => {
const query = e.target.value.toLowerCase().trim();
if (!query || query.length < 2) {
autocompletePanel.classList.add('hidden');
return;
}
const matches = autocompleteVocabulary.filter(item => item.includes(query)).slice(0, 4);
if (matches.length === 0) {
autocompletePanel.classList.add('hidden');
return;
}
autocompletePanel.innerHTML = matches.map(match => `
<div class="autocomplete-item" data-value="${match}">${match}</div>
`).join('');
autocompletePanel.classList.remove('hidden');
document.querySelectorAll('.autocomplete-item').forEach(item => {
item.addEventListener('click', () => {
chatInput.value = item.dataset.value;
autocompletePanel.classList.add('hidden');
chatInput.focus();
});
});
});
document.addEventListener('click', (e) => {
if (!e.target.closest('#chat-form')) {
autocompletePanel.classList.add('hidden');
}
});
}
// 8. Log and Pipeline functions
function updateBadgeStatus(status) {
if (status === 'connected') {
badge.className = 'badge online';
badge.textContent = 'Connected';
} else {
badge.className = 'badge offline';
badge.textContent = 'Disconnected';
}
}
function writeLog(text, className = 'info') {
const entry = document.createElement('div');
entry.className = `log-entry ${className}`;
entry.textContent = `> ${text}`;
const placeholder = logConsole.querySelector('.placeholder-text');
if (placeholder) placeholder.remove();
logConsole.appendChild(entry);
logConsole.scrollTop = logConsole.scrollHeight;
}
function getLogClass(message) {
if (message.includes('✅')) return 'success';
if (message.includes('❌')) return 'error';
if (message.includes('⚠️')) return 'warn';
if (message.includes('🚀') || message.includes('⏳')) return 'info';
return '';
}
function updatePipelineUI(message) {
const stepLlm = document.getElementById('step-llm');
const stepVal = document.getElementById('step-val');
const stepExec = document.getElementById('step-exec');
const stepScore = document.getElementById('step-score');
if (message.includes('[1/5]')) {
setActiveStep(stepLlm);
} else if (message.includes('✅ [1]')) {
setCompletedStep(stepLlm);
} else if (message.includes('❌ [1]')) {
setErrorStep(stepLlm);
unlockInput();
speakFeedback("Lập kế hoạch thất bại. Vui lòng kiểm tra lại câu lệnh.");
}
else if (message.includes('[2/5]')) {
setActiveStep(stepVal);
} else if (message.includes('✅ [2]')) {
setCompletedStep(stepVal);
} else if (message.includes('❌ [2]') || message.includes('⚠️ [2]')) {
if (message.includes('❌')) {
setErrorStep(stepVal);
unlockInput();
speakFeedback("Kế hoạch không hợp lệ. Vi phạm các quy tắc an toàn.");
} else {
stepVal.className = 'status-step active warn';
}
}
else if (message.includes('[3/5]')) {
setActiveStep(stepExec);
} else if (message.includes('Thực thi thành công')) {
setCompletedStep(stepExec);
} else if (message.includes('Thực thi kết thúc có bước lỗi')) {
setErrorStep(stepExec);
speakFeedback("Quá trình thực thi gặp sự cố va chạm.");
}
else if (message.includes('[5/5]')) {
setActiveStep(stepScore);
} else if (message.includes('Rearrangement Evaluation Report') || message.includes('result')) {
setCompletedStep(stepScore);
unlockInput();
}
}
function setActiveStep(el) {
el.className = 'status-step active';
}
function setCompletedStep(el) {
el.className = 'status-step completed';
}
function setErrorStep(el) {
el.className = 'status-step error';
}
function displayPlan(plan) {
planList.innerHTML = '';
plan.forEach(step => {
const item = document.createElement('div');
item.className = 'plan-item';
item.id = `plan-step-${step.step}`;
const argsStr = Object.entries(step.args)
.map(([k, v]) => `${k}:${v}`)
.join(', ');
item.innerHTML = `
<span><b>Step ${step.step}:</b> ${step.skill}(${step.object})</span>
<span style="font-size: 0.75rem; opacity: 0.8;">${argsStr}</span>
`;
planList.appendChild(item);
});
}
function showRearrangementScore(markdownText) {
let html = markdownText
.replace(/### (.*)/g, '<h3>$1</h3>')
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/- (.*)/g, '<li>$1</li>')
.replace(/\n\n/g, '<br>')
.replace(/✅/g, '<span style="color:#10b981">✅</span>')
.replace(/⚠️/g, '<span style="color:#f59e0b">⚠️</span>')
.replace(/❌/g, '<span style="color:#ef4444">❌</span>');
scoreContent.innerHTML = html;
scoreModal.classList.remove('hidden');
}
function lockInput() {
chatInput.disabled = true;
submitBtn.disabled = true;
resetBtn.disabled = true;
mockToggle.disabled = true;
if (guiToggle) guiToggle.disabled = true;
}
document.getElementById('chat-form').addEventListener('submit', (e) => {
e.preventDefault();
const prompt = chatInput.value.trim();
if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return;
currentPrompt = prompt;
chatInput.value = '';
logConsole.innerHTML = '';
planList.innerHTML = '<p class="placeholder-text">Đang tải kế hoạch...</p>';
['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => {
document.getElementById(id).className = 'status-step';
});
writeLog(`Gửi yêu cầu: "${prompt}"`, "info");
lockInput();
speakFeedback("Bắt đầu xử lý câu lệnh điều khiển của bạn.");
socket.send(JSON.stringify({
type: 'run',
prompt: prompt,
mock: mockToggle.checked
}));
});
function unlockInput() {
chatInput.disabled = false;
submitBtn.disabled = false;
resetBtn.disabled = false;
mockToggle.disabled = false;
if (guiToggle) guiToggle.disabled = false;
}
resetBtn.addEventListener('click', () => {
if (!socket || socket.readyState !== WebSocket.OPEN) return;
logConsole.innerHTML = '';
planList.innerHTML = '<p class="placeholder-text">Chưa có kế hoạch...</p>';
['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => {
document.getElementById(id).className = 'status-step';
});
socket.send(JSON.stringify({
type: 'reset'
}));
});
closeModalBtn.addEventListener('click', () => {
scoreModal.classList.add('hidden');
unlockInput();
});
if (guiToggle) {
guiToggle.addEventListener('change', () => {
writeLog("Thay đổi thiết lập hiển thị cửa sổ PyBullet. Đang kết nối lại...", "info");
if (socket) {
socket.onclose = null;
socket.close();
}
connectWebSocket();
});
}
// 10. Manual joint controls sending
function sendManualJoints() {
if (!socket || socket.readyState !== WebSocket.OPEN) return;
const q0 = parseFloat(document.getElementById('slider-j1').value);
const q1 = parseFloat(document.getElementById('slider-j2').value);
const q2 = parseFloat(document.getElementById('slider-j3').value);
const q3 = parseFloat(document.getElementById('slider-j4').value);
const q4 = parseFloat(document.getElementById('slider-j5').value);
const q5 = parseFloat(document.getElementById('slider-j6').value);
const q6 = parseFloat(document.getElementById('slider-j7').value);
const qg = parseFloat(document.getElementById('slider-jg').value);
socket.send(JSON.stringify({
type: "update_joints",
joints: [q0, q1, q2, q3, q4, q5, q6, 0.0, 0.0, qg, qg]
}));
}
const slidersList = ['j1', 'j2', 'j3', 'j4', 'j5', 'j6', 'j7', 'jg'];
slidersList.forEach(id => {
const slider = document.getElementById(`slider-${id}`);
const label = document.getElementById(`val-${id}`);
if (slider && label) {
slider.addEventListener('input', (e) => {
const val = parseFloat(e.target.value);
label.textContent = id === 'jg' ? val.toFixed(3) : val.toFixed(2);
sendManualJoints();
});
}
});
// 11. Interactive Drag and Drop for YCB objects and Robot End Effector using THREE.TransformControls
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// State variables for Hover Highlight
const originalEmissives = new Map();
let hoveredGroup = null;
canvas.addEventListener('mousedown', onMouseDown);
canvas.addEventListener('mousemove', onMouseMove);
// Helper to determine if an intersected object belongs to a draggable group (YCB or Robot)
function findDraggableTarget(hitObject) {
let curr = hitObject;
while (curr && curr !== scene) {
if (curr === robotGroup) {
return { type: 'robot', group: robotGroup, name: 'robot' };
}
const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr);
if (ycbEntry) {
return { type: 'ycb', group: ycbEntry[1], name: ycbEntry[0] };
}
curr = curr.parent;
}
return null;
}
// Helper to set/restore emissive highlight glow on all child meshes of a group
function highlightGroup(group, highlightColor = null) {
if (!group) return;
group.traverse(child => {
if (child.isMesh) {
if (highlightColor) {
if (!originalEmissives.has(child.uuid)) {
if (child.material && child.material.emissive) {
originalEmissives.set(child.uuid, {
color: child.material.emissive.clone(),
material: child.material
});
}
}
if (child.material && child.material.emissive) {
child.material.emissive.copy(highlightColor);
}
} else {
const orig = originalEmissives.get(child.uuid);
if (orig && orig.material && orig.material.emissive) {
orig.material.emissive.copy(orig.color);
}
}
}
});
}
function onMouseDown(event) {
if (event.button !== 0 || chatInput.disabled) return;
// Ignore clicks if we are already dragging the transform controls handles
if (transformControls && transformControls.dragging) return;
const rect = canvas.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObjects(scene.children, true);
let target = null;
// Check if the click hit the Gizmo itself
for (let i = 0; i < hits.length; i++) {
// Exclude the gizmo meshes themselves
let isGizmo = false;
let p = hits[i].object;
while (p) {
if (p === transformControls) {
isGizmo = true;
break;
// Click is on the gizmo handles; let TransformControls handle it
return;
}
p = p.parent;
}
if (isGizmo) continue;
}
let target = null;
for (let i = 0; i < hits.length; i++) {
const found = findDraggableTarget(hits[i].object);
if (found) {
target = found;
break;
}
}
if (target) {
if (target.type === 'robot') {
if (eeDummy && joints.handJoint) {
const handWorldPos = new THREE.Vector3();
joints.handJoint.getWorldPosition(handWorldPos);
eeDummy.position.copy(handWorldPos);
eeDummy.visible = true;
transformControls.attach(eeDummy);
writeLog("Đã kích hoạt Gizmo điều khiển cánh tay robot. Kéo các trục mũi tên để dịch chuyển.", "info");
}
} else {
if (transformControls.object === eeDummy) {
eeDummy.visible = false;
}
transformControls.attach(target.group);
writeLog(`Đã chọn vật thể: ${target.name}. Kéo các trục mũi tên để dịch chuyển.`, "info");
}
} else {
if (transformControls && !transformControls.dragging) {
if (transformControls.object === eeDummy) {
eeDummy.visible = false;
}
transformControls.detach();
}
}
}
function onMouseMove(event) {
if (transformControls && transformControls.dragging) {
return;
}
const rect = canvas.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObjects(scene.children, true);
let hoverTarget = null;
// Check if the mouse is hovering over the Gizmo itself
for (let i = 0; i < hits.length; i++) {
let isGizmo = false;
let p = hits[i].object;
while (p) {
if (p === transformControls) {
isGizmo = true;
break;
// Let Gizmo handle cursors and mouse interaction
return;
}
p = p.parent;
}
if (isGizmo) continue;
}
let hoverTarget = null;
for (let i = 0; i < hits.length; i++) {
const found = findDraggableTarget(hits[i].object);
if (found) {
hoverTarget = found;
break;
}
}
if (hoverTarget) {
if (hoveredGroup !== hoverTarget.group) {
if (hoveredGroup) {
highlightGroup(hoveredGroup, null);
}
originalEmissives.clear();
hoveredGroup = hoverTarget.group;
const glowColor = new THREE.Color(hoverTarget.type === 'robot' ? '#1e40af' : '#2563eb');
highlightGroup(hoveredGroup, glowColor);
canvas.style.cursor = 'pointer';
}
} else {
if (hoveredGroup) {
highlightGroup(hoveredGroup, null);
hoveredGroup = null;
originalEmissives.clear();
canvas.style.cursor = '';
}
}
}
// 12. Initial runs
initVisualizer();
connectWebSocket();
renderObjectsTable();
renderHistory();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595:root {
--primary-color: #1e3a8a; /* Dark Navy Blue */
--primary-glow: rgba(30, 58, 138, 0.3);
--accent-success: #064e3b; /* Very Dark Green */
--accent-warning: #78350f; /* Dark Amber/Brown */
--accent-error: #7f1d1d; /* Dark Red */
--bg-dark: #f8fafc;
--text-main: #000000; /* Pure Black for maximum contrast */
--text-muted: #1e293b; /* Dark Slate */
--hud-text-shadow: 0 1px 3px rgba(255, 255, 255, 0.95), 0 0 6px rgba(255, 255, 255, 0.85);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Outfit', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background-color: #f1f5f9;
color: var(--text-main);
overflow: hidden;
width: 100vw;
height: 100vh;
}
/* Fullscreen Viewport Container */
#viewport-container {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #f1f5f9;
z-index: 1;
overflow: hidden;
}
#pybullet-viewport {
width: 100%;
height: 100%;
object-fit: cover; /* Stretches to fill widescreen displays without borders */
border: none;
border-radius: 0;
box-shadow: none;
cursor: grab;
}
#pybullet-viewport:active {
cursor: grabbing;
}
/* Transparent HUD Panels with Premium Glassmorphism */
.glass {
background: rgba(255, 255, 255, 0.75);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.4);
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.08);
border-radius: 16px;
}
/* Sidebar Styling (Light-HUD layout) */
.sidebar {
position: absolute;
top: 20px;
left: 20px;
width: 360px;
height: calc(100vh - 40px);
z-index: 10;
padding: 24px;
display: flex;
flex-direction: column;
gap: 22px;
pointer-events: auto;
}
.sidebar-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 2px solid rgba(37, 99, 235, 0.3);
padding-bottom: 12px;
}
.sidebar-header h2 {
font-family: 'Space Grotesk', sans-serif;
font-size: 1.6rem;
font-weight: 700;
letter-spacing: -0.025em;
color: #1e3a8a; /* Navy Blue */
text-shadow: var(--hud-text-shadow);
}
.badge {
font-size: 0.75rem;
font-weight: 700;
padding: 4px 12px;
border-radius: 12px;
text-transform: uppercase;
letter-spacing: 0.05em;
display: inline-flex;
align-items: center;
gap: 6px;
text-shadow: var(--hud-text-shadow);
border: 1px solid currentColor;
}
.badge::before {
content: '';
display: inline-block;
width: 6px;
height: 6px;
border-radius: 50%;
}
.badge.online {
background: rgba(16, 185, 129, 0.15);
color: var(--accent-success);
}
.badge.online::before {
background: var(--accent-success);
box-shadow: 0 0 8px var(--accent-success);
}
.badge.offline {
background: rgba(239, 68, 68, 0.15);
color: var(--accent-error);
}
.badge.offline::before {
background: var(--accent-error);
}
.sidebar-section {
display: flex;
flex-direction: column;
gap: 10px;
}
.sidebar-section.flex-grow {
flex-grow: 1;
min-height: 0;
}
.sidebar-section h3 {
font-size: 0.85rem;
font-weight: 700;
text-transform: uppercase;
color: var(--primary-color); /* Darker blue header */
letter-spacing: 0.05em;
text-shadow: var(--hud-text-shadow);
}
/* Status Steps */
.status-steps {
display: flex;
flex-direction: column;
gap: 10px;
background: transparent;
padding: 0;
}
.status-step {
display: flex;
align-items: center;
gap: 12px;
font-size: 0.95rem;
color: var(--text-muted);
font-weight: 600;
text-shadow: var(--hud-text-shadow);
transition: all 0.3s ease;
}
.status-step .dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: rgba(15, 23, 42, 0.3);
border: 1px solid rgba(15, 23, 42, 0.5);
transition: all 0.3s ease;
}
.status-step.active {
color: var(--primary-color);
}
.status-step.active .dot {
background: var(--primary-color);
box-shadow: 0 0 8px var(--primary-color);
border-color: var(--primary-color);
}
.status-step.completed {
color: var(--accent-success);
}
.status-step.completed .dot {
background: var(--accent-success);
border-color: var(--accent-success);
}
.status-step.error {
color: var(--accent-error);
}
.status-step.error .dot {
background: var(--accent-error);
border-color: var(--accent-error);
}
/* Plan steps list (translucent backdrop for readability) */
.plan-list {
background: rgba(255, 255, 255, 0.65);
backdrop-filter: blur(8px);
border: 1px solid rgba(0, 0, 0, 0.08);
border-radius: 10px;
max-height: 160px;
overflow-y: auto;
padding: 10px;
display: flex;
flex-direction: column;
gap: 6px;
box-shadow: 0 4px 20px rgba(0,0,0,0.05);
}
.plan-item {
font-size: 0.85rem;
padding: 8px 10px;
background: rgba(255, 255, 255, 0.4);
border-radius: 6px;
border-left: 3px solid rgba(0, 0, 0, 0.1);
color: var(--text-main);
font-weight: 500;
display: flex;
justify-content: space-between;
}
.plan-item.active {
background: rgba(37, 99, 235, 0.08);
border-left-color: var(--primary-color);
color: var(--primary-color);
font-weight: 600;
}
.plan-item.completed {
border-left-color: var(--accent-success);
color: rgba(15, 23, 42, 0.4);
text-decoration: line-through;
opacity: 0.6;
}
/* Scrollable Log Console (translucent backdrop for readability) */
.log-console {
background: rgba(255, 255, 255, 0.65);
backdrop-filter: blur(8px);
border: 1px solid rgba(0, 0, 0, 0.08);
font-family: 'Space Grotesk', monospace;
font-size: 0.85rem;
line-height: 1.4;
border-radius: 10px;
padding: 12px;
overflow-y: auto;
flex-grow: 1;
display: flex;
flex-direction: column;
gap: 6px;
box-shadow: 0 4px 20px rgba(0,0,0,0.05);
}
.log-entry {
color: var(--text-main);
font-weight: 600;
}
.log-entry.info { color: #1e3a8a; }
.log-entry.success { color: #064e3b; }
.log-entry.warn { color: #78350f; }
.log-entry.error { color: #7f1d1d; }
.placeholder-text {
color: var(--text-muted);
font-style: italic;
text-align: center;
margin: auto;
}
/* Floating Chat Input Box */
.chat-container {
position: absolute;
bottom: 30px;
left: calc(50% + 185px);
transform: translateX(-50%);
width: 650px;
z-index: 10;
padding: 12px;
display: flex;
flex-direction: column;
gap: 12px;
pointer-events: auto;
}
#chat-form {
display: flex;
gap: 12px;
align-items: center;
}
#chat-input {
flex-grow: 1;
background: rgba(255, 255, 255, 0.75); /* Highly readable text entry */
backdrop-filter: blur(10px);
border: 2px solid var(--primary-color);
box-shadow: 0 4px 20px rgba(0,0,0,0.08);
padding: 14px 20px;
border-radius: 12px;
color: #0f172a;
font-size: 1rem;
font-weight: 600;
outline: none;
transition: all 0.3s ease;
}
#chat-input:focus {
border-color: #1d4ed8;
background: rgba(255, 255, 255, 0.9);
box-shadow: 0 0 15px rgba(37, 99, 235, 0.3);
}
#submit-btn {
background: var(--primary-color);
color: white;
border: none;
width: 50px;
height: 50px;
border-radius: 12px;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.3s ease;
box-shadow: 0 4px 12px var(--primary-glow);
}
#submit-btn:hover {
background: #1d4ed8;
box-shadow: 0 4px 20px rgba(29, 78, 216, 0.5);
transform: translateY(-1px);
}
#submit-btn:active {
transform: translateY(1px);
}
#submit-btn:disabled, #chat-input:disabled {
opacity: 0.4;
cursor: not-allowed;
box-shadow: none;
}
.chat-options {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.85rem;
color: #0f172a;
font-weight: 600;
text-shadow: var(--hud-text-shadow);
}
/* Toggle Switch */
.toggle-switch {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
.toggle-switch input {
display: none;
}
.slider {
position: relative;
display: inline-block;
width: 36px;
height: 20px;
background-color: rgba(15, 23, 42, 0.2);
border-radius: 20px;
transition: .4s;
border: 1px solid rgba(0, 0, 0, 0.2);
}
.slider:before {
position: absolute;
content: "";
height: 12px;
width: 12px;
left: 3px;
bottom: 3px;
background-color: #0f172a;
border-radius: 50%;
transition: .4s;
}
.toggle-switch input:checked + .slider {
background-color: var(--primary-color);
border-color: #1d4ed8;
}
.toggle-switch input:checked + .slider:before {
background-color: white;
transform: translateX(16px);
}
.toggle-label {
user-select: none;
}
/* Buttons */
.text-btn {
background: none;
border: none;
color: #1d4ed8;
cursor: pointer;
font-weight: 700;
transition: color 0.2s;
font-size: 0.85rem;
text-shadow: var(--hud-text-shadow);
}
.text-btn:hover {
color: #0f172a;
}
.primary-btn {
background: var(--primary-color);
color: white;
border: none;
padding: 10px 24px;
border-radius: 8px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
box-shadow: 0 4px 12px var(--primary-glow);
}
.primary-btn:hover {
background: #1d4ed8;
box-shadow: 0 4px 20px rgba(29, 78, 216, 0.4);
}
/* Header overlays */
.header-overlay {
position: absolute;
top: 20px;
left: 390px;
right: 20px;
z-index: 10;
pointer-events: none;
}
.header-overlay h1 {
font-family: 'Space Grotesk', sans-serif;
font-size: 1.4rem;
font-weight: 700;
letter-spacing: -0.015em;
color: #0f172a;
text-shadow: var(--hud-text-shadow);
margin-bottom: 4px;
}
.header-overlay p {
font-size: 0.85rem;
color: var(--text-muted);
text-shadow: var(--hud-text-shadow);
margin-bottom: 12px;
}
.preset-badges {
pointer-events: auto;
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.preset-badge {
background: rgba(255, 255, 255, 0.75);
border: 1.5px solid var(--primary-color);
color: var(--text-main);
font-family: inherit;
font-size: 0.8rem;
font-weight: 600;
padding: 6px 14px;
border-radius: 8px;
cursor: pointer;
transition: all 0.2s;
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
.preset-badge:hover {
background: rgba(255, 255, 255, 0.95);
border-color: #1d4ed8;
box-shadow: 0 4px 15px rgba(37, 99, 235, 0.2);
transform: translateY(-1px);
}
/* Modal Overlay for Score Card */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(15, 23, 42, 0.45);
backdrop-filter: blur(10px);
z-index: 1000;
display: flex;
justify-content: center;
align-items: center;
opacity: 1;
transition: opacity 0.3s ease;
}
.modal-overlay.hidden {
opacity: 0;
pointer-events: none;
}
.modal-content {
width: 500px;
max-width: 90%;
padding: 30px;
display: flex;
flex-direction: column;
gap: 20px;
background: rgba(255, 255, 255, 0.9) !important;
border: 2px solid var(--primary-color) !important;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2) !important;
border-radius: 16px;
animation: scaleUp 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}
@keyframes scaleUp {
from { transform: scale(0.9); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
.modal-content h2 {
font-family: 'Space Grotesk', sans-serif;
font-size: 1.5rem;
text-align: center;
border-bottom: 2px solid rgba(37, 99, 235, 0.2);
padding-bottom: 12px;
color: #0f172a;
}
.score-md-content {
font-size: 0.95rem;
line-height: 1.6;
color: #334155;
}
.score-md-content h3 {
margin: 14px 0 6px 0;
font-size: 1.15rem;
color: #1d4ed8;
}
.score-md-content ul {
padding-left: 20px;
margin-bottom: 10px;
}
.score-md-content li {
margin-bottom: 4px;
}
.score-md-content strong {
color: #0f172a;
}
/* Scrollbars styling */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: rgba(37, 99, 235, 0.25);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(37, 99, 235, 0.45);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LLM-Panda Web-Embedded PyBullet Simulation</title>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Space+Grotesk:wght@400;500;700&display=swap" rel="stylesheet">
<!-- Three.js libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/MTLLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/OBJLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<!-- Main Style -->
<link rel="stylesheet" href="/static/index.css">
</head>
<body>
<!-- Real-Time PyBullet Streaming Viewport -->
<div id="viewport-container">
<canvas id="pybullet-viewport"></canvas>
</div>
<!-- Status & Logs Sidebar -->
<div class="sidebar glass">
<div class="sidebar-header">
<h2>🤖 LLM-Panda</h2>
<span class="badge offline" id="connection-badge">Disconnected</span>
</div>
<div class="sidebar-section">
<h3>📊 Pipeline Status</h3>
<div class="status-steps">
<div class="status-step" id="step-llm">
<span class="dot"></span>
<span class="step-label">1. LLM Planning</span>
</div>
<div class="status-step" id="step-val">
<span class="dot"></span>
<span class="step-label">2. Rule Validation</span>
</div>
<div class="status-step" id="step-exec">
<span class="dot"></span>
<span class="step-label">3. PyBullet Execution</span>
</div>
<div class="status-step" id="step-score">
<span class="dot"></span>
<span class="step-label">4. Scoring & Feedback</span>
</div>
</div>
</div>
<div class="sidebar-section">
<h3>📋 Task Plan</h3>
<div id="plan-list" class="plan-list">
<p class="placeholder-text">Chưa có kế hoạch...</p>
</div>
</div>
<div class="sidebar-section flex-grow">
<h3>📺 Execution Log</h3>
<div id="log-console" class="log-console">
<p class="placeholder-text">Đang đợi yêu cầu...</p>
</div>
</div>
</div>
<!-- Floating Chat Window (Glassmorphic Overlay) -->
<div class="chat-container glass">
<form id="chat-form">
<input
type="text"
id="chat-input"
placeholder="Nhập yêu cầu dọn bàn... (e.g. 'Sắp xếp bàn học tập', 'Dọn đồ nguy hiểm')"
autocomplete="off"
required
>
<button type="submit" id="submit-btn">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M2,21L23,12L2,3V10L17,12L2,14V21Z"/>
</svg>
</button>
</form>
<div class="chat-options">
<label class="toggle-switch">
<input type="checkbox" id="mock-toggle" checked>
<span class="slider"></span>
<span class="toggle-label">Use Mock Preset Plans (Fast & Offline)</span>
</label>
<label class="toggle-switch">
<input type="checkbox" id="gui-toggle" checked>
<span class="slider"></span>
<span class="toggle-label">Hiển thị cửa sổ PyBullet</span>
</label>
<button id="reset-btn" class="text-btn">🔄 Reset Scene</button>
</div>
</div>
<!-- Top Instructions & Preset Badges Overlay -->
<div class="header-overlay">
<h1>Web-Embedded PyBullet Interface</h1>
<p>Tương tác trực tiếp: <b>Kéo chuột trái</b> để xoay camera, <b>Kéo chuột phải</b> để di chuyển camera, <b>Cuộn chuột</b> để Zoom</p>
<div class="preset-badges">
<button class="preset-badge" data-prompt="Tôi cần chuẩn bị bàn để sửa một thiết bị điện tử nhỏ. Hãy dọn các vật chứa nước ra xa, cất đồ nguy hiểm vào khu an toàn, đặt công cụ gần trung tâm, và dọn khay đựng dụng cụ trước nếu bị chặn. Không cần chạm vào đồ dễ vỡ trừ khi thật sự cần thiết.">🔌 Sửa đồ điện tử</button>
<button class="preset-badge" data-prompt="Hãy dọn bàn này để một đứa trẻ có thể chơi an toàn. Cất ngay tất cả dao, pin tiểu, và đồ thủy tinh dễ vỡ đi. Chỉ để lại khối đồ chơi xếp hình ở giữa. Bỏ rác vào thùng rác.">🧸 Trẻ em chơi</button>
<button class="preset-badge" data-prompt="Sắp xếp lại bàn để tôi có thể ngồi học bài tập trung. Để sách/vở gần trung tâm, dọn đồ chơi gây mất tập trung đi, cốc nước để ở góc xa nhưng vẫn giữ lại, bỏ rác vào thùng rác.">📚 Bàn học tập</button>
</div>
</div>
<!-- Final Score Display Overlay Modal -->
<div id="score-modal" class="modal-overlay hidden">
<div class="modal-content glass">
<h2>🏆 Rearrangement Evaluation Report</h2>
<div id="score-md-content" class="score-md-content">
<!-- Markdown Content rendered dynamically -->
</div>
<button id="close-modal-btn" class="primary-btn">Đóng</button>
</div>
</div>
<!-- Application Script -->
<script src="/static/app.js"></script>
</body>
</html>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177// ─── WebSocket and Visualizer Setup ────────────────────────────────────────
const canvas = document.getElementById('pybullet-viewport');
// Three.js Core Variables
let renderer, scene, camera, controls;
let robotGroup, tableMesh, trayMesh;
const slotHelpers = [];
const joints = {};
const ycbMeshes = {};
let transformControls = null;
let eeDummy = null;
const OBJ_LOADER = new THREE.OBJLoader();
const MTL_LOADER = new THREE.MTLLoader();
let socket = null;
let currentPrompt = '';
function initVisualizer() {
// Set default coordinate system to Z-up
THREE.Object3D.DefaultUp.set(0, 0, 1);
// Renderer
renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
const width = canvas.clientWidth || window.innerWidth;
const height = canvas.clientHeight || window.innerHeight;
renderer.setSize(width, height, false);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.shadowMap.enabled = true;
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color('#f1f5f9'); // Light smoke gray background
// Camera
camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100);
// Position camera to look down at the table, matching PyBullet default view
camera.position.set(1.2, -1.2, 1.2);
// Controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.target.set(0.5, 0.0, 0.2);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.maxPolarAngle = Math.PI / 2 - 0.02; // do not go below table plane
controls.update();
// Lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.85);
dirLight.position.set(2, -2, 4);
dirLight.castShadow = true;
dirLight.shadow.mapSize.width = 1024;
dirLight.shadow.mapSize.height = 1024;
dirLight.shadow.camera.near = 0.5;
dirLight.shadow.camera.far = 15;
scene.add(dirLight);
const dirLight2 = new THREE.DirectionalLight(0xaaccff, 0.35);
dirLight2.position.set(-2, 2, 2);
scene.add(dirLight2);
// Floor plane
const planeGeo = new THREE.PlaneGeometry(10, 10);
const planeMat = new THREE.MeshStandardMaterial({ color: 0xe2e8f0, roughness: 0.85 });
const plane = new THREE.Mesh(planeGeo, planeMat);
plane.receiveShadow = true;
scene.add(plane);
// Caro background / Grid Helper
const gridHelper = new THREE.GridHelper(10, 100, 0x94a3b8, 0xcbd5e1);
gridHelper.rotation.x = Math.PI / 2;
gridHelper.position.z = 0.001;
scene.add(gridHelper);
// Axes helper (X: Red, Y: Green, Z: Blue)
const axesHelper = new THREE.AxesHelper(0.5);
axesHelper.position.z = 0.002;
scene.add(axesHelper);
// Initialize Transform Controls
transformControls = new THREE.TransformControls(camera, renderer.domElement);
transformControls.addEventListener('dragging-changed', function (event) {
controls.enabled = !event.value;
if (!event.value && transformControls.object && transformControls.object !== eeDummy) {
const obj = transformControls.object;
if (socket && socket.readyState === WebSocket.OPEN) {
const pos = [obj.position.x, obj.position.y, obj.position.z];
const ori = [obj.quaternion.x, obj.quaternion.y, obj.quaternion.z, obj.quaternion.w];
socket.send(JSON.stringify({
type: "update_object_pose",
name: obj.name,
pos: pos,
ori: ori
}));
writeLog(`Đã đặt vật thể ${obj.name} xuống vị trí mới.`, "success");
}
}
});
transformControls.addEventListener('change', function () {
if (transformControls.object) {
const obj = transformControls.object;
if (obj === eeDummy) {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({
type: "update_robot_ee",
pos: [eeDummy.position.x, eeDummy.position.y, eeDummy.position.z]
}));
}
} else {
obj.position.x = Math.max(0.15, Math.min(0.85, obj.position.x));
obj.position.y = Math.max(-0.65, Math.min(0.65, obj.position.y));
obj.position.z = Math.max(0.02, Math.min(0.85, obj.position.z));
if (targetObjects[obj.name]) {
targetObjects[obj.name].pos.copy(obj.position);
}
}
}
});
scene.add(transformControls);
// Start animation loop
animate();
}
let targetJoints = null;
const targetObjects = {};
let isInitialStateSynced = false;
function animate() {
requestAnimationFrame(animate);
if (controls) controls.update();
// Smooth interpolation (Lerp / Slerp) to eliminate visual stutter
if (targetJoints && targetJoints.length >= 11) {
if (!isInitialStateSynced) {
// First tick or after reset: snap immediately to avoid sliding from rest position
joints.joint1.rotation.z = targetJoints[0];
joints.joint2.rotation.z = targetJoints[1];
joints.joint3.rotation.z = targetJoints[2];
joints.joint4.rotation.z = targetJoints[3];
joints.joint5.rotation.z = targetJoints[4];
joints.joint6.rotation.z = targetJoints[5];
joints.joint7.rotation.z = targetJoints[6];
joints.fingerJoint1.position.y = targetJoints[9];
joints.fingerJoint2.position.y = -targetJoints[10];
Object.entries(targetObjects).forEach(([name, target]) => {
if (transformControls && transformControls.object && transformControls.object.name === name) return;
const group = ycbMeshes[name];
if (group) {
group.position.copy(target.pos);
group.quaternion.copy(target.ori);
}
});
isInitialStateSynced = true;
} else {
// Incremental interpolation towards target poses at client framerate (60+ FPS)
const lerpFactor = 0.15; // Balanced tracking speed vs smoothness
joints.joint1.rotation.z = THREE.MathUtils.lerp(joints.joint1.rotation.z, targetJoints[0], lerpFactor);
joints.joint2.rotation.z = THREE.MathUtils.lerp(joints.joint2.rotation.z, targetJoints[1], lerpFactor);
joints.joint3.rotation.z = THREE.MathUtils.lerp(joints.joint3.rotation.z, targetJoints[2], lerpFactor);
joints.joint4.rotation.z = THREE.MathUtils.lerp(joints.joint4.rotation.z, targetJoints[3], lerpFactor);
joints.joint5.rotation.z = THREE.MathUtils.lerp(joints.joint5.rotation.z, targetJoints[4], lerpFactor);
joints.joint6.rotation.z = THREE.MathUtils.lerp(joints.joint6.rotation.z, targetJoints[5], lerpFactor);
joints.joint7.rotation.z = THREE.MathUtils.lerp(joints.joint7.rotation.z, targetJoints[6], lerpFactor);
joints.fingerJoint1.position.y = THREE.MathUtils.lerp(joints.fingerJoint1.position.y, targetJoints[9], lerpFactor);
joints.fingerJoint2.position.y = THREE.MathUtils.lerp(joints.fingerJoint2.position.y, -targetJoints[10], lerpFactor);
Object.entries(targetObjects).forEach(([name, target]) => {
if (transformControls && transformControls.object && transformControls.object.name === name) return;
const group = ycbMeshes[name];
if (group) {
group.position.lerp(target.pos, lerpFactor);
group.quaternion.slerp(target.ori, lerpFactor);
}
});
}
}
// Update joint sliders to match current animation if user is not actively dragging them
const activeEl = document.activeElement;
const isEditingSliders = activeEl && activeEl.id && activeEl.id.startsWith('slider-');
if (!isEditingSliders && targetJoints) {
const j1 = document.getElementById('slider-j1');
if (j1) j1.value = joints.joint1.rotation.z.toFixed(2);
const v1 = document.getElementById('val-j1');
if (v1) v1.textContent = joints.joint1.rotation.z.toFixed(2);
const j2 = document.getElementById('slider-j2');
if (j2) j2.value = joints.joint2.rotation.z.toFixed(2);
const v2 = document.getElementById('val-j2');
if (v2) v2.textContent = joints.joint2.rotation.z.toFixed(2);
const j3 = document.getElementById('slider-j3');
if (j3) j3.value = joints.joint3.rotation.z.toFixed(2);
const v3 = document.getElementById('val-j3');
if (v3) v3.textContent = joints.joint3.rotation.z.toFixed(2);
const j4 = document.getElementById('slider-j4');
if (j4) j4.value = joints.joint4.rotation.z.toFixed(2);
const v4 = document.getElementById('val-j4');
if (v4) v4.textContent = joints.joint4.rotation.z.toFixed(2);
const j5 = document.getElementById('slider-j5');
if (j5) j5.value = joints.joint5.rotation.z.toFixed(2);
const v5 = document.getElementById('val-j5');
if (v5) v5.textContent = joints.joint5.rotation.z.toFixed(2);
const j6 = document.getElementById('slider-j6');
if (j6) j6.value = joints.joint6.rotation.z.toFixed(2);
const v6 = document.getElementById('val-j6');
if (v6) v6.textContent = joints.joint6.rotation.z.toFixed(2);
const j7 = document.getElementById('slider-j7');
if (j7) j7.value = joints.joint7.rotation.z.toFixed(2);
const v7 = document.getElementById('val-j7');
if (v7) v7.textContent = joints.joint7.rotation.z.toFixed(2);
const jg = document.getElementById('slider-jg');
if (jg) jg.value = joints.fingerJoint1.position.y.toFixed(3);
const vg = document.getElementById('val-jg');
if (vg) vg.textContent = joints.fingerJoint1.position.y.toFixed(3);
}
// Align eeDummy position to handJoint if not being dragged
if (eeDummy && joints.handJoint && (!transformControls || !transformControls.object || transformControls.object !== eeDummy)) {
const handWorldPos = new THREE.Vector3();
joints.handJoint.getWorldPosition(handWorldPos);
eeDummy.position.copy(handWorldPos);
}
renderer.render(scene, camera);
}
// Window resizing
window.addEventListener('resize', () => {
const width = canvas.clientWidth;
const height = canvas.clientHeight;
if (canvas.width !== width || canvas.height !== height) {
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
});
// ─── Three.js Scene Construction ────────────────────────────────────────────
function createTable(tableConfig) {
if (tableMesh) scene.remove(tableMesh);
const ext = tableConfig.half_extents;
const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2);
const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3));
const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 });
tableMesh = new THREE.Mesh(geo, mat);
tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]);
tableMesh.castShadow = true;
tableMesh.receiveShadow = true;
scene.add(tableMesh);
}
function createTray(trayConfig) {
if (trayMesh) scene.remove(trayMesh);
const ext = trayConfig.half_extents;
const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2);
const color = new THREE.Color().fromArray(trayConfig.color.slice(0, 3));
const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.7 });
trayMesh = new THREE.Mesh(geo, mat);
trayMesh.position.set(trayConfig.position[0], trayConfig.position[1], trayConfig.position[2] - ext[2]);
trayMesh.castShadow = true;
trayMesh.receiveShadow = true;
scene.add(trayMesh);
}
function createSlotHelpers(slots) {
slotHelpers.forEach(mesh => scene.remove(mesh));
slotHelpers.length = 0;
const geom = new THREE.RingGeometry(0.045, 0.05, 32);
const mat = new THREE.MeshBasicMaterial({ color: 0x3b82f6, side: THREE.DoubleSide, transparent: true, opacity: 0.45 });
Object.entries(slots).forEach(([name, pos]) => {
const ring = new THREE.Mesh(geom, mat);
ring.position.set(pos[0], pos[1], pos[2] + 0.001); // slightly above table
scene.add(ring);
slotHelpers.push(ring);
});
}
function initRobotStructure() {
if (robotGroup) scene.remove(robotGroup);
robotGroup = new THREE.Group();
scene.add(robotGroup);
joints.joint1 = new THREE.Group();
joints.joint2 = new THREE.Group();
joints.joint3 = new THREE.Group();
joints.joint4 = new THREE.Group();
joints.joint5 = new THREE.Group();
joints.joint6 = new THREE.Group();
joints.joint7 = new THREE.Group();
joints.joint8 = new THREE.Group();
joints.handJoint = new THREE.Group();
joints.fingerJoint1 = new THREE.Group();
joints.fingerJoint2 = new THREE.Group();
const link0 = new THREE.Group();
const link1 = new THREE.Group();
const link2 = new THREE.Group();
const link3 = new THREE.Group();
const link4 = new THREE.Group();
const link5 = new THREE.Group();
const link6 = new THREE.Group();
const link7 = new THREE.Group();
const link8 = new THREE.Group();
const hand = new THREE.Group();
const leftFinger = new THREE.Group();
const rightFinger = new THREE.Group();
robotGroup.add(link0);
link0.add(joints.joint1);
joints.joint1.position.set(0, 0, 0.333);
joints.joint1.add(link1);
link1.add(joints.joint2);
joints.joint2.position.set(0, 0, 0);
joints.joint2.rotation.set(-1.57079632679, 0, 0);
joints.joint2.add(link2);
link2.add(joints.joint3);
joints.joint3.position.set(0, -0.316, 0);
joints.joint3.rotation.set(1.57079632679, 0, 0);
joints.joint3.add(link3);
link3.add(joints.joint4);
joints.joint4.position.set(0.0825, 0, 0);
joints.joint4.rotation.set(1.57079632679, 0, 0);
joints.joint4.add(link4);
link4.add(joints.joint5);
joints.joint5.position.set(-0.0825, 0.384, 0);
joints.joint5.rotation.set(-1.57079632679, 0, 0);
joints.joint5.add(link5);
link5.add(joints.joint6);
joints.joint6.position.set(0, 0, 0);
joints.joint6.rotation.set(1.57079632679, 0, 0);
joints.joint6.add(link6);
link6.add(joints.joint7);
joints.joint7.position.set(0.088, 0, 0);
joints.joint7.rotation.set(1.57079632679, 0, 0);
joints.joint7.add(link7);
link7.add(joints.joint8);
joints.joint8.position.set(0, 0, 0.107);
joints.joint8.add(link8);
link8.add(joints.handJoint);
joints.handJoint.position.set(0, 0, 0);
joints.handJoint.rotation.set(0, 0, -0.785398163397);
joints.handJoint.add(hand);
hand.add(joints.fingerJoint1);
joints.fingerJoint1.position.set(0, 0, 0.0584);
joints.fingerJoint1.add(leftFinger);
hand.add(joints.fingerJoint2);
joints.fingerJoint2.position.set(0, 0, 0.0584);
joints.fingerJoint2.add(rightFinger);
const defaultPandaMaterial = new THREE.MeshStandardMaterial({
color: 0xdddddd,
roughness: 0.35,
metalness: 0.15
});
const loadModel = (parent, objPath, mtlPath = null, rotateRightFinger = false) => {
const applyRotation = (obj) => {
if (rotateRightFinger) {
obj.rotation.z = Math.PI;
}
parent.add(obj);
};
if (mtlPath) {
MTL_LOADER.load(mtlPath, (materials) => {
materials.preload();
const objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.load(objPath, (obj) => {
obj.traverse(child => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
applyRotation(obj);
});
});
} else {
const objLoader = new THREE.OBJLoader();
objLoader.load(objPath, (obj) => {
obj.traverse(child => {
if (child.isMesh) {
child.material = defaultPandaMaterial;
child.castShadow = true;
child.receiveShadow = true;
}
});
applyRotation(obj);
});
}
};
loadModel(link0, '/assets/panda/meshes/collision/link0.obj');
loadModel(link1, '/assets/panda/meshes/visual/link1.obj', '/assets/panda/meshes/visual/link1.mtl');
loadModel(link2, '/assets/panda/meshes/visual/link2.obj', '/assets/panda/meshes/visual/link2.mtl');
loadModel(link3, '/assets/panda/meshes/visual/link3.obj', '/assets/panda/meshes/visual/link3.mtl');
loadModel(link4, '/assets/panda/meshes/visual/link4.obj', '/assets/panda/meshes/visual/link4.mtl');
loadModel(link5, '/assets/panda/meshes/visual/link5.obj', '/assets/panda/meshes/visual/link5.mtl');
loadModel(link6, '/assets/panda/meshes/visual/link6.obj', '/assets/panda/meshes/visual/link6.mtl');
loadModel(link7, '/assets/panda/meshes/collision/link7.obj');
loadModel(hand, '/assets/panda/meshes/visual/hand.obj', '/assets/panda/meshes/visual/hand.mtl');
loadModel(leftFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl');
loadModel(rightFinger, '/assets/panda/meshes/visual/finger.obj', '/assets/panda/meshes/visual/finger.mtl', true);
// Create eeDummy sphere representing the end-effector target
if (eeDummy) scene.remove(eeDummy);
const dummyGeo = new THREE.SphereGeometry(0.035, 16, 16);
const dummyMat = new THREE.MeshStandardMaterial({
color: 0x3b82f6,
transparent: true,
opacity: 0.65,
roughness: 0.1,
metalness: 0.9
});
eeDummy = new THREE.Mesh(dummyGeo, dummyMat);
eeDummy.name = 'robot';
eeDummy.visible = false;
scene.add(eeDummy);
}
function loadYcbObjects(objectsConfig) {
// Clear old meshes/groups from scene
Object.values(ycbMeshes).forEach(group => scene.remove(group));
for (const key in ycbMeshes) delete ycbMeshes[key];
Object.entries(objectsConfig).forEach(([name, config]) => {
const folder = config.folder;
let objFile = "";
let mtlFile = "";
if (folder === "YcbBanana" || folder === "YcbTomatoSoupCan" || folder === "YcbCrackerBox" || folder === "YcbMustardBottle" || folder === "YcbPottedMeatCan") {
objFile = `/assets/ycb/${folder}/textured_simple_reoriented.obj`;
mtlFile = `/assets/ycb/${folder}/textured_simple_reoriented.mtl`;
} else if (folder === "YcbChipsCan") {
objFile = `/assets/ycb/${folder}/textured.obj`;
mtlFile = `/assets/ycb/${folder}/textured.mtl`;
}
if (!objFile) return;
// Create a parent group to represent the object's body link pose
const objectGroup = new THREE.Group();
objectGroup.name = name;
objectGroup.position.fromArray(config.initial_pos);
objectGroup.quaternion.fromArray(config.initial_ori);
scene.add(objectGroup);
ycbMeshes[name] = objectGroup;
// 1. Load Visual Mesh
MTL_LOADER.load(mtlFile, (materials) => {
materials.preload();
const objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.load(objFile, (visObj) => {
visObj.traverse(child => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
// Position, rotate and scale relative to parent group
if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos);
if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori);
if (config.vis_scale) visObj.scale.fromArray(config.vis_scale);
objectGroup.add(visObj);
});
});
// 2. Load Collision Mesh (Semi-transparent Blue)
const collObjFile = `/assets/ycb/${folder}/collision_vhacd.obj`;
const collLoader = new THREE.OBJLoader();
collLoader.load(collObjFile, (collObj) => {
collObj.traverse(child => {
if (child.isMesh) {
child.material = new THREE.MeshStandardMaterial({
color: 0x0000ff, // blue
transparent: true,
opacity: 0.5, // semi-transparent
roughness: 0.4,
metalness: 0.1
});
child.castShadow = true;
child.receiveShadow = true;
}
});
// Position, rotate and scale relative to parent group
if (config.coll_local_pos) collObj.position.fromArray(config.coll_local_pos);
if (config.coll_local_ori) collObj.quaternion.fromArray(config.coll_local_ori);
if (config.coll_scale) collObj.scale.fromArray(config.coll_scale);
objectGroup.add(collObj);
});
});
}
function updateSimulationState(jointsData, objectsData) {
if (jointsData && jointsData.length >= 11) {
targetJoints = jointsData;
}
if (objectsData) {
Object.entries(objectsData).forEach(([name, data]) => {
targetObjects[name] = {
pos: new THREE.Vector3().fromArray(data.pos),
ori: new THREE.Quaternion().fromArray(data.ori)
};
});
}
}
let reconnectTimeout = null;
function connectWebSocket() {
if (reconnectTimeout) {
clearTimeout(reconnectTimeout);
reconnectTimeout = null;
}
const guiToggle = document.getElementById('gui-toggle');
const showGui = guiToggle ? guiToggle.checked : false;
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=${showGui}`;
updateBadgeStatus('disconnected');
socket = new WebSocket(wsUrl);
socket.onopen = () => {
console.log("WebSocket connected.");
updateBadgeStatus('connected');
writeLog("Kết nối thành công đến Backend server.", "success");
};
socket.onmessage = (event) => {
const msg = JSON.parse(event.data);
handleSocketMessage(msg);
};
socket.onclose = () => {
console.log("WebSocket disconnected.");
updateBadgeStatus('disconnected');
writeLog("Mất kết nối đến Backend server. Đang thử kết nối lại...", "error");
reconnectTimeout = setTimeout(connectWebSocket, 3000);
};
socket.onerror = (err) => {
console.error("WebSocket Error: ", err);
};
}
function handleSocketMessage(msg) {
switch(msg.type) {
case 'init':
createTable(msg.table);
createTray(msg.tray);
createSlotHelpers(msg.slots);
loadYcbObjects(msg.objects);
initRobotStructure();
isInitialStateSynced = false; // Reset sync state for new simulations
break;
case 'state':
updateSimulationState(msg.joints, msg.objects);
break;
case 'log':
writeLog(msg.message, getLogClass(msg.message));
updatePipelineUI(msg.message);
break;
case 'plan':
displayPlan(msg.plan);
break;
case 'result':
showRearrangementScore(msg.score_display);
unlockInput();
// Add new run record to history log dynamically
const now = new Date();
const timeStr = now.toTimeString().split(' ')[0];
const scoreVal = msg.score_value !== undefined ? msg.score_value : 100;
const scoreClass = scoreVal >= 90 ? "high" : (scoreVal >= 60 ? "medium" : "low");
historyData.unshift({
time: timeStr,
operator: "Operator",
prompt: currentPrompt || "Câu lệnh nhanh",
score: scoreVal,
class: scoreClass
});
renderHistory();
// Speak speech feedback
speakFeedback(`Đã hoàn thành vận hành. Điểm rearrangement đạt ${scoreVal} điểm.`);
break;
}
}
// ─── UI Updates and Interactions ────────────────────────────────────────────
const badge = document.getElementById('connection-badge');
const logConsole = document.getElementById('log-console');
const planList = document.getElementById('plan-list');
const chatInput = document.getElementById('chat-input');
const submitBtn = document.getElementById('submit-btn');
const mockToggle = document.getElementById('mock-toggle');
const guiToggle = document.getElementById('gui-toggle');
const resetBtn = document.getElementById('reset-btn');
const scoreModal = document.getElementById('score-modal');
const scoreContent = document.getElementById('score-md-content');
const closeModalBtn = document.getElementById('close-modal-btn');
const ttsToggle = document.getElementById('tts-toggle');
const autocompletePanel = document.getElementById('autocomplete-panel');
// 1. Tab switching logic
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
btn.classList.add('active');
const tabId = btn.dataset.tab;
document.getElementById(`panel-${tabId}`).classList.add('active');
});
});
// 2. Scenario template click events
document.querySelectorAll('.scenario-card').forEach(card => {
card.addEventListener('click', () => {
const prompt = card.dataset.prompt;
chatInput.value = prompt;
chatInput.focus();
});
});
document.querySelectorAll('.preset-command-item').forEach(item => {
item.addEventListener('click', () => {
const prompt = item.dataset.prompt;
chatInput.value = prompt;
chatInput.focus();
});
});
// 3. Object Catalog Data & Render
const activeObjects = [
{ id: "banana", name: "Quả chuối (YCB)", mass: 0.066, friction: 0.8, trait: "Safe" },
{ id: "soup_can", name: "Lon súp cà chua", mass: 0.349, friction: 0.8, trait: "Safe" },
{ id: "chips_can", name: "Lon snack khoai tây", mass: 0.205, friction: 0.5, trait: "Safe" }
];
function renderObjectsTable() {
const objectsTableBody = document.getElementById('objects-table-body');
if (!objectsTableBody) return;
objectsTableBody.innerHTML = activeObjects.map(obj => `
<tr>
<td><strong>${obj.name}</strong><br><span style="font-size:0.7rem; opacity:0.6">${obj.id}</span></td>
<td>${obj.mass}</td>
<td>${obj.friction}</td>
<td><span class="tag-badge safe">${obj.trait}</span></td>
</tr>
`).join('');
}
// 4. History Logs Data & Render
const historyData = [
{ time: "14:20:15", operator: "Operator", prompt: "gắp lon snack đặt vào khay", score: 100, class: "high" },
{ time: "14:15:32", operator: "Operator", prompt: "dọn dẹp chướng ngại vật ở khay", score: 85, class: "medium" },
{ time: "14:02:10", operator: "Operator", prompt: "gắp quả chuối đặt vào Slot_2", score: 100, class: "high" }
];
function renderHistory() {
const historyList = document.getElementById('history-list');
if (!historyList) return;
historyList.innerHTML = historyData.map((item, index) => `
<div class="history-card">
<div class="history-card-header">
<span>🕒 ${item.time} - ${item.operator}</span>
<span class="history-score ${item.class}">${item.score}/100</span>
</div>
<p class="history-card-prompt">"${item.prompt}"</p>
<div class="history-card-footer">
<span style="font-size:0.7rem; opacity:0.7">API Cost: ~$0.002</span>
<div class="history-actions">
<button class="history-action-btn" onclick="runHistoryPrompt(${index})">
<svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg> Chạy lại
</button>
</div>
</div>
</div>
`).join('');
}
window.runHistoryPrompt = function(index) {
const item = historyData[index];
if (item) {
chatInput.value = item.prompt;
chatInput.focus();
document.getElementById('chat-form').dispatchEvent(new Event('submit'));
}
};
// 5. Speech Synthesis (Text-to-Speech)
function speakFeedback(text) {
if (!ttsToggle || !ttsToggle.checked) return;
// Determine language based on text content (Vietnamese by default, English if it contains mostly technical terms)
let lang = 'vi';
const textLower = text.toLowerCase();
if (textLower.includes('evaluation') || textLower.includes('score') || textLower.includes('report') || textLower.includes('step') || textLower.includes('verification')) {
lang = 'en';
}
// Call Google Translate TTS (free API) for high-quality English & Vietnamese voices
const encodedText = encodeURIComponent(text);
const ttsUrl = `https://translate.google.com/translate_tts?ie=UTF-8&tl=${lang}&client=tw-ob&q=${encodedText}`;
const audio = new Audio(ttsUrl);
audio.play().catch(err => {
console.warn("Google Translate TTS failed, falling back to local speech synthesis:", err);
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = lang === 'vi' ? 'vi-VN' : 'en-US';
utterance.rate = 1.0;
utterance.pitch = 1.0;
const voices = window.speechSynthesis.getVoices();
const matchingVoice = voices.find(voice => voice.lang.includes(lang));
if (matchingVoice) utterance.voice = matchingVoice;
window.speechSynthesis.speak(utterance);
}
});
}
// 6. Voice Recognition (Speech-to-Text)
const micBtn = document.getElementById('mic-btn');
let recognition = null;
let isRecording = false;
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
recognition = new SpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = 'vi-VN';
recognition.onstart = () => {
isRecording = true;
micBtn.classList.add('recording');
writeLog("Đang nghe giọng nói của bạn... Hãy nói đi.", "info");
speakFeedback("Tôi đang nghe.");
};
recognition.onresult = (event) => {
const resultText = event.results[0][0].transcript;
chatInput.value = resultText;
writeLog(`Nhận dạng giọng nói: "${resultText}"`, "success");
speakFeedback(`Đã nhận diện: ${resultText}`);
};
recognition.onerror = (event) => {
console.error("Speech Recognition Error: ", event.error);
writeLog("Nhận diện giọng nói gặp lỗi: " + event.error, "warn");
isRecording = false;
micBtn.classList.remove('recording');
};
recognition.onend = () => {
isRecording = false;
micBtn.classList.remove('recording');
};
micBtn.addEventListener('click', () => {
if (isRecording) {
recognition.stop();
} else {
recognition.start();
}
});
} else {
micBtn.style.display = 'none';
}
// 7. Smart Autocomplete suggestions
const autocompleteVocabulary = [
"gắp quả chuối đặt vào khay",
"gắp quả chuối đặt vào Slot_2",
"gắp quả chuối đặt vào Slot_4",
"gắp lon súp cà chua đặt vào khay",
"gắp lon súp cà chua đặt vào Slot_3",
"gắp lon snack đặt vào khay",
"gắp lon snack đặt vào Slot_6",
"dọn dẹp chướng ngại vật trên bàn",
"sắp xếp lại bàn học tập",
"cất dọn đồ vật nguy hiểm"
];
if (chatInput && autocompletePanel) {
chatInput.addEventListener('input', (e) => {
const query = e.target.value.toLowerCase().trim();
if (!query || query.length < 2) {
autocompletePanel.classList.add('hidden');
return;
}
const matches = autocompleteVocabulary.filter(item => item.includes(query)).slice(0, 4);
if (matches.length === 0) {
autocompletePanel.classList.add('hidden');
return;
}
autocompletePanel.innerHTML = matches.map(match => `
<div class="autocomplete-item" data-value="${match}">${match}</div>
`).join('');
autocompletePanel.classList.remove('hidden');
document.querySelectorAll('.autocomplete-item').forEach(item => {
item.addEventListener('click', () => {
chatInput.value = item.dataset.value;
autocompletePanel.classList.add('hidden');
chatInput.focus();
});
});
});
document.addEventListener('click', (e) => {
if (!e.target.closest('#chat-form')) {
autocompletePanel.classList.add('hidden');
}
});
}
// 8. Log and Pipeline functions
function updateBadgeStatus(status) {
if (status === 'connected') {
badge.className = 'badge online';
badge.textContent = 'Connected';
} else {
badge.className = 'badge offline';
badge.textContent = 'Disconnected';
}
}
function writeLog(text, className = 'info') {
const entry = document.createElement('div');
entry.className = `log-entry ${className}`;
entry.textContent = `> ${text}`;
const placeholder = logConsole.querySelector('.placeholder-text');
if (placeholder) placeholder.remove();
logConsole.appendChild(entry);
logConsole.scrollTop = logConsole.scrollHeight;
}
function getLogClass(message) {
if (message.includes('✅')) return 'success';
if (message.includes('❌')) return 'error';
if (message.includes('⚠️')) return 'warn';
if (message.includes('🚀') || message.includes('⏳')) return 'info';
return '';
}
function updatePipelineUI(message) {
const stepLlm = document.getElementById('step-llm');
const stepVal = document.getElementById('step-val');
const stepExec = document.getElementById('step-exec');
const stepScore = document.getElementById('step-score');
if (message.includes('[1/5]')) {
setActiveStep(stepLlm);
} else if (message.includes('✅ [1]')) {
setCompletedStep(stepLlm);
} else if (message.includes('❌ [1]')) {
setErrorStep(stepLlm);
unlockInput();
speakFeedback("Lập kế hoạch thất bại. Vui lòng kiểm tra lại câu lệnh.");
}
else if (message.includes('[2/5]')) {
setActiveStep(stepVal);
} else if (message.includes('✅ [2]')) {
setCompletedStep(stepVal);
} else if (message.includes('❌ [2]') || message.includes('⚠️ [2]')) {
if (message.includes('❌')) {
setErrorStep(stepVal);
unlockInput();
speakFeedback("Kế hoạch không hợp lệ. Vi phạm các quy tắc an toàn.");
} else {
stepVal.className = 'status-step active warn';
}
}
else if (message.includes('[3/5]')) {
setActiveStep(stepExec);
} else if (message.includes('Thực thi thành công')) {
setCompletedStep(stepExec);
} else if (message.includes('Thực thi kết thúc có bước lỗi')) {
setErrorStep(stepExec);
speakFeedback("Quá trình thực thi gặp sự cố va chạm.");
}
else if (message.includes('[5/5]')) {
setActiveStep(stepScore);
} else if (message.includes('Rearrangement Evaluation Report') || message.includes('result')) {
setCompletedStep(stepScore);
unlockInput();
}
}
function setActiveStep(el) {
el.className = 'status-step active';
}
function setCompletedStep(el) {
el.className = 'status-step completed';
}
function setErrorStep(el) {
el.className = 'status-step error';
}
function displayPlan(plan) {
planList.innerHTML = '';
plan.forEach(step => {
const item = document.createElement('div');
item.className = 'plan-item';
item.id = `plan-step-${step.step}`;
const argsStr = Object.entries(step.args)
.map(([k, v]) => `${k}:${v}`)
.join(', ');
item.innerHTML = `
<span><b>Step ${step.step}:</b> ${step.skill}(${step.object})</span>
<span style="font-size: 0.75rem; opacity: 0.8;">${argsStr}</span>
`;
planList.appendChild(item);
});
}
function showRearrangementScore(markdownText) {
let html = markdownText
.replace(/### (.*)/g, '<h3>$1</h3>')
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/- (.*)/g, '<li>$1</li>')
.replace(/\n\n/g, '<br>')
.replace(/✅/g, '<span style="color:#10b981">✅</span>')
.replace(/⚠️/g, '<span style="color:#f59e0b">⚠️</span>')
.replace(/❌/g, '<span style="color:#ef4444">❌</span>');
scoreContent.innerHTML = html;
scoreModal.classList.remove('hidden');
}
function lockInput() {
chatInput.disabled = true;
submitBtn.disabled = true;
resetBtn.disabled = true;
mockToggle.disabled = true;
if (guiToggle) guiToggle.disabled = true;
}
document.getElementById('chat-form').addEventListener('submit', (e) => {
e.preventDefault();
const prompt = chatInput.value.trim();
if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return;
currentPrompt = prompt;
chatInput.value = '';
logConsole.innerHTML = '';
planList.innerHTML = '<p class="placeholder-text">Đang tải kế hoạch...</p>';
['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => {
document.getElementById(id).className = 'status-step';
});
writeLog(`Gửi yêu cầu: "${prompt}"`, "info");
lockInput();
speakFeedback("Bắt đầu xử lý câu lệnh điều khiển của bạn.");
socket.send(JSON.stringify({
type: 'run',
prompt: prompt,
mock: mockToggle.checked
}));
});
function unlockInput() {
chatInput.disabled = false;
submitBtn.disabled = false;
resetBtn.disabled = false;
mockToggle.disabled = false;
if (guiToggle) guiToggle.disabled = false;
}
resetBtn.addEventListener('click', () => {
if (!socket || socket.readyState !== WebSocket.OPEN) return;
logConsole.innerHTML = '';
planList.innerHTML = '<p class="placeholder-text">Chưa có kế hoạch...</p>';
['step-llm', 'step-val', 'step-exec', 'step-score'].forEach(id => {
document.getElementById(id).className = 'status-step';
});
socket.send(JSON.stringify({
type: 'reset'
}));
});
closeModalBtn.addEventListener('click', () => {
scoreModal.classList.add('hidden');
unlockInput();
});
if (guiToggle) {
guiToggle.addEventListener('change', () => {
writeLog("Thay đổi thiết lập hiển thị cửa sổ PyBullet. Đang kết nối lại...", "info");
if (socket) {
socket.onclose = null;
socket.close();
}
connectWebSocket();
});
}
// 10. Manual joint controls sending
function sendManualJoints() {
if (!socket || socket.readyState !== WebSocket.OPEN) return;
const q0 = parseFloat(document.getElementById('slider-j1').value);
const q1 = parseFloat(document.getElementById('slider-j2').value);
const q2 = parseFloat(document.getElementById('slider-j3').value);
const q3 = parseFloat(document.getElementById('slider-j4').value);
const q4 = parseFloat(document.getElementById('slider-j5').value);
const q5 = parseFloat(document.getElementById('slider-j6').value);
const q6 = parseFloat(document.getElementById('slider-j7').value);
const qg = parseFloat(document.getElementById('slider-jg').value);
socket.send(JSON.stringify({
type: "update_joints",
joints: [q0, q1, q2, q3, q4, q5, q6, 0.0, 0.0, qg, qg]
}));
}
const slidersList = ['j1', 'j2', 'j3', 'j4', 'j5', 'j6', 'j7', 'jg'];
slidersList.forEach(id => {
const slider = document.getElementById(`slider-${id}`);
const label = document.getElementById(`val-${id}`);
if (slider && label) {
slider.addEventListener('input', (e) => {
const val = parseFloat(e.target.value);
label.textContent = id === 'jg' ? val.toFixed(3) : val.toFixed(2);
sendManualJoints();
});
}
});
// 11. Interactive Drag and Drop for YCB objects and Robot End Effector using THREE.TransformControls
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// State variables for Hover Highlight
const originalEmissives = new Map();
let hoveredGroup = null;
canvas.addEventListener('mousedown', onMouseDown);
canvas.addEventListener('mousemove', onMouseMove);
// Helper to determine if an intersected object belongs to a draggable group (YCB or Robot)
function findDraggableTarget(hitObject) {
let curr = hitObject;
while (curr && curr !== scene) {
if (curr === robotGroup) {
return { type: 'robot', group: robotGroup, name: 'robot' };
}
const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr);
if (ycbEntry) {
return { type: 'ycb', group: ycbEntry[1], name: ycbEntry[0] };
}
curr = curr.parent;
}
return null;
}
// Helper to set/restore emissive highlight glow on all child meshes of a group
function highlightGroup(group, highlightColor = null) {
if (!group) return;
group.traverse(child => {
if (child.isMesh) {
if (highlightColor) {
if (!originalEmissives.has(child.uuid)) {
if (child.material && child.material.emissive) {
originalEmissives.set(child.uuid, {
color: child.material.emissive.clone(),
material: child.material
});
}
}
if (child.material && child.material.emissive) {
child.material.emissive.copy(highlightColor);
}
} else {
const orig = originalEmissives.get(child.uuid);
if (orig && orig.material && orig.material.emissive) {
orig.material.emissive.copy(orig.color);
}
}
}
});
}
function onMouseDown(event) {
if (event.button !== 0 || chatInput.disabled) return;
// Ignore clicks if we are already dragging the transform controls handles
if (transformControls && transformControls.dragging) return;
const rect = canvas.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObjects(scene.children, true);
let target = null;
// Check if the click hit the Gizmo itself
for (let i = 0; i < hits.length; i++) {
// Exclude the gizmo meshes themselves
let isGizmo = false;
let p = hits[i].object;
while (p) {
if (p === transformControls) {
isGizmo = true;
break;
// Click is on the gizmo handles; let TransformControls handle it
return;
}
p = p.parent;
}
if (isGizmo) continue;
}
let target = null;
for (let i = 0; i < hits.length; i++) {
const found = findDraggableTarget(hits[i].object);
if (found) {
target = found;
break;
}
}
if (target) {
if (target.type === 'robot') {
if (eeDummy && joints.handJoint) {
const handWorldPos = new THREE.Vector3();
joints.handJoint.getWorldPosition(handWorldPos);
eeDummy.position.copy(handWorldPos);
eeDummy.visible = true;
transformControls.attach(eeDummy);
writeLog("Đã kích hoạt Gizmo điều khiển cánh tay robot. Kéo các trục mũi tên để dịch chuyển.", "info");
}
} else {
if (transformControls.object === eeDummy) {
eeDummy.visible = false;
}
transformControls.attach(target.group);
writeLog(`Đã chọn vật thể: ${target.name}. Kéo các trục mũi tên để dịch chuyển.`, "info");
}
} else {
if (transformControls && !transformControls.dragging) {
if (transformControls.object === eeDummy) {
eeDummy.visible = false;
}
transformControls.detach();
}
}
}
function onMouseMove(event) {
if (transformControls && transformControls.dragging) {
return;
}
const rect = canvas.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObjects(scene.children, true);
let hoverTarget = null;
// Check if the mouse is hovering over the Gizmo itself
for (let i = 0; i < hits.length; i++) {
let isGizmo = false;
let p = hits[i].object;
while (p) {
if (p === transformControls) {
isGizmo = true;
break;
// Let Gizmo handle cursors and mouse interaction
return;
}
p = p.parent;
}
if (isGizmo) continue;
}
let hoverTarget = null;
for (let i = 0; i < hits.length; i++) {
const found = findDraggableTarget(hits[i].object);
if (found) {
hoverTarget = found;
break;
}
}
if (hoverTarget) {
if (hoveredGroup !== hoverTarget.group) {
if (hoveredGroup) {
highlightGroup(hoveredGroup, null);
}
originalEmissives.clear();
hoveredGroup = hoverTarget.group;
const glowColor = new THREE.Color(hoverTarget.type === 'robot' ? '#1e40af' : '#2563eb');
highlightGroup(hoveredGroup, glowColor);
canvas.style.cursor = 'pointer';
}
} else {
if (hoveredGroup) {
highlightGroup(hoveredGroup, null);
hoveredGroup = null;
originalEmissives.clear();
canvas.style.cursor = '';
}
}
}
// 12. Initial runs
initVisualizer();
connectWebSocket();
renderObjectsTable();
renderHistory();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LLM-Panda Web-Embedded PyBullet Simulation</title>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Space+Grotesk:wght@400;500;700&display=swap" rel="stylesheet">
<!-- Three.js libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/MTLLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/OBJLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<!-- Main Style -->
<link rel="stylesheet" href="/static/index.css">
</head>
<body>
<!-- Real-Time PyBullet Streaming Viewport -->
<div id="viewport-container">
<canvas id="pybullet-viewport"></canvas>
</div>
<!-- Status & Logs Sidebar -->
<div class="sidebar glass">
<div class="sidebar-header">
<h2>🤖 LLM-Panda</h2>
<span class="badge offline" id="connection-badge">Disconnected</span>
</div>
<div class="sidebar-section">
<h3>📊 Pipeline Status</h3>
<div class="status-steps">
<div class="status-step" id="step-llm">
<span class="dot"></span>
<span class="step-label">1. LLM Planning</span>
</div>
<div class="status-step" id="step-val">
<span class="dot"></span>
<span class="step-label">2. Rule Validation</span>
</div>
<div class="status-step" id="step-exec">
<span class="dot"></span>
<span class="step-label">3. PyBullet Execution</span>
</div>
<div class="status-step" id="step-score">
<span class="dot"></span>
<span class="step-label">4. Scoring & Feedback</span>
</div>
</div>
</div>
<div class="sidebar-section">
<h3>📋 Task Plan</h3>
<div id="plan-list" class="plan-list">
<p class="placeholder-text">Chưa có kế hoạch...</p>
</div>
</div>
<div class="sidebar-section flex-grow">
<h3>📺 Execution Log</h3>
<div id="log-console" class="log-console">
<p class="placeholder-text">Đang đợi yêu cầu...</p>
</div>
</div>
</div>
<!-- Floating Chat Window (Glassmorphic Overlay) -->
<div class="chat-container glass">
<form id="chat-form">
<input
type="text"
id="chat-input"
placeholder="Nhập yêu cầu dọn bàn... (e.g. 'Sắp xếp bàn học tập', 'Dọn đồ nguy hiểm')"
autocomplete="off"
required
>
<button type="submit" id="submit-btn">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M2,21L23,12L2,3V10L17,12L2,14V21Z"/>
</svg>
</button>
</form>
<div class="chat-options">
<label class="toggle-switch">
<input type="checkbox" id="mock-toggle" checked>
<span class="slider"></span>
<span class="toggle-label">Use Mock Preset Plans (Fast & Offline)</span>
</label>
<label class="toggle-switch">
<input type="checkbox" id="gui-toggle" checked>
<span class="slider"></span>
<span class="toggle-label">Hiển thị cửa sổ PyBullet</span>
</label>
<button id="reset-btn" class="text-btn">🔄 Reset Scene</button>
</div>
</div>
<!-- Top Instructions & Preset Badges Overlay -->
<div class="header-overlay">
<h1>Web-Embedded PyBullet Interface</h1>
<p>Tương tác trực tiếp: <b>Kéo chuột trái</b> để xoay camera, <b>Kéo chuột phải</b> để di chuyển camera, <b>Cuộn chuột</b> để Zoom</p>
<div class="preset-badges">
<button class="preset-badge" data-prompt="Tôi cần chuẩn bị bàn để sửa một thiết bị điện tử nhỏ. Hãy dọn các vật chứa nước ra xa, cất đồ nguy hiểm vào khu an toàn, đặt công cụ gần trung tâm, và dọn khay đựng dụng cụ trước nếu bị chặn. Không cần chạm vào đồ dễ vỡ trừ khi thật sự cần thiết.">🔌 Sửa đồ điện tử</button>
<button class="preset-badge" data-prompt="Hãy dọn bàn này để một đứa trẻ có thể chơi an toàn. Cất ngay tất cả dao, pin tiểu, và đồ thủy tinh dễ vỡ đi. Chỉ để lại khối đồ chơi xếp hình ở giữa. Bỏ rác vào thùng rác.">🧸 Trẻ em chơi</button>
<button class="preset-badge" data-prompt="Sắp xếp lại bàn để tôi có thể ngồi học bài tập trung. Để sách/vở gần trung tâm, dọn đồ chơi gây mất tập trung đi, cốc nước để ở góc xa nhưng vẫn giữ lại, bỏ rác vào thùng rác.">📚 Bàn học tập</button>
</div>
</div>
<!-- Final Score Display Overlay Modal -->
<div id="score-modal" class="modal-overlay hidden">
<div class="modal-content glass">
<h2>🏆 Rearrangement Evaluation Report</h2>
<div id="score-md-content" class="score-md-content">
<!-- Markdown Content rendered dynamically -->
</div>
<button id="close-modal-btn" class="primary-btn">Đóng</button>
</div>
</div>
<!-- Application Script -->
<script src="/static/app.js"></script>
</body>
</html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LLM-Panda Web-Embedded PyBullet Simulation</title>
<!-- Google Fonts - Outfit Font Only -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<!-- Three.js libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/MTLLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/OBJLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/TransformControls.js"></script>
<!-- Main Style -->
<link rel="stylesheet" href="/static/index.css">
</head>
<body>
<!-- Real-Time PyBullet Streaming Viewport -->
<div id="viewport-container">
<canvas id="pybullet-viewport"></canvas>
</div>
<!-- Status & Logs Sidebar -->
<div class="sidebar glass">
<div class="sidebar-header">
<div class="brand">
<!-- Bot SVG Icon -->
<svg class="brand-icon" viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="11" width="18" height="10" rx="2"></rect>
<circle cx="12" cy="5" r="2"></circle>
<path d="M12 7v4M8 8h8M2 14h1M21 14h1"></path>
</svg>
<h2>LLM-Panda</h2>
</div>
<span class="badge offline" id="connection-badge">Disconnected</span>
</div>
<!-- Sidebar Navigation Tabs -->
<div class="sidebar-tabs">
<button class="tab-btn active" data-tab="operations" title="Vận hành">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="8" y1="6" x2="21" y2="6"></line>
<line x1="8" y1="12" x2="21" y2="12"></line>
<line x1="8" y1="18" x2="21" y2="18"></line>
<line x1="3" y1="6" x2="3.01" y2="6"></line>
<line x1="3" y1="12" x2="3.01" y2="12"></line>
<line x1="3" y1="18" x2="3.01" y2="18"></line>
</svg>
</button>
<button class="tab-btn" data-tab="scenarios" title="Kịch bản">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
<polyline points="2 17 12 22 22 17"></polyline>
<polyline points="2 12 12 17 22 12"></polyline>
</svg>
</button>
<button class="tab-btn" data-tab="objects" title="Vật thể">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path>
<polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline>
<line x1="12" y1="22.08" x2="12" y2="12"></line>
</svg>
</button>
<button class="tab-btn" data-tab="history" title="Lịch sử">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<polyline points="12 6 12 12 16 14"></polyline>
</svg>
</button>
<button class="tab-btn" data-tab="analytics" title="Báo cáo">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="20" x2="18" y2="10"></line>
<line x1="12" y1="20" x2="12" y2="4"></line>
<line x1="6" y1="20" x2="6" y2="14"></line>
</svg>
</button>
<button class="tab-btn" data-tab="system" title="Hệ thống">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="4" y1="21" x2="4" y2="14"></line>
<line x1="4" y1="10" x2="4" y2="3"></line>
<line x1="12" y1="21" x2="12" y2="12"></line>
<line x1="12" y1="8" x2="12" y2="3"></line>
<line x1="20" y1="21" x2="20" y2="16"></line>
<line x1="20" y1="12" x2="20" y2="3"></line>
<line x1="1" y1="14" x2="7" y2="14"></line>
<line x1="9" y1="8" x2="15" y2="8"></line>
<line x1="17" y1="16" x2="23" y2="16"></line>
</svg>
</button>
</div>
<!-- 1. OPERATIONS TAB PANEL -->
<div class="tab-panel active" id="panel-operations">
<div class="sidebar-section">
<h3>Pipeline Status</h3>
<div class="status-steps">
<div class="status-step" id="step-llm">
<span class="dot"></span>
<span class="step-label">1. LLM Planning</span>
</div>
<div class="status-step" id="step-val">
<span class="dot"></span>
<span class="step-label">2. Rule Validation</span>
</div>
<div class="status-step" id="step-exec">
<span class="dot"></span>
<span class="step-label">3. PyBullet Execution</span>
</div>
<div class="status-step" id="step-score">
<span class="dot"></span>
<span class="step-label">4. Scoring & Feedback</span>
</div>
</div>
</div>
<div class="sidebar-section">
<h3>Task Plan</h3>
<div id="plan-list" class="plan-list">
<p class="placeholder-text">Chưa có kế hoạch...</p>
</div>
</div>
<div class="sidebar-section flex-grow">
<h3>Execution Log</h3>
<div id="log-console" class="log-console">
<p class="placeholder-text">Đang đợi yêu cầu...</p>
</div>
</div>
</div>
<!-- 2. SCENARIOS TAB PANEL -->
<div class="tab-panel" id="panel-scenarios">
<div class="sidebar-section">
<h3>Mẫu thiết lập bàn học</h3>
<div class="scenarios-grid">
<div class="scenario-card" data-prompt="Tôi cần chuẩn bị bàn để sửa một thiết bị điện tử nhỏ. Hãy dọn các vật chứa nước ra xa, cất đồ nguy hiểm vào khu an toàn, đặt công cụ gần trung tâm, và dọn khay đựng dụng cụ trước nếu bị chặn. Không cần chạm vào đồ dễ vỡ trừ khi thật sự cần thiết.">
<div class="scenario-icon">
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect>
<path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path>
<line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line>
</svg>
</div>
<h4>Sửa đồ điện tử</h4>
</div>
<div class="scenario-card" data-prompt="Hãy dọn bàn này để một đứa trẻ có thể chơi an toàn. Cất ngay tất cả dao, pin tiểu, và đồ thủy tinh dễ vỡ đi. Chỉ để lại khối đồ chơi xếp hình ở giữa. Bỏ rác vào thùng rác.">
<div class="scenario-icon">
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path>
</svg>
</div>
<h4>Trẻ em chơi an toàn</h4>
</div>
<div class="scenario-card" data-prompt="Sắp xếp lại bàn để tôi có thể ngồi học bài tập trung. Để sách/vở gần trung tâm, dọn đồ chơi gây mất tập trung đi, cốc nước để ở góc xa nhưng vẫn giữ lại, bỏ rác vào thùng rác.">
<div class="scenario-icon">
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path>
<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path>
</svg>
</div>
<h4>Bàn học tập trung</h4>
</div>
</div>
</div>
<div class="sidebar-section">
<h3>Câu lệnh vận hành nhanh</h3>
<div class="preset-commands-list">
<button class="preset-command-item" data-prompt="gắp quả chuối đặt vào khay">Gắp quả chuối vào khay</button>
<button class="preset-command-item" data-prompt="gắp lon súp cà chua đặt vào Slot_2">Gắp lon súp vào Slot 2</button>
<button class="preset-command-item" data-prompt="dọn sạch khay và chuyển lon khoai tây vào Slot_6">Dọn khay, chuyển snack vào Slot 6</button>
</div>
</div>
</div>
<!-- 3. OBJECTS TAB PANEL -->
<div class="tab-panel" id="panel-objects">
<div class="sidebar-section">
<h3>Thư viện vật thể hoạt động</h3>
<div class="table-container">
<table class="objects-table">
<thead>
<tr>
<th>Vật thể</th>
<th>Nặng (kg)</th>
<th>Ma sát</th>
<th>Đặc tính</th>
</tr>
</thead>
<tbody id="objects-table-body">
<!-- Populated dynamically via JS -->
</tbody>
</table>
</div>
</div>
</div>
<!-- 4. HISTORY TAB PANEL -->
<div class="tab-panel" id="panel-history">
<div class="sidebar-section">
<h3>Nhật ký hoạt động hệ thống</h3>
<div id="history-list" class="history-list">
<!-- Populated dynamically via JS -->
</div>
</div>
</div>
<!-- 5. ANALYTICS TAB PANEL -->
<div class="tab-panel" id="panel-analytics">
<div class="sidebar-section">
<h3>Chỉ số hiệu suất (KPIs)</h3>
<div class="kpi-grid">
<div class="kpi-card">
<span class="kpi-value">94%</span>
<span class="kpi-label">Thành công</span>
</div>
<div class="kpi-card">
<span class="kpi-value">88/100</span>
<span class="kpi-label">Điểm TB</span>
</div>
<div class="kpi-card">
<span class="kpi-value">22.5s</span>
<span class="kpi-label">Thời gian TB</span>
</div>
</div>
</div>
<div class="sidebar-section">
<h3>Phân bố nguyên nhân lỗi vận hành</h3>
<div class="analytics-chart">
<div class="chart-bar-group">
<div class="chart-label-row">
<span class="chart-label">Ngoài tầm với robot (IK)</span>
<span class="chart-value">50%</span>
</div>
<div class="chart-track">
<div class="chart-bar" style="width: 50%; background: #3b82f6;"></div>
</div>
</div>
<div class="chart-bar-group">
<div class="chart-label-row">
<span class="chart-label">Vật bị trượt khỏi tay kẹp</span>
<span class="chart-value">30%</span>
</div>
<div class="chart-track">
<div class="chart-bar" style="width: 30%; background: #ef4444;"></div>
</div>
</div>
<div class="chart-bar-group">
<div class="chart-label-row">
<span class="chart-label">LLM lập kế hoạch sai</span>
<span class="chart-value">20%</span>
</div>
<div class="chart-track">
<div class="chart-bar" style="width: 20%; background: #f59e0b;"></div>
</div>
</div>
</div>
</div>
</div>
<!-- 6. SYSTEM SETTINGS TAB PANEL -->
<div class="tab-panel" id="panel-system">
<div class="sidebar-section">
<h3>Phân vùng làm việc (Workspace)</h3>
<div class="form-group">
<label class="form-label" for="workspace-select">Chọn Workspace vận hành</label>
<div class="select-wrapper">
<select id="workspace-select" class="glass-select">
<option value="workspace_a" selected>Project AI20K-161 - Franka Panda A</option>
<option value="workspace_b">Project AI20K-161 - Franka Panda B</option>
</select>
</div>
</div>
</div>
<div class="sidebar-section">
<h3>Cấu hình âm thanh phản hồi</h3>
<div class="form-group">
<label class="toggle-switch">
<input type="checkbox" id="tts-toggle" checked>
<span class="slider"></span>
<span class="toggle-label">Bật phản hồi giọng nói (TTS)</span>
</label>
</div>
</div>
<div class="sidebar-section">
<h3>Điều khiển Robot thủ công</h3>
<div class="manual-controls">
<div class="slider-group">
<label>Khớp 1: <span id="val-j1">0.00</span></label>
<input type="range" id="slider-j1" min="-2.89" max="2.89" step="0.01" value="0.00">
</div>
<div class="slider-group">
<label>Khớp 2: <span id="val-j2">0.00</span></label>
<input type="range" id="slider-j2" min="-1.76" max="1.76" step="0.01" value="0.00">
</div>
<div class="slider-group">
<label>Khớp 3: <span id="val-j3">0.00</span></label>
<input type="range" id="slider-j3" min="-2.89" max="2.89" step="0.01" value="0.00">
</div>
<div class="slider-group">
<label>Khớp 4: <span id="val-j4">-1.57</span></label>
<input type="range" id="slider-j4" min="-3.07" max="-0.07" step="0.01" value="-1.57">
</div>
<div class="slider-group">
<label>Khớp 5: <span id="val-j5">0.00</span></label>
<input type="range" id="slider-j5" min="-2.89" max="2.89" step="0.01" value="0.00">
</div>
<div class="slider-group">
<label>Khớp 6: <span id="val-j6">1.57</span></label>
<input type="range" id="slider-j6" min="-0.01" max="3.75" step="0.01" value="1.57">
</div>
<div class="slider-group">
<label>Khớp 7: <span id="val-j7">0.78</span></label>
<input type="range" id="slider-j7" min="-2.89" max="2.89" step="0.01" value="0.78">
</div>
<div class="slider-group">
<label>Kẹp ngón (m): <span id="val-jg">0.040</span></label>
<input type="range" id="slider-jg" min="0.0" max="0.04" step="0.001" value="0.040">
</div>
</div>
</div>
</div>
</div>
<!-- Floating Chat Window (Glassmorphic Overlay) -->
<div class="chat-container glass">
<form id="chat-form">
<!-- Autocomplete Suggestions Panel -->
<div id="autocomplete-panel" class="autocomplete-panel hidden"></div>
<button type="button" id="mic-btn" class="chat-action-btn" title="Ghi âm giọng nói">
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"></path>
<path d="M19 10v1a7 7 0 0 1-14 0v-1M12 19v4M8 23h8"></path>
</svg>
</button>
<input
type="text"
id="chat-input"
placeholder="Nhập yêu cầu dọn bàn... (e.g. 'Sắp xếp bàn học tập', 'Dọn đồ nguy hiểm')"
autocomplete="off"
required
>
<button type="submit" id="submit-btn" class="chat-action-btn" title="Gửi yêu cầu">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="22" y1="2" x2="11" y2="13"></line>
<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
</svg>
</button>
</form>
<div class="chat-options">
<label class="toggle-switch">
<input type="checkbox" id="mock-toggle" checked>
<span class="slider"></span>
<span class="toggle-label">Sử dụng kế hoạch Presets (Ngoại tuyến)</span>
</label>
<label class="toggle-switch">
<input type="checkbox" id="gui-toggle" checked>
<span class="slider"></span>
<span class="toggle-label">Hiển thị cửa sổ PyBullet</span>
</label>
<button id="reset-btn" class="text-btn">
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 4px;">
<polyline points="23 4 23 10 17 10"></polyline>
<polyline points="1 20 1 14 7 14"></polyline>
<path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path>
</svg>Reset Scene
</button>
</div>
</div>
<!-- Top Instructions Overlay -->
<div class="header-overlay">
<h1>Mô phỏng điều khiển Franka Panda</h1>
<p>Thao tác: <b>Kéo chuột trái</b> để xoay camera, <b>Kéo chuột phải</b> để di chuyển camera, <b>Cuộn chuột</b> để Zoom</p>
</div>
<!-- Final Score Display Overlay Modal -->
<div id="score-modal" class="modal-overlay hidden">
<div class="modal-content glass">
<!-- Trophy SVG Icon -->
<svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="#f59e0b" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin: 0 auto;">
<path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"></path>
<path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"></path>
<path d="M4 22h16"></path>
<path d="M10 14.66V17c0 .55-.45 1-1 1H4v2h16v-2h-5c-.55 0-1-.45-1-1v-2.34"></path>
<path d="M12 2a6 6 0 0 1 6 6v5a6 6 0 0 1-6 6 6 6 0 0 1-6-6V8a6 6 0 0 1 6-6z"></path>
</svg>
<h2>🏆 Rearrangement Evaluation Report</h2>
<div id="score-md-content" class="score-md-content">
<!-- Markdown Content rendered dynamically -->
</div>
<button id="close-modal-btn" class="primary-btn">Đóng</button>
</div>
</div>
<!-- Application Script -->
<script src="/static/app.js"></script>
</body>
</html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569import sys
import os
import json
import asyncio
import math
import time
import threading
from typing import Optional
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import uvicorn
import cv2
import numpy as np
import pybullet as pb
# Ensure project source root is in path
PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if PROJECT_SRC not in sys.path:
sys.path.insert(0, PROJECT_SRC)
from dotenv import load_dotenv
load_dotenv()
from main import PandaSimulation, _YCB_CATALOG
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
from llm_panda.plan_verifier import PlanVerifier
from llm_panda import config
import pybullet_data
from pybullet_object_models import ycb_objects
app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
# Serve static files from the frontend directory itself
static_dir = os.path.dirname(__file__)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
# Mount robot meshes and YCB object assets
panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda")
ycb_data_path = ycb_objects.getDataPath()
app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda")
app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb")
@app.get("/")
async def get():
html_file = os.path.join(static_dir, "index.html")
if os.path.exists(html_file):
with open(html_file, "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read(), status_code=200)
return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
# Global variables to track the current active simulation, lock, and thread lock
current_sim: Optional[PandaSimulation] = None
executor_lock = asyncio.Lock()
pybullet_lock = threading.RLock()
def get_init_payload(sim: PandaSimulation) -> dict:
"""Gathers the initial static geometry and YCB object definitions."""
with pybullet_lock:
objects_info = {}
if sim and sim.scene:
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
cls = sim.scene.get_class(oid)
folder = ""
for cat_name, cat_cls, cat_folder in _YCB_CATALOG:
if cat_name == name:
folder = cat_folder
break
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
# Query collision shape data for CoM-to-link offset
collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client)
coll_scale = [1.0, 1.0, 1.0]
coll_local_pos = [0.0, 0.0, 0.0]
coll_local_ori = [0.0, 0.0, 0.0, 1.0]
if collision_data:
cd = collision_data[0]
coll_scale = list(cd[3])
coll_local_pos = list(cd[5])
coll_local_ori = list(cd[6])
# Query visual shape data for exact dimensions/scales and offsets relative to link
visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client)
vis_scale = [1.0, 1.0, 1.0]
vis_local_pos = [0.0, 0.0, 0.0]
vis_local_ori = [0.0, 0.0, 0.0, 1.0]
if visual_data:
vd = visual_data[0]
vis_scale = list(vd[3])
# Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual
vis_pos_com, vis_ori_com = pb.multiplyTransforms(
coll_local_pos, coll_local_ori,
list(vd[5]), list(vd[6])
)
vis_local_pos = list(vis_pos_com)
vis_local_ori = list(vis_ori_com)
objects_info[name] = {
"class": cls,
"folder": folder,
"initial_pos": list(pos),
"initial_ori": list(ori),
"vis_scale": vis_scale,
"vis_local_pos": vis_local_pos,
"vis_local_ori": vis_local_ori,
"coll_scale": coll_scale,
"coll_local_pos": coll_local_pos,
"coll_local_ori": coll_local_ori
}
return {
"type": "init",
"table": {
"center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z],
"half_extents": list(config.TABLE_HALF_EXTENTS),
"color": list(config.TABLE_COLOR),
"top_z": config.TABLE_TOP_Z
},
"tray": {
"position": list(config.TRAY_POSITION),
"half_extents": list(config.TRAY_HALF_EXTENTS),
"color": list(config.TRAY_COLOR)
},
"slots": {name: list(pos) for name, pos in config.SLOTS.items()},
"objects": objects_info
}
def get_simulation_state_payload(sim: PandaSimulation) -> dict:
"""Gathers the current robot joint positions and YCB object poses."""
with pybullet_lock:
if sim is None or sim.client is None or not pb.isConnected(sim.client):
return {}
# Read all joints (12 joints including arm joints and gripper fingers)
num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client)
joints_state = []
for i in range(num_joints):
pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client)
joints_state.append(pos)
# Read objects pos/ori
objects_state = {}
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
objects_state[name] = {
"pos": list(pos),
"ori": list(ori)
}
return {
"type": "state",
"joints": joints_state,
"objects": objects_state
}
def set_pybullet_window_visibility(visible: bool):
"""Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen."""
import sys
if sys.platform != "win32":
return False
import ctypes
import time
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
for _ in range(30):
found_hwnd = []
def foreach_window(hwnd, lParam):
length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
title = buff.value
if "bullet physics examplebrowser" in title.lower():
found_hwnd.append(hwnd)
return False
return True
ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0)
if found_hwnd:
hwnd = found_hwnd[0]
# Ensure the window is shown/restored from minimized state first (SW_SHOW = 5)
ctypes.windll.user32.ShowWindow(hwnd, 5)
# SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004
if visible:
# Move window to visible region
ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004)
else:
# Move window far off-screen to hide it without destroying OpenGL context
ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004)
print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True)
return True
time.sleep(0.1)
return False
def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool):
"""Calculates rearrangement score based on final object locations and collisions."""
with pybullet_lock:
score = 100
details = []
# Check target placement if we had a plan
target_location = None
target_object = None
for step in plan:
if step.get("function") in ("place_at", "place_down", "move_to"):
args = step.get("args", {})
if "location_id" in args:
target_location = args["location_id"]
if step.get("function") == "pick_up":
target_object = step.get("args", {}).get("object_id")
if target_object and target_location:
obj_id = sim.scene.name_to_id(target_object)
if obj_id is not None:
pos, _ = pb.getBasePositionAndOrientation(obj_id)
current_loc = sim.scene.classify_location(pos)
if current_loc == target_location:
details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm")
else:
details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm")
score -= 50
else:
details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm")
score -= 50
else:
details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.")
# Knock detection
knocked_count = 0
for oid in sim.scene.object_ids:
if oid == sim.scene.name_to_id(target_object):
continue
pos, _ = pb.getBasePositionAndOrientation(oid)
loc = sim.scene.classify_location(pos)
if loc == "elsewhere":
name = sim.scene.get_name(oid)
details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm")
score -= 15
knocked_count += 1
if knocked_count == 0:
details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm")
else:
score = max(0, score)
# Execution success
if executed_successfully:
details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm")
else:
details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm")
score -= 30
score = max(0, min(100, score))
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
return score, md
def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None):
"""Runs the planning, validation, execution with image streaming, and scoring."""
global current_sim
def log(message: str, step: Optional[int] = None):
try:
print(f"[WS Log] {message}", flush=True)
except Exception:
pass
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "log", "message": message, "step": step}),
loop
)
# Step 1: Planning
log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...")
if use_mock:
planner = RuleBasedPlanner()
log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)")
else:
api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY")
if not api_key:
log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.")
return
planner = RemoteLLMPlanner()
log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})")
with pybullet_lock:
current_sim.agent = LLMAgent(planner=planner)
# Define reachability check for scene state
def reachability_fn(oid):
cls = current_sim.scene.get_class(oid)
try:
grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls)
return current_sim.controller.is_reachable(grasp_pos, grasp_ori)
except Exception:
return False
carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None
scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name)
state_text = json.dumps(scene_state, indent=2)
try:
with pybullet_lock:
plan = current_sim.agent.plan(user_prompt, state_text)
log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.")
except Exception as e:
log(f"❌ [1] Lập kế hoạch thất bại: {e}")
return
# Send steps to client
plan_steps = []
for idx, step in enumerate(plan, 1):
func = step.get("function")
args = step.get("args", {})
obj = args.get("object_id") or args.get("location_id") or ""
plan_steps.append({
"step": idx,
"skill": func,
"object": obj,
"args": args
})
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "plan", "plan": plan_steps}),
loop
)
if not plan:
log("⚠️ [1] Kế hoạch rỗng.")
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, [], True)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
return
# Step 2: Validation
log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...")
try:
with pybullet_lock:
warnings = PlanVerifier.check(plan, scene_state)
if not warnings:
log("✅ [2] Kế hoạch hợp lệ.")
else:
log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.")
for w in warnings:
log(f" - {w}")
except Exception as e:
log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}")
return
# Step 3: PyBullet Execution (Live!)
log("⏳ [3/5] Đang thực thi hành động của robot...")
# Hook pb.stepSimulation to capture states during movements
original_step = pb.stepSimulation
last_stream_time = [0.0]
throttle_interval = 0.033
def wrapped_step():
original_step()
if not current_sim.gui:
# Sleep slightly in headless mode to simulate arm speed and avoid freezing
time.sleep(0.001)
curr_time = time.time()
if curr_time - last_stream_time[0] >= throttle_interval:
last_stream_time[0] = curr_time
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(
websocket.send_json(state_payload),
loop
)
with pybullet_lock:
pb.stepSimulation = wrapped_step
executed_successfully = True
try:
# Trigger an initial simulation state transmission
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
for i, step in enumerate(plan, 1):
log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}")
with pybullet_lock:
current_sim._execute(step, verbose=True)
log("✅ [3] Thực thi thành công toàn bộ kế hoạch.")
except Exception as e:
log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
executed_successfully = False
finally:
with pybullet_lock:
pb.stepSimulation = original_step
# Send a final state to ensure visual sync
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
# Step 5: Scoring
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
global current_sim
await websocket.accept()
loop = asyncio.get_running_loop()
# Retrieve user's desktop display preference from client query params
client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
# Force gui = False to run PyBullet completely headless (DIRECT mode)
gui = False
camera_state = {
"target": [0.5, 0.0, 0.3],
"dist": 1.3,
"yaw": 45.0,
"pitch": -35.0
}
async with executor_lock:
def init_sim():
global current_sim
with pybullet_lock:
is_connected = False
if current_sim is not None and current_sim.client is not None:
try:
is_connected = pb.isConnected(current_sim.client)
except Exception:
is_connected = False
if is_connected and current_sim.gui == gui:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
for _ in range(5):
pb.stepSimulation(physicsClientId=current_sim.client)
else:
if is_connected:
try:
current_sim.disconnect()
except Exception as e:
print(f"[Teardown Error] {e}")
current_sim = PandaSimulation(gui=gui, seed=0)
await asyncio.to_thread(init_sim)
# Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
# Send static scene configuration
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
await websocket.send_json(init_payload)
# Send the first simulation state to sync objects and joints
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
try:
while True:
data = await websocket.receive_text()
payload = json.loads(data)
p_type = payload.get("type")
if p_type == "run":
prompt = payload.get("prompt", "")
use_mock = payload.get("mock", False)
asyncio.create_task(
asyncio.to_thread(
run_pipeline_threadsafe,
websocket,
prompt,
loop,
use_mock
)
)
elif p_type == "reset":
async with executor_lock:
def reset_sim():
with pybullet_lock:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
await asyncio.to_thread(reset_sim)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
elif p_type == "update_object_pose":
name = payload.get("name")
pos = payload.get("pos")
ori = payload.get("ori")
async with executor_lock:
def move_obj():
with pybullet_lock:
oid = current_sim.scene.name_to_id(name)
if oid is not None:
pb.resetBasePositionAndOrientation(oid, pos, ori)
await asyncio.to_thread(move_obj)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
elif p_type == "update_joints":
joints_data = payload.get("joints")
async with executor_lock:
def move_joints():
with pybullet_lock:
for idx, q in enumerate(joints_data[:7]):
pb.resetJointState(current_sim.robot_id, idx, q)
if len(joints_data) >= 11:
pb.resetJointState(current_sim.robot_id, 9, joints_data[9])
pb.resetJointState(current_sim.robot_id, 10, joints_data[10])
await asyncio.to_thread(move_joints)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
elif p_type == "update_robot_ee":
pos = payload.get("pos")
async with executor_lock:
def move_robot_ee():
with pybullet_lock:
link_state = pb.getLinkState(
current_sim.robot_id,
current_sim.controller.ee_index,
physicsClientId=current_sim.client
)
ee_ori = link_state[1]
solution = pb.calculateInverseKinematics(
current_sim.robot_id,
current_sim.controller.ee_index,
pos,
ee_ori,
lowerLimits=current_sim.controller._lower_limits,
upperLimits=current_sim.controller._upper_limits,
jointRanges=current_sim.controller._joint_ranges,
restPoses=current_sim.controller._rest_poses,
maxNumIterations=300,
residualThreshold=1e-5,
physicsClientId=current_sim.client
)
for idx, q in enumerate(solution[:7]):
pb.resetJointState(
current_sim.robot_id,
idx,
q,
physicsClientId=current_sim.client
)
await asyncio.to_thread(move_robot_ee)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
pass
except WebSocketDisconnect:
print("Client disconnected")
except Exception as e:
print(f"WS Exception: {e}")
if __name__ == "__main__":
uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569import sys
import os
import json
import asyncio
import math
import time
import threading
from typing import Optional
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import uvicorn
import cv2
import numpy as np
import pybullet as pb
# Ensure project source root is in path
PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if PROJECT_SRC not in sys.path:
sys.path.insert(0, PROJECT_SRC)
from dotenv import load_dotenv
load_dotenv()
from main import PandaSimulation, _YCB_CATALOG
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
from llm_panda.plan_verifier import PlanVerifier
from llm_panda import config
import pybullet_data
from pybullet_object_models import ycb_objects
app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
# Serve static files from the frontend directory itself
static_dir = os.path.dirname(__file__)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
# Mount robot meshes and YCB object assets
panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda")
ycb_data_path = ycb_objects.getDataPath()
app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda")
app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb")
@app.get("/")
async def get():
html_file = os.path.join(static_dir, "index.html")
if os.path.exists(html_file):
with open(html_file, "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read(), status_code=200)
return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
# Global variables to track the current active simulation, lock, and thread lock
current_sim: Optional[PandaSimulation] = None
executor_lock = asyncio.Lock()
pybullet_lock = threading.RLock()
def get_init_payload(sim: PandaSimulation) -> dict:
"""Gathers the initial static geometry and YCB object definitions."""
with pybullet_lock:
objects_info = {}
if sim and sim.scene:
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
cls = sim.scene.get_class(oid)
folder = ""
for cat_name, cat_cls, cat_folder in _YCB_CATALOG:
if cat_name == name:
folder = cat_folder
break
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
# Query collision shape data for CoM-to-link offset
collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client)
coll_scale = [1.0, 1.0, 1.0]
coll_local_pos = [0.0, 0.0, 0.0]
coll_local_ori = [0.0, 0.0, 0.0, 1.0]
if collision_data:
cd = collision_data[0]
coll_scale = list(cd[3])
coll_local_pos = list(cd[5])
coll_local_ori = list(cd[6])
# Query visual shape data for exact dimensions/scales and offsets relative to link
visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client)
vis_scale = [1.0, 1.0, 1.0]
vis_local_pos = [0.0, 0.0, 0.0]
vis_local_ori = [0.0, 0.0, 0.0, 1.0]
if visual_data:
vd = visual_data[0]
vis_scale = list(vd[3])
# Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual
vis_pos_com, vis_ori_com = pb.multiplyTransforms(
coll_local_pos, coll_local_ori,
list(vd[5]), list(vd[6])
)
vis_local_pos = list(vis_pos_com)
vis_local_ori = list(vis_ori_com)
objects_info[name] = {
"class": cls,
"folder": folder,
"initial_pos": list(pos),
"initial_ori": list(ori),
"vis_scale": vis_scale,
"vis_local_pos": vis_local_pos,
"vis_local_ori": vis_local_ori,
"coll_scale": coll_scale,
"coll_local_pos": coll_local_pos,
"coll_local_ori": coll_local_ori
}
return {
"type": "init",
"table": {
"center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z],
"half_extents": list(config.TABLE_HALF_EXTENTS),
"color": list(config.TABLE_COLOR),
"top_z": config.TABLE_TOP_Z
},
"tray": {
"position": list(config.TRAY_POSITION),
"half_extents": list(config.TRAY_HALF_EXTENTS),
"color": list(config.TRAY_COLOR)
},
"slots": {name: list(pos) for name, pos in config.SLOTS.items()},
"objects": objects_info
}
def get_simulation_state_payload(sim: PandaSimulation) -> dict:
"""Gathers the current robot joint positions and YCB object poses."""
with pybullet_lock:
if sim is None or sim.client is None or not pb.isConnected(sim.client):
return {}
# Read all joints (12 joints including arm joints and gripper fingers)
num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client)
joints_state = []
for i in range(num_joints):
pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client)
joints_state.append(pos)
# Read objects pos/ori
objects_state = {}
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
objects_state[name] = {
"pos": list(pos),
"ori": list(ori)
}
return {
"type": "state",
"joints": joints_state,
"objects": objects_state
}
def set_pybullet_window_visibility(visible: bool):
"""Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen."""
import sys
if sys.platform != "win32":
return False
import ctypes
import time
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
for _ in range(30):
found_hwnd = []
def foreach_window(hwnd, lParam):
length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
title = buff.value
if "bullet physics examplebrowser" in title.lower():
found_hwnd.append(hwnd)
return False
return True
ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0)
if found_hwnd:
hwnd = found_hwnd[0]
# Ensure the window is shown/restored from minimized state first (SW_SHOW = 5)
ctypes.windll.user32.ShowWindow(hwnd, 5)
# SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004
if visible:
# Move window to visible region
ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004)
else:
# Move window far off-screen to hide it without destroying OpenGL context
ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004)
print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True)
return True
time.sleep(0.1)
return False
def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool):
"""Calculates rearrangement score based on final object locations and collisions."""
with pybullet_lock:
score = 100
details = []
# Check target placement if we had a plan
target_location = None
target_object = None
for step in plan:
if step.get("function") in ("place_at", "place_down", "move_to"):
args = step.get("args", {})
if "location_id" in args:
target_location = args["location_id"]
if step.get("function") == "pick_up":
target_object = step.get("args", {}).get("object_id")
if target_object and target_location:
obj_id = sim.scene.name_to_id(target_object)
if obj_id is not None:
pos, _ = pb.getBasePositionAndOrientation(obj_id)
current_loc = sim.scene.classify_location(pos)
if current_loc == target_location:
details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm")
else:
details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm")
score -= 50
else:
details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm")
score -= 50
else:
details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.")
# Knock detection
knocked_count = 0
for oid in sim.scene.object_ids:
if oid == sim.scene.name_to_id(target_object):
continue
pos, _ = pb.getBasePositionAndOrientation(oid)
loc = sim.scene.classify_location(pos)
if loc == "elsewhere":
name = sim.scene.get_name(oid)
details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm")
score -= 15
knocked_count += 1
if knocked_count == 0:
details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm")
else:
score = max(0, score)
# Execution success
if executed_successfully:
details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm")
else:
details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm")
score -= 30
score = max(0, min(100, score))
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
return score, md
def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None):
"""Runs the planning, validation, execution with image streaming, and scoring."""
global current_sim
def log(message: str, step: Optional[int] = None):
try:
print(f"[WS Log] {message}", flush=True)
except Exception:
pass
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "log", "message": message, "step": step}),
loop
)
# Step 1: Planning
log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...")
if use_mock:
planner = RuleBasedPlanner()
log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)")
else:
api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY")
if not api_key:
log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.")
return
planner = RemoteLLMPlanner()
log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})")
with pybullet_lock:
current_sim.agent = LLMAgent(planner=planner)
# Define reachability check for scene state
def reachability_fn(oid):
cls = current_sim.scene.get_class(oid)
try:
grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls)
return current_sim.controller.is_reachable(grasp_pos, grasp_ori)
except Exception:
return False
carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None
scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name)
state_text = json.dumps(scene_state, indent=2)
try:
with pybullet_lock:
plan = current_sim.agent.plan(user_prompt, state_text)
log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.")
except Exception as e:
log(f"❌ [1] Lập kế hoạch thất bại: {e}")
return
# Send steps to client
plan_steps = []
for idx, step in enumerate(plan, 1):
func = step.get("function")
args = step.get("args", {})
obj = args.get("object_id") or args.get("location_id") or ""
plan_steps.append({
"step": idx,
"skill": func,
"object": obj,
"args": args
})
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "plan", "plan": plan_steps}),
loop
)
if not plan:
log("⚠️ [1] Kế hoạch rỗng.")
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, [], True)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
return
# Step 2: Validation
log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...")
try:
with pybullet_lock:
warnings = PlanVerifier.check(plan, scene_state)
if not warnings:
log("✅ [2] Kế hoạch hợp lệ.")
else:
log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.")
for w in warnings:
log(f" - {w}")
except Exception as e:
log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}")
return
# Step 3: PyBullet Execution (Live!)
log("⏳ [3/5] Đang thực thi hành động của robot...")
# Hook pb.stepSimulation to capture states during movements
original_step = pb.stepSimulation
last_stream_time = [0.0]
throttle_interval = 0.033
def wrapped_step():
original_step()
if not current_sim.gui:
# Sleep slightly in headless mode to simulate arm speed and avoid freezing
time.sleep(0.001)
curr_time = time.time()
if curr_time - last_stream_time[0] >= throttle_interval:
last_stream_time[0] = curr_time
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(
websocket.send_json(state_payload),
loop
)
with pybullet_lock:
pb.stepSimulation = wrapped_step
executed_successfully = True
try:
# Trigger an initial simulation state transmission
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
for i, step in enumerate(plan, 1):
log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}")
with pybullet_lock:
current_sim._execute(step, verbose=True)
log("✅ [3] Thực thi thành công toàn bộ kế hoạch.")
except Exception as e:
log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
executed_successfully = False
finally:
with pybullet_lock:
pb.stepSimulation = original_step
# Send a final state to ensure visual sync
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
# Step 5: Scoring
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
global current_sim
await websocket.accept()
loop = asyncio.get_running_loop()
# Retrieve user's desktop display preference from client query params
client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
# Force gui = False to run PyBullet completely headless (DIRECT mode)
gui = False
camera_state = {
"target": [0.5, 0.0, 0.3],
"dist": 1.3,
"yaw": 45.0,
"pitch": -35.0
}
async with executor_lock:
def init_sim():
global current_sim
with pybullet_lock:
is_connected = False
if current_sim is not None and current_sim.client is not None:
try:
is_connected = pb.isConnected(current_sim.client)
except Exception:
is_connected = False
if is_connected and current_sim.gui == gui:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
for _ in range(5):
pb.stepSimulation(physicsClientId=current_sim.client)
else:
if is_connected:
try:
current_sim.disconnect()
except Exception as e:
print(f"[Teardown Error] {e}")
current_sim = PandaSimulation(gui=gui, seed=0)
await asyncio.to_thread(init_sim)
# Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
# Send static scene configuration
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
await websocket.send_json(init_payload)
# Send the first simulation state to sync objects and joints
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
try:
while True:
data = await websocket.receive_text()
payload = json.loads(data)
p_type = payload.get("type")
if p_type == "run":
prompt = payload.get("prompt", "")
use_mock = payload.get("mock", False)
asyncio.create_task(
asyncio.to_thread(
run_pipeline_threadsafe,
websocket,
prompt,
loop,
use_mock
)
)
elif p_type == "reset":
async with executor_lock:
def reset_sim():
with pybullet_lock:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
await asyncio.to_thread(reset_sim)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
elif p_type == "update_object_pose":
name = payload.get("name")
pos = payload.get("pos")
ori = payload.get("ori")
async with executor_lock:
def move_obj():
with pybullet_lock:
oid = current_sim.scene.name_to_id(name)
if oid is not None:
pb.resetBasePositionAndOrientation(oid, pos, ori)
await asyncio.to_thread(move_obj)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
elif p_type == "update_joints":
joints_data = payload.get("joints")
async with executor_lock:
def move_joints():
with pybullet_lock:
for idx, q in enumerate(joints_data[:7]):
pb.resetJointState(current_sim.robot_id, idx, q)
if len(joints_data) >= 11:
pb.resetJointState(current_sim.robot_id, 9, joints_data[9])
pb.resetJointState(current_sim.robot_id, 10, joints_data[10])
await asyncio.to_thread(move_joints)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
elif p_type == "update_robot_ee":
pos = payload.get("pos")
async with executor_lock:
def move_robot_ee():
with pybullet_lock:
link_state = pb.getLinkState(
current_sim.robot_id,
current_sim.controller.ee_index,
physicsClientId=current_sim.client
)
ee_ori = link_state[1]
solution = pb.calculateInverseKinematics(
current_sim.robot_id,
current_sim.controller.ee_index,
pos,
ee_ori,
lowerLimits=current_sim.controller._lower_limits,
upperLimits=current_sim.controller._upper_limits,
jointRanges=current_sim.controller._joint_ranges,
restPoses=current_sim.controller._rest_poses,
maxNumIterations=300,
residualThreshold=1e-5,
physicsClientId=current_sim.client
)
for idx, q in enumerate(solution[:7]):
pb.resetJointState(
current_sim.robot_id,
idx,
q,
physicsClientId=current_sim.client
)
await asyncio.to_thread(move_robot_ee)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
pass
except WebSocketDisconnect:
print("Client disconnected")
except Exception as e:
print(f"WS Exception: {e}")
if __name__ == "__main__":
uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937:root {
--primary-color: #1e3a8a; /* Dark Navy Blue */
--primary-glow: rgba(30, 58, 138, 0.3);
--accent-success: #064e3b; /* Very Dark Green */
--accent-warning: #78350f; /* Dark Amber/Brown */
--accent-error: #7f1d1d; /* Dark Red */
--bg-dark: #f8fafc;
--text-main: #000000; /* Pure Black for maximum contrast */
--text-muted: #1e293b; /* Dark Slate */
--hud-text-shadow: 0 1px 3px rgba(255, 255, 255, 0.95), 0 0 6px rgba(255, 255, 255, 0.85);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Outfit', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background-color: #f1f5f9;
color: var(--text-main);
overflow: hidden;
width: 100vw;
height: 100vh;
}
button, input, select, table {
font-family: inherit;
}
/* Fullscreen Viewport Container */
#viewport-container {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #f1f5f9;
z-index: 1;
overflow: hidden;
}
#pybullet-viewport {
width: 100%;
height: 100%;
object-fit: cover;
border: none;
border-radius: 0;
box-shadow: none;
cursor: grab;
}
#pybullet-viewport:active {
cursor: grabbing;
}
/* Transparent HUD Panels with Premium Glassmorphism */
.glass {
background: rgba(255, 255, 255, 0.75);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.4);
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.08);
border-radius: 16px;
}
/* Sidebar Styling (Light-HUD layout) */
.sidebar {
position: absolute;
top: 20px;
left: 20px;
width: 360px;
height: calc(100vh - 40px);
z-index: 10;
padding: 20px;
display: flex;
flex-direction: column;
gap: 16px;
pointer-events: auto;
}
.sidebar-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 2px solid rgba(37, 99, 235, 0.2);
padding-bottom: 10px;
}
.sidebar-header .brand {
display: flex;
align-items: center;
gap: 8px;
color: #1e3a8a;
}
.sidebar-header h2 {
font-size: 1.4rem;
font-weight: 700;
letter-spacing: -0.025em;
text-shadow: var(--hud-text-shadow);
}
.brand-icon {
filter: drop-shadow(0 1px 2px rgba(255,255,255,0.8));
}
.badge {
font-size: 0.7rem;
font-weight: 700;
padding: 4px 10px;
border-radius: 10px;
text-transform: uppercase;
letter-spacing: 0.05em;
display: inline-flex;
align-items: center;
gap: 6px;
text-shadow: var(--hud-text-shadow);
border: 1px solid currentColor;
}
.badge::before {
content: '';
display: inline-block;
width: 6px;
height: 6px;
border-radius: 50%;
}
.badge.online {
background: rgba(16, 185, 129, 0.15);
color: var(--accent-success);
}
.badge.online::before {
background: var(--accent-success);
box-shadow: 0 0 8px var(--accent-success);
}
.badge.offline {
background: rgba(239, 68, 68, 0.15);
color: var(--accent-error);
}
.badge.offline::before {
background: var(--accent-error);
}
/* Tab Bar Navigation inside Sidebar */
.sidebar-tabs {
display: flex;
gap: 4px;
background: rgba(15, 23, 42, 0.05);
border: 1px solid rgba(0, 0, 0, 0.05);
border-radius: 10px;
padding: 3px;
justify-content: space-between;
}
.tab-btn {
flex-grow: 1;
display: flex;
justify-content: center;
align-items: center;
padding: 8px 4px;
background: transparent;
border: none;
border-radius: 6px;
color: var(--text-muted);
cursor: pointer;
transition: all 0.2s ease;
outline: none;
}
.tab-btn:hover {
background: rgba(255, 255, 255, 0.5);
color: var(--primary-color);
}
.tab-btn.active {
background: white;
color: var(--primary-color);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
/* Tab Panel Transitions */
.tab-panel {
display: none;
opacity: 0;
transition: opacity 0.3s ease;
}
.tab-panel.active {
display: flex;
flex-direction: column;
gap: 16px;
opacity: 1;
flex-grow: 1;
min-height: 0;
}
.sidebar-section {
display: flex;
flex-direction: column;
gap: 8px;
}
.sidebar-section.flex-grow {
flex-grow: 1;
min-height: 0;
}
.sidebar-section h3 {
font-size: 0.8rem;
font-weight: 700;
text-transform: uppercase;
color: var(--primary-color);
letter-spacing: 0.05em;
text-shadow: var(--hud-text-shadow);
}
/* Operations Steps */
.status-steps {
display: flex;
flex-direction: column;
gap: 8px;
}
.status-step {
display: flex;
align-items: center;
gap: 10px;
font-size: 0.9rem;
color: var(--text-muted);
font-weight: 600;
text-shadow: var(--hud-text-shadow);
transition: all 0.2s ease;
}
.status-step .dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: rgba(15, 23, 42, 0.3);
border: 1px solid rgba(15, 23, 42, 0.5);
transition: all 0.2s ease;
}
.status-step.active {
color: var(--primary-color);
}
.status-step.active .dot {
background: var(--primary-color);
box-shadow: 0 0 8px var(--primary-color);
border-color: var(--primary-color);
}
.status-step.completed {
color: var(--accent-success);
}
.status-step.completed .dot {
background: var(--accent-success);
border-color: var(--accent-success);
}
.status-step.error {
color: var(--accent-error);
}
.status-step.error .dot {
background: var(--accent-error);
border-color: var(--accent-error);
}
/* Task Plan List */
.plan-list {
background: rgba(255, 255, 255, 0.65);
backdrop-filter: blur(8px);
border: 1px solid rgba(0, 0, 0, 0.08);
border-radius: 10px;
max-height: 120px;
overflow-y: auto;
padding: 8px;
display: flex;
flex-direction: column;
gap: 5px;
box-shadow: 0 4px 20px rgba(0,0,0,0.03);
}
.plan-item {
font-size: 0.8rem;
padding: 6px 10px;
background: rgba(255, 255, 255, 0.4);
border-radius: 6px;
border-left: 3px solid rgba(0, 0, 0, 0.1);
color: var(--text-main);
font-weight: 500;
display: flex;
justify-content: space-between;
}
.plan-item.active {
background: rgba(37, 99, 235, 0.08);
border-left-color: var(--primary-color);
color: var(--primary-color);
font-weight: 600;
}
.plan-item.completed {
border-left-color: var(--accent-success);
color: rgba(15, 23, 42, 0.4);
text-decoration: line-through;
opacity: 0.6;
}
/* Monospace Log Console */
.log-console {
background: rgba(255, 255, 255, 0.65);
backdrop-filter: blur(8px);
border: 1px solid rgba(0, 0, 0, 0.08);
font-family: 'Consolas', 'Fira Code', monospace;
font-size: 0.8rem;
line-height: 1.4;
border-radius: 10px;
padding: 10px;
overflow-y: auto;
flex-grow: 1;
display: flex;
flex-direction: column;
gap: 5px;
box-shadow: 0 4px 20px rgba(0,0,0,0.03);
}
.log-entry {
color: var(--text-main);
font-weight: 600;
}
.log-entry.info { color: #1e3a8a; }
.log-entry.success { color: #064e3b; }
.log-entry.warn { color: #78350f; }
.log-entry.error { color: #7f1d1d; }
.placeholder-text {
color: var(--text-muted);
font-style: italic;
text-align: center;
margin: auto;
font-size: 0.85rem;
}
/* Scenarios Tab styling */
.scenarios-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.scenario-card {
background: rgba(255, 255, 255, 0.6);
border: 1px solid rgba(0, 0, 0, 0.08);
border-radius: 10px;
padding: 10px 6px;
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
text-align: center;
cursor: pointer;
transition: all 0.2s ease;
user-select: none;
}
.scenario-card:hover {
background: rgba(255, 255, 255, 0.95);
border-color: var(--primary-color);
box-shadow: 0 4px 12px rgba(30, 58, 138, 0.08);
transform: translateY(-1.5px);
}
.scenario-icon {
color: var(--primary-color);
background: rgba(30, 58, 138, 0.06);
padding: 6px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
}
.scenario-card h4 {
font-size: 0.7rem;
font-weight: 700;
color: var(--text-muted);
line-height: 1.2;
}
.preset-commands-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.preset-command-item {
background: rgba(255, 255, 255, 0.55);
border: 1px solid rgba(0, 0, 0, 0.06);
border-radius: 8px;
padding: 8px 12px;
font-size: 0.8rem;
font-weight: 600;
color: var(--text-muted);
text-align: left;
cursor: pointer;
transition: all 0.2s ease;
}
.preset-command-item:hover {
background: rgba(255, 255, 255, 0.85);
border-color: var(--primary-color);
color: var(--primary-color);
}
/* Objects Tab Table */
.table-container {
background: rgba(255, 255, 255, 0.65);
border: 1px solid rgba(0, 0, 0, 0.06);
border-radius: 10px;
overflow: hidden;
box-shadow: 0 4px 20px rgba(0,0,0,0.03);
}
.objects-table {
width: 100%;
border-collapse: collapse;
font-size: 0.8rem;
text-align: left;
}
.objects-table th, .objects-table td {
padding: 10px 10px;
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}
.objects-table th {
background: rgba(15, 23, 42, 0.03);
color: var(--primary-color);
font-weight: 700;
text-transform: uppercase;
font-size: 0.7rem;
letter-spacing: 0.05em;
}
.objects-table tr:last-child td {
border-bottom: none;
}
.objects-table td {
color: var(--text-main);
font-weight: 600;
}
.tag-badge {
display: inline-block;
padding: 2px 6px;
border-radius: 4px;
font-size: 0.65rem;
font-weight: 700;
text-transform: uppercase;
}
.tag-badge.safe {
background: rgba(16, 185, 129, 0.1);
color: #047857;
}
/* History Tab list */
.history-list {
display: flex;
flex-direction: column;
gap: 8px;
max-height: calc(100vh - 120px);
overflow-y: auto;
padding-right: 2px;
}
.history-card {
background: rgba(255, 255, 255, 0.6);
border: 1px solid rgba(0, 0, 0, 0.06);
border-radius: 10px;
padding: 10px 12px;
display: flex;
flex-direction: column;
gap: 6px;
transition: all 0.2s ease;
}
.history-card:hover {
background: rgba(255, 255, 255, 0.85);
border-color: var(--primary-color);
}
.history-card-header {
display: flex;
justify-content: space-between;
font-size: 0.7rem;
color: var(--text-muted);
font-weight: 600;
}
.history-card-prompt {
font-size: 0.8rem;
font-style: italic;
color: var(--text-main);
font-weight: 600;
line-height: 1.3;
}
.history-card-footer {
display: flex;
justify-content: space-between;
align-items: center;
border-top: 1px solid rgba(0, 0, 0, 0.04);
padding-top: 6px;
margin-top: 2px;
}
.history-score {
font-size: 0.85rem;
font-weight: 700;
}
.history-score.high { color: #047857; }
.history-score.medium { color: #b45309; }
.history-score.low { color: #b91c1c; }
.history-actions {
display: flex;
gap: 4px;
}
.history-action-btn {
background: transparent;
border: 1px solid rgba(37, 99, 235, 0.2);
color: var(--primary-color);
padding: 3px 6px;
border-radius: 4px;
font-size: 0.7rem;
font-weight: 600;
cursor: pointer;
display: flex;
align-items: center;
gap: 3px;
transition: all 0.2s ease;
}
.history-action-btn:hover {
background: rgba(37, 99, 235, 0.08);
border-color: var(--primary-color);
}
/* Analytics Tab KPIs & Charts */
.kpi-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.kpi-card {
background: rgba(255, 255, 255, 0.65);
border: 1px solid rgba(0, 0, 0, 0.06);
border-radius: 10px;
padding: 10px 4px;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
box-shadow: 0 2px 8px rgba(0,0,0,0.02);
}
.kpi-value {
font-size: 1.15rem;
font-weight: 700;
color: var(--primary-color);
}
.kpi-label {
font-size: 0.65rem;
font-weight: 700;
color: var(--text-muted);
text-transform: uppercase;
margin-top: 2px;
letter-spacing: 0.02em;
}
.analytics-chart {
display: flex;
flex-direction: column;
gap: 10px;
background: rgba(255, 255, 255, 0.5);
border: 1px solid rgba(0, 0, 0, 0.06);
border-radius: 10px;
padding: 12px;
}
.chart-bar-group {
display: flex;
flex-direction: column;
gap: 4px;
}
.chart-label-row {
display: flex;
justify-content: space-between;
font-size: 0.75rem;
font-weight: 600;
color: var(--text-muted);
}
.chart-track {
width: 100%;
height: 8px;
background: rgba(0, 0, 0, 0.05);
border-radius: 4px;
overflow: hidden;
}
.chart-bar {
height: 100%;
border-radius: 4px;
transition: width 0.6s cubic-bezier(0.16, 1, 0.3, 1);
}
/* System settings form controls */
.form-group {
display: flex;
flex-direction: column;
gap: 4px;
}
.form-label {
font-size: 0.8rem;
font-weight: 600;
color: var(--text-muted);
}
.select-wrapper {
position: relative;
width: 100%;
}
.glass-select {
width: 100%;
background: rgba(255, 255, 255, 0.7);
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 8px;
padding: 8px 24px 8px 10px;
font-size: 0.8rem;
font-weight: 600;
color: var(--text-main);
outline: none;
cursor: pointer;
transition: all 0.2s ease;
appearance: none;
}
.glass-select:focus {
border-color: var(--primary-color);
box-shadow: 0 0 10px rgba(37, 99, 235, 0.1);
}
.select-wrapper::after {
content: '';
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
width: 0;
height: 0;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 4px solid var(--text-muted);
pointer-events: none;
}
/* Floating Chat Input Box & Buttons */
.chat-container {
position: absolute;
bottom: 30px;
left: calc(50% + 180px);
transform: translateX(-50%);
width: 650px;
z-index: 10;
padding: 12px;
display: flex;
flex-direction: column;
gap: 8px;
pointer-events: auto;
}
#chat-form {
display: flex;
gap: 8px;
align-items: center;
position: relative;
}
#chat-input {
flex-grow: 1;
background: rgba(255, 255, 255, 0.75);
backdrop-filter: blur(10px);
border: 2px solid var(--primary-color);
box-shadow: 0 4px 20px rgba(0,0,0,0.05);
padding: 12px 18px;
border-radius: 12px;
color: #0f172a;
font-size: 0.95rem;
font-weight: 600;
outline: none;
transition: all 0.2s ease;
}
#chat-input:focus {
border-color: #1d4ed8;
background: rgba(255, 255, 255, 0.9);
box-shadow: 0 0 15px rgba(37, 99, 235, 0.2);
}
.chat-action-btn {
background: rgba(255, 255, 255, 0.85);
border: 2px solid var(--primary-color);
color: var(--primary-color);
width: 46px;
height: 46px;
border-radius: 12px;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.2s ease;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
outline: none;
}
.chat-action-btn:hover {
background: rgba(255, 255, 255, 0.95);
transform: translateY(-1px);
box-shadow: 0 4px 16px rgba(30, 58, 138, 0.12);
}
.chat-action-btn:active {
transform: translateY(0);
}
#submit-btn {
background: var(--primary-color);
color: white;
}
#submit-btn:hover {
background: #1d4ed8;
}
#submit-btn:disabled, #chat-input:disabled, #mic-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
box-shadow: none;
}
/* Pulsing voice recorder active glow */
#mic-btn.recording {
border-color: var(--accent-error);
color: var(--accent-error);
background: rgba(239, 68, 68, 0.08);
animation: pulseMic 1.5s infinite alternate;
}
@keyframes pulseMic {
0% {
box-shadow: 0 0 4px rgba(239, 68, 68, 0.2);
}
100% {
box-shadow: 0 0 16px rgba(239, 68, 68, 0.5);
}
}
.chat-options {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.8rem;
color: #0f172a;
font-weight: 600;
text-shadow: var(--hud-text-shadow);
}
/* Toggle Switch styling */
.toggle-switch {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
}
.toggle-switch input {
display: none;
}
.slider {
position: relative;
display: inline-block;
width: 32px;
height: 18px;
background-color: rgba(15, 23, 42, 0.2);
border-radius: 18px;
transition: .3s;
border: 1px solid rgba(0, 0, 0, 0.15);
}
.slider:before {
position: absolute;
content: "";
height: 12px;
width: 12px;
left: 2px;
bottom: 2px;
background-color: #0f172a;
border-radius: 50%;
transition: .3s;
}
.toggle-switch input:checked + .slider {
background-color: var(--primary-color);
border-color: #1d4ed8;
}
.toggle-switch input:checked + .slider:before {
background-color: white;
transform: translateX(14px);
}
.toggle-label {
user-select: none;
}
/* Custom Text and Primary Buttons */
.text-btn {
background: none;
border: none;
color: #1d4ed8;
cursor: pointer;
font-weight: 700;
transition: color 0.2s;
font-size: 0.8rem;
text-shadow: var(--hud-text-shadow);
}
.text-btn:hover {
color: #0f172a;
}
.primary-btn {
background: var(--primary-color);
color: white;
border: none;
padding: 10px 24px;
border-radius: 8px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
box-shadow: 0 4px 12px var(--primary-glow);
}
.primary-btn:hover {
background: #1d4ed8;
box-shadow: 0 4px 20px rgba(29, 78, 216, 0.4);
}
/* Header overlays */
.header-overlay {
position: absolute;
top: 20px;
left: 390px;
right: 20px;
z-index: 10;
pointer-events: none;
}
.header-overlay h1 {
font-size: 1.3rem;
font-weight: 700;
letter-spacing: -0.015em;
color: #0f172a;
text-shadow: var(--hud-text-shadow);
margin-bottom: 2px;
}
.header-overlay p {
font-size: 0.8rem;
color: var(--text-muted);
text-shadow: var(--hud-text-shadow);
}
/* Autocomplete Suggestion Panel styling */
.autocomplete-panel {
position: absolute;
bottom: calc(100% + 10px);
left: 0;
width: 100%;
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(12px);
border: 1px solid rgba(30, 58, 138, 0.15);
border-radius: 12px;
box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.08);
padding: 6px;
display: flex;
flex-direction: column;
gap: 3px;
z-index: 100;
max-height: 150px;
overflow-y: auto;
}
.autocomplete-panel.hidden {
display: none;
}
.autocomplete-item {
padding: 8px 12px;
font-size: 0.8rem;
font-weight: 600;
color: var(--text-muted);
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
text-align: left;
}
.autocomplete-item:hover {
background: rgba(30, 58, 138, 0.06);
color: var(--primary-color);
}
/* Modal Overlay for Score Card */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(15, 23, 42, 0.45);
backdrop-filter: blur(10px);
z-index: 1000;
display: flex;
justify-content: center;
align-items: center;
opacity: 1;
transition: opacity 0.3s ease;
}
.modal-overlay.hidden {
opacity: 0;
pointer-events: none;
}
.modal-content {
width: 500px;
max-width: 90%;
padding: 24px;
display: flex;
flex-direction: column;
gap: 16px;
background: rgba(255, 255, 255, 0.9) !important;
border: 2px solid var(--primary-color) !important;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2) !important;
border-radius: 16px;
animation: scaleUp 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}
@keyframes scaleUp {
from { transform: scale(0.9); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
.modal-content h2 {
font-size: 1.35rem;
text-align: center;
border-bottom: 2px solid rgba(37, 99, 235, 0.2);
padding-bottom: 10px;
color: #0f172a;
}
.score-md-content {
font-size: 0.9rem;
line-height: 1.5;
color: #334155;
}
.score-md-content h3 {
margin: 10px 0 4px 0;
font-size: 1rem;
color: #1d4ed8;
}
.score-md-content ul {
padding-left: 18px;
margin-bottom: 8px;
}
.score-md-content li {
margin-bottom: 2px;
}
.score-md-content strong {
color: #0f172a;
}
/* Scrollbars styling */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: rgba(37, 99, 235, 0.25);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(37, 99, 235, 0.45);
}
/* Manual controls range sliders styling */
.manual-controls {
display: flex;
flex-direction: column;
gap: 8px;
background: rgba(255, 255, 255, 0.5);
border: 1px solid rgba(0, 0, 0, 0.06);
border-radius: 10px;
padding: 12px;
max-height: 240px;
overflow-y: auto;
}
.slider-group {
display: flex;
flex-direction: column;
gap: 2px;
}
.slider-group label {
font-size: 0.75rem;
font-weight: 600;
color: var(--text-muted);
display: flex;
justify-content: space-between;
}
.slider-group input[type="range"] {
width: 100%;
height: 4px;
background: rgba(15, 23, 42, 0.1);
border-radius: 2px;
outline: none;
accent-color: var(--primary-color);
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524import sys
import os
import json
import asyncio
import math
import time
import threading
from typing import Optional
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import uvicorn
import cv2
import numpy as np
import pybullet as pb
# Ensure project source root is in path
PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if PROJECT_SRC not in sys.path:
sys.path.insert(0, PROJECT_SRC)
from dotenv import load_dotenv
load_dotenv()
from main import PandaSimulation, _YCB_CATALOG
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
from llm_panda.plan_verifier import PlanVerifier
from llm_panda import config
import pybullet_data
from pybullet_object_models import ycb_objects
app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
# Serve static files from the frontend directory itself
static_dir = os.path.dirname(__file__)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
# Mount robot meshes and YCB object assets
panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda")
ycb_data_path = ycb_objects.getDataPath()
app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda")
app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb")
@app.get("/")
async def get():
html_file = os.path.join(static_dir, "index.html")
if os.path.exists(html_file):
with open(html_file, "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read(), status_code=200)
return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
# Global variables to track the current active simulation, lock, and thread lock
current_sim: Optional[PandaSimulation] = None
executor_lock = asyncio.Lock()
pybullet_lock = threading.RLock()
def get_init_payload(sim: PandaSimulation) -> dict:
"""Gathers the initial static geometry and YCB object definitions."""
with pybullet_lock:
objects_info = {}
if sim and sim.scene:
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
cls = sim.scene.get_class(oid)
folder = ""
for cat_name, cat_cls, cat_folder in _YCB_CATALOG:
if cat_name == name:
folder = cat_folder
break
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
# Query collision shape data for CoM-to-link offset
collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client)
coll_scale = [1.0, 1.0, 1.0]
coll_local_pos = [0.0, 0.0, 0.0]
coll_local_ori = [0.0, 0.0, 0.0, 1.0]
if collision_data:
cd = collision_data[0]
coll_scale = list(cd[3])
coll_local_pos = list(cd[5])
coll_local_ori = list(cd[6])
# Query visual shape data for exact dimensions/scales and offsets relative to link
visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client)
vis_scale = [1.0, 1.0, 1.0]
vis_local_pos = [0.0, 0.0, 0.0]
vis_local_ori = [0.0, 0.0, 0.0, 1.0]
if visual_data:
vd = visual_data[0]
vis_scale = list(vd[3])
# Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual
vis_pos_com, vis_ori_com = pb.multiplyTransforms(
coll_local_pos, coll_local_ori,
list(vd[5]), list(vd[6])
)
vis_local_pos = list(vis_pos_com)
vis_local_ori = list(vis_ori_com)
objects_info[name] = {
"class": cls,
"folder": folder,
"initial_pos": list(pos),
"initial_ori": list(ori),
"vis_scale": vis_scale,
"vis_local_pos": vis_local_pos,
"vis_local_ori": vis_local_ori,
"coll_scale": coll_scale,
"coll_local_pos": coll_local_pos,
"coll_local_ori": coll_local_ori
}
return {
"type": "init",
"table": {
"center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z],
"half_extents": list(config.TABLE_HALF_EXTENTS),
"color": list(config.TABLE_COLOR),
"top_z": config.TABLE_TOP_Z
},
"tray": {
"position": list(config.TRAY_POSITION),
"half_extents": list(config.TRAY_HALF_EXTENTS),
"color": list(config.TRAY_COLOR)
},
"slots": {name: list(pos) for name, pos in config.SLOTS.items()},
"objects": objects_info
}
def get_simulation_state_payload(sim: PandaSimulation) -> dict:
"""Gathers the current robot joint positions and YCB object poses."""
with pybullet_lock:
if sim is None or sim.client is None or not pb.isConnected(sim.client):
return {}
# Read all joints (12 joints including arm joints and gripper fingers)
num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client)
joints_state = []
for i in range(num_joints):
pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client)
joints_state.append(pos)
# Read objects pos/ori
objects_state = {}
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
objects_state[name] = {
"pos": list(pos),
"ori": list(ori)
}
return {
"type": "state",
"joints": joints_state,
"objects": objects_state
}
def set_pybullet_window_visibility(visible: bool):
"""Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen."""
import sys
if sys.platform != "win32":
return False
import ctypes
import time
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
for _ in range(30):
found_hwnd = []
def foreach_window(hwnd, lParam):
length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
title = buff.value
if "bullet physics examplebrowser" in title.lower():
found_hwnd.append(hwnd)
return False
return True
ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0)
if found_hwnd:
hwnd = found_hwnd[0]
# Ensure the window is shown/restored from minimized state first (SW_SHOW = 5)
ctypes.windll.user32.ShowWindow(hwnd, 5)
# SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004
if visible:
# Move window to visible region
ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004)
else:
# Move window far off-screen to hide it without destroying OpenGL context
ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004)
print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True)
return True
time.sleep(0.1)
return False
def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool):
"""Calculates rearrangement score based on final object locations and collisions."""
with pybullet_lock:
score = 100
details = []
# Check target placement if we had a plan
target_location = None
target_object = None
for step in plan:
if step.get("function") in ("place_at", "place_down", "move_to"):
args = step.get("args", {})
if "location_id" in args:
target_location = args["location_id"]
if step.get("function") == "pick_up":
target_object = step.get("args", {}).get("object_id")
if target_object and target_location:
obj_id = sim.scene.name_to_id(target_object)
if obj_id is not None:
pos, _ = pb.getBasePositionAndOrientation(obj_id)
current_loc = sim.scene.classify_location(pos)
if current_loc == target_location:
details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm")
else:
details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm")
score -= 50
else:
details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm")
score -= 50
else:
details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.")
# Knock detection
knocked_count = 0
for oid in sim.scene.object_ids:
if oid == sim.scene.name_to_id(target_object):
continue
pos, _ = pb.getBasePositionAndOrientation(oid)
loc = sim.scene.classify_location(pos)
if loc == "elsewhere":
name = sim.scene.get_name(oid)
details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm")
score -= 15
knocked_count += 1
if knocked_count == 0:
details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm")
else:
score = max(0, score)
# Execution success
if executed_successfully:
details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm")
else:
details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm")
score -= 30
score = max(0, min(100, score))
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
return score, md
def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None):
"""Runs the planning, validation, execution with image streaming, and scoring."""
global current_sim
def log(message: str, step: Optional[int] = None):
try:
print(f"[WS Log] {message}", flush=True)
except Exception:
pass
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "log", "message": message, "step": step}),
loop
)
# Step 1: Planning
log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...")
if use_mock:
planner = RuleBasedPlanner()
log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)")
else:
api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY")
if not api_key:
log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.")
return
planner = RemoteLLMPlanner()
log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})")
with pybullet_lock:
current_sim.agent = LLMAgent(planner=planner)
# Define reachability check for scene state
def reachability_fn(oid):
cls = current_sim.scene.get_class(oid)
try:
grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls)
return current_sim.controller.is_reachable(grasp_pos, grasp_ori)
except Exception:
return False
carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None
scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name)
state_text = json.dumps(scene_state, indent=2)
try:
with pybullet_lock:
plan = current_sim.agent.plan(user_prompt, state_text)
log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.")
except Exception as e:
log(f"❌ [1] Lập kế hoạch thất bại: {e}")
return
# Send steps to client
plan_steps = []
for idx, step in enumerate(plan, 1):
func = step.get("function")
args = step.get("args", {})
obj = args.get("object_id") or args.get("location_id") or ""
plan_steps.append({
"step": idx,
"skill": func,
"object": obj,
"args": args
})
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "plan", "plan": plan_steps}),
loop
)
if not plan:
log("⚠️ [1] Kế hoạch rỗng.")
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, [], True)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
return
# Step 2: Validation
log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...")
try:
with pybullet_lock:
warnings = PlanVerifier.check(plan, scene_state)
if not warnings:
log("✅ [2] Kế hoạch hợp lệ.")
else:
log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.")
for w in warnings:
log(f" - {w}")
except Exception as e:
log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}")
return
# Step 3: PyBullet Execution (Live!)
log("⏳ [3/5] Đang thực thi hành động của robot...")
# Hook pb.stepSimulation to capture states during movements
original_step = pb.stepSimulation
last_stream_time = [0.0]
throttle_interval = 0.033 if current_sim.gui else 0.066
def wrapped_step():
original_step()
if not current_sim.gui:
# Sleep slightly in headless mode to simulate arm speed and avoid freezing
time.sleep(0.001)
curr_time = time.time()
if curr_time - last_stream_time[0] >= throttle_interval:
last_stream_time[0] = curr_time
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(
websocket.send_json(state_payload),
loop
)
with pybullet_lock:
pb.stepSimulation = wrapped_step
executed_successfully = True
try:
# Trigger an initial simulation state transmission
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
for i, step in enumerate(plan, 1):
log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}")
with pybullet_lock:
current_sim._execute(step, verbose=True)
log("✅ [3] Thực thi thành công toàn bộ kế hoạch.")
except Exception as e:
log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
executed_successfully = False
finally:
with pybullet_lock:
pb.stepSimulation = original_step
# Send a final state to ensure visual sync
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
# Step 5: Scoring
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
global current_sim
await websocket.accept()
loop = asyncio.get_running_loop()
# Retrieve user's desktop display preference from client query params
client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
# Force gui = False to run PyBullet completely headless (DIRECT mode)
gui = False
camera_state = {
"target": [0.5, 0.0, 0.3],
"dist": 1.3,
"yaw": 45.0,
"pitch": -35.0
}
async with executor_lock:
def init_sim():
global current_sim
with pybullet_lock:
is_connected = False
if current_sim is not None and current_sim.client is not None:
try:
is_connected = pb.isConnected(current_sim.client)
except Exception:
is_connected = False
if is_connected and current_sim.gui == gui:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
for _ in range(5):
pb.stepSimulation(physicsClientId=current_sim.client)
else:
if is_connected:
try:
current_sim.disconnect()
except Exception as e:
print(f"[Teardown Error] {e}")
current_sim = PandaSimulation(gui=gui, seed=0)
await asyncio.to_thread(init_sim)
# Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
# Send static scene configuration
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
await websocket.send_json(init_payload)
# Send the first simulation state to sync objects and joints
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
try:
while True:
data = await websocket.receive_text()
payload = json.loads(data)
p_type = payload.get("type")
if p_type == "run":
prompt = payload.get("prompt", "")
use_mock = payload.get("mock", False)
asyncio.create_task(
asyncio.to_thread(
run_pipeline_threadsafe,
websocket,
prompt,
loop,
use_mock
)
)
elif p_type == "reset":
async with executor_lock:
def reset_sim():
with pybullet_lock:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
await asyncio.to_thread(reset_sim)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
pass
except WebSocketDisconnect:
print("Client disconnected")
except Exception as e:
print(f"WS Exception: {e}")
if __name__ == "__main__":
uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569import sys
import os
import json
import asyncio
import math
import time
import threading
from typing import Optional
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import uvicorn
import cv2
import numpy as np
import pybullet as pb
# Ensure project source root is in path
PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if PROJECT_SRC not in sys.path:
sys.path.insert(0, PROJECT_SRC)
from dotenv import load_dotenv
load_dotenv()
from main import PandaSimulation, _YCB_CATALOG
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
from llm_panda.plan_verifier import PlanVerifier
from llm_panda import config
import pybullet_data
from pybullet_object_models import ycb_objects
app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
# Serve static files from the frontend directory itself
static_dir = os.path.dirname(__file__)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
# Mount robot meshes and YCB object assets
panda_data_path = os.path.join(pybullet_data.getDataPath(), "franka_panda")
ycb_data_path = ycb_objects.getDataPath()
app.mount("/assets/panda", StaticFiles(directory=panda_data_path), name="panda")
app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb")
@app.get("/")
async def get():
html_file = os.path.join(static_dir, "index.html")
if os.path.exists(html_file):
with open(html_file, "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read(), status_code=200)
return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
# Global variables to track the current active simulation, lock, and thread lock
current_sim: Optional[PandaSimulation] = None
executor_lock = asyncio.Lock()
pybullet_lock = threading.RLock()
def get_init_payload(sim: PandaSimulation) -> dict:
"""Gathers the initial static geometry and YCB object definitions."""
with pybullet_lock:
objects_info = {}
if sim and sim.scene:
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
cls = sim.scene.get_class(oid)
folder = ""
for cat_name, cat_cls, cat_folder in _YCB_CATALOG:
if cat_name == name:
folder = cat_folder
break
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
# Query collision shape data for CoM-to-link offset
collision_data = pb.getCollisionShapeData(oid, -1, physicsClientId=sim.client)
coll_scale = [1.0, 1.0, 1.0]
coll_local_pos = [0.0, 0.0, 0.0]
coll_local_ori = [0.0, 0.0, 0.0, 1.0]
if collision_data:
cd = collision_data[0]
coll_scale = list(cd[3])
coll_local_pos = list(cd[5])
coll_local_ori = list(cd[6])
# Query visual shape data for exact dimensions/scales and offsets relative to link
visual_data = pb.getVisualShapeData(oid, physicsClientId=sim.client)
vis_scale = [1.0, 1.0, 1.0]
vis_local_pos = [0.0, 0.0, 0.0]
vis_local_ori = [0.0, 0.0, 0.0, 1.0]
if visual_data:
vd = visual_data[0]
vis_scale = list(vd[3])
# Transform visual frame to be relative to CoM: CoM_to_visual = CoM_to_link * link_to_visual
vis_pos_com, vis_ori_com = pb.multiplyTransforms(
coll_local_pos, coll_local_ori,
list(vd[5]), list(vd[6])
)
vis_local_pos = list(vis_pos_com)
vis_local_ori = list(vis_ori_com)
objects_info[name] = {
"class": cls,
"folder": folder,
"initial_pos": list(pos),
"initial_ori": list(ori),
"vis_scale": vis_scale,
"vis_local_pos": vis_local_pos,
"vis_local_ori": vis_local_ori,
"coll_scale": coll_scale,
"coll_local_pos": coll_local_pos,
"coll_local_ori": coll_local_ori
}
return {
"type": "init",
"table": {
"center": [config.TABLE_CENTER[0], config.TABLE_CENTER[1], config.TABLE_BASE_Z],
"half_extents": list(config.TABLE_HALF_EXTENTS),
"color": list(config.TABLE_COLOR),
"top_z": config.TABLE_TOP_Z
},
"tray": {
"position": list(config.TRAY_POSITION),
"half_extents": list(config.TRAY_HALF_EXTENTS),
"color": list(config.TRAY_COLOR)
},
"slots": {name: list(pos) for name, pos in config.SLOTS.items()},
"objects": objects_info
}
def get_simulation_state_payload(sim: PandaSimulation) -> dict:
"""Gathers the current robot joint positions and YCB object poses."""
with pybullet_lock:
if sim is None or sim.client is None or not pb.isConnected(sim.client):
return {}
# Read all joints (12 joints including arm joints and gripper fingers)
num_joints = pb.getNumJoints(sim.robot_id, physicsClientId=sim.client)
joints_state = []
for i in range(num_joints):
pos, _, _, _ = pb.getJointState(sim.robot_id, i, physicsClientId=sim.client)
joints_state.append(pos)
# Read objects pos/ori
objects_state = {}
for oid in sim.scene.object_ids:
name = sim.scene.get_name(oid)
pos, ori = pb.getBasePositionAndOrientation(oid, physicsClientId=sim.client)
objects_state[name] = {
"pos": list(pos),
"ori": list(ori)
}
return {
"type": "state",
"joints": joints_state,
"objects": objects_state
}
def set_pybullet_window_visibility(visible: bool):
"""Finds the PyBullet GUI window on Windows and sets its visibility by moving it on/off-screen."""
import sys
if sys.platform != "win32":
return False
import ctypes
import time
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
for _ in range(30):
found_hwnd = []
def foreach_window(hwnd, lParam):
length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
title = buff.value
if "bullet physics examplebrowser" in title.lower():
found_hwnd.append(hwnd)
return False
return True
ctypes.windll.user32.EnumWindows(EnumWindowsProc(foreach_window), 0)
if found_hwnd:
hwnd = found_hwnd[0]
# Ensure the window is shown/restored from minimized state first (SW_SHOW = 5)
ctypes.windll.user32.ShowWindow(hwnd, 5)
# SWP_NOSIZE = 0x0001, SWP_NOZORDER = 0x0004
if visible:
# Move window to visible region
ctypes.windll.user32.SetWindowPos(hwnd, 0, 100, 100, 0, 0, 0x0001 | 0x0004)
else:
# Move window far off-screen to hide it without destroying OpenGL context
ctypes.windll.user32.SetWindowPos(hwnd, 0, -10000, -10000, 0, 0, 0x0001 | 0x0004)
print(f"[Window Visibility] Set PyBullet window (HWND: {hwnd}) visibility to: {visible}", flush=True)
return True
time.sleep(0.1)
return False
def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successfully: bool):
"""Calculates rearrangement score based on final object locations and collisions."""
with pybullet_lock:
score = 100
details = []
# Check target placement if we had a plan
target_location = None
target_object = None
for step in plan:
if step.get("function") in ("place_at", "place_down", "move_to"):
args = step.get("args", {})
if "location_id" in args:
target_location = args["location_id"]
if step.get("function") == "pick_up":
target_object = step.get("args", {}).get("object_id")
if target_object and target_location:
obj_id = sim.scene.name_to_id(target_object)
if obj_id is not None:
pos, _ = pb.getBasePositionAndOrientation(obj_id)
current_loc = sim.scene.classify_location(pos)
if current_loc == target_location:
details.append(f"✅ **Đã đặt {target_object} đúng vị trí {target_location}**: +50 điểm")
else:
details.append(f"❌ **{target_object} chưa đến đúng vị trí {target_location} (đang ở {current_loc})**: -50 điểm")
score -= 50
else:
details.append(f"❌ **Không tìm thấy vật thể {target_object}**: -50 điểm")
score -= 50
else:
details.append("ℹ️ Không có yêu cầu di chuyển vật thể cụ thể nào được phát hiện.")
# Knock detection
knocked_count = 0
for oid in sim.scene.object_ids:
if oid == sim.scene.name_to_id(target_object):
continue
pos, _ = pb.getBasePositionAndOrientation(oid)
loc = sim.scene.classify_location(pos)
if loc == "elsewhere":
name = sim.scene.get_name(oid)
details.append(f"⚠️ **Vật thể '{name}' bị lệch khỏi vị trí quy định**: -15 điểm")
score -= 15
knocked_count += 1
if knocked_count == 0:
details.append("✅ **Không có vật thể nào khác bị va chạm hay xê dịch**: +30 điểm")
else:
score = max(0, score)
# Execution success
if executed_successfully:
details.append("✅ **Thực thi toàn bộ kế hoạch thành công**: +20 điểm")
else:
details.append("❌ **Thực thi gặp lỗi gián đoạn**: -30 điểm")
score -= 30
score = max(0, min(100, score))
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
return score, md
def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None):
"""Runs the planning, validation, execution with image streaming, and scoring."""
global current_sim
def log(message: str, step: Optional[int] = None):
try:
print(f"[WS Log] {message}", flush=True)
except Exception:
pass
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "log", "message": message, "step": step}),
loop
)
# Step 1: Planning
log("⏳ [1/5] Đang lập kế hoạch (LLM Planner)...")
if use_mock:
planner = RuleBasedPlanner()
log("✅ [1] Đang sử dụng RuleBasedPlanner (Offline)")
else:
api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY")
if not api_key:
log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.")
return
planner = RemoteLLMPlanner()
log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})")
with pybullet_lock:
current_sim.agent = LLMAgent(planner=planner)
# Define reachability check for scene state
def reachability_fn(oid):
cls = current_sim.scene.get_class(oid)
try:
grasp_pos, grasp_ori = current_sim.grasp_planner.compute_grasp_pose(oid, cls)
return current_sim.controller.is_reachable(grasp_pos, grasp_ori)
except Exception:
return False
carried_name = current_sim.scene.get_name(current_sim._carried) if current_sim._carried is not None else None
scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name)
state_text = json.dumps(scene_state, indent=2)
try:
with pybullet_lock:
plan = current_sim.agent.plan(user_prompt, state_text)
log(f"✅ [1] Đã tạo kế hoạch: {len(plan)} bước.")
except Exception as e:
log(f"❌ [1] Lập kế hoạch thất bại: {e}")
return
# Send steps to client
plan_steps = []
for idx, step in enumerate(plan, 1):
func = step.get("function")
args = step.get("args", {})
obj = args.get("object_id") or args.get("location_id") or ""
plan_steps.append({
"step": idx,
"skill": func,
"object": obj,
"args": args
})
asyncio.run_coroutine_threadsafe(
websocket.send_json({"type": "plan", "plan": plan_steps}),
loop
)
if not plan:
log("⚠️ [1] Kế hoạch rỗng.")
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, [], True)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
return
# Step 2: Validation
log("⏳ [2/5] Đang kiểm tra kế hoạch (Validator)...")
try:
with pybullet_lock:
warnings = PlanVerifier.check(plan, scene_state)
if not warnings:
log("✅ [2] Kế hoạch hợp lệ.")
else:
log(f"⚠️ [2] Validator phát hiện {len(warnings)} cảnh báo.")
for w in warnings:
log(f" - {w}")
except Exception as e:
log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}")
return
# Step 3: PyBullet Execution (Live!)
log("⏳ [3/5] Đang thực thi hành động của robot...")
# Hook pb.stepSimulation to capture states during movements
original_step = pb.stepSimulation
last_stream_time = [0.0]
throttle_interval = 0.033
def wrapped_step():
original_step()
if not current_sim.gui:
# Sleep slightly in headless mode to simulate arm speed and avoid freezing
time.sleep(0.001)
curr_time = time.time()
if curr_time - last_stream_time[0] >= throttle_interval:
last_stream_time[0] = curr_time
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(
websocket.send_json(state_payload),
loop
)
with pybullet_lock:
pb.stepSimulation = wrapped_step
executed_successfully = True
try:
# Trigger an initial simulation state transmission
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
for i, step in enumerate(plan, 1):
log(f"🚀 [3/5] Đang chạy bước {i}/{len(plan)}: {step['function']}")
with pybullet_lock:
current_sim._execute(step, verbose=True)
log("✅ [3] Thực thi thành công toàn bộ kế hoạch.")
except Exception as e:
log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
executed_successfully = False
finally:
with pybullet_lock:
pb.stepSimulation = original_step
# Send a final state to ensure visual sync
state_payload = get_simulation_state_payload(current_sim)
if state_payload:
asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
# Step 5: Scoring
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully)
asyncio.run_coroutine_threadsafe(
websocket.send_json({
"type": "result",
"score_display": score_md,
"score_value": score_val
}),
loop
)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
global current_sim
await websocket.accept()
loop = asyncio.get_running_loop()
# Retrieve user's desktop display preference from client query params
client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
# Force gui = False to run PyBullet completely headless (DIRECT mode)
gui = False
camera_state = {
"target": [0.5, 0.0, 0.3],
"dist": 1.3,
"yaw": 45.0,
"pitch": -35.0
}
async with executor_lock:
def init_sim():
global current_sim
with pybullet_lock:
is_connected = False
if current_sim is not None and current_sim.client is not None:
try:
is_connected = pb.isConnected(current_sim.client)
except Exception:
is_connected = False
if is_connected and current_sim.gui == gui:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
for _ in range(5):
pb.stepSimulation(physicsClientId=current_sim.client)
else:
if is_connected:
try:
current_sim.disconnect()
except Exception as e:
print(f"[Teardown Error] {e}")
current_sim = PandaSimulation(gui=gui, seed=0)
await asyncio.to_thread(init_sim)
# Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
# Send static scene configuration
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
await websocket.send_json(init_payload)
# Send the first simulation state to sync objects and joints
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
try:
while True:
data = await websocket.receive_text()
payload = json.loads(data)
p_type = payload.get("type")
if p_type == "run":
prompt = payload.get("prompt", "")
use_mock = payload.get("mock", False)
asyncio.create_task(
asyncio.to_thread(
run_pipeline_threadsafe,
websocket,
prompt,
loop,
use_mock
)
)
elif p_type == "reset":
async with executor_lock:
def reset_sim():
with pybullet_lock:
current_sim.reset_objects(seed=0)
current_sim.controller.reset_to_home()
await asyncio.to_thread(reset_sim)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
elif p_type == "update_object_pose":
name = payload.get("name")
pos = payload.get("pos")
ori = payload.get("ori")
async with executor_lock:
def move_obj():
with pybullet_lock:
oid = current_sim.scene.name_to_id(name)
if oid is not None:
pb.resetBasePositionAndOrientation(oid, pos, ori)
await asyncio.to_thread(move_obj)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
elif p_type == "update_joints":
joints_data = payload.get("joints")
async with executor_lock:
def move_joints():
with pybullet_lock:
for idx, q in enumerate(joints_data[:7]):
pb.resetJointState(current_sim.robot_id, idx, q)
if len(joints_data) >= 11:
pb.resetJointState(current_sim.robot_id, 9, joints_data[9])
pb.resetJointState(current_sim.robot_id, 10, joints_data[10])
await asyncio.to_thread(move_joints)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
elif p_type == "update_robot_ee":
pos = payload.get("pos")
async with executor_lock:
def move_robot_ee():
with pybullet_lock:
link_state = pb.getLinkState(
current_sim.robot_id,
current_sim.controller.ee_index,
physicsClientId=current_sim.client
)
ee_ori = link_state[1]
solution = pb.calculateInverseKinematics(
current_sim.robot_id,
current_sim.controller.ee_index,
pos,
ee_ori,
lowerLimits=current_sim.controller._lower_limits,
upperLimits=current_sim.controller._upper_limits,
jointRanges=current_sim.controller._joint_ranges,
restPoses=current_sim.controller._rest_poses,
maxNumIterations=300,
residualThreshold=1e-5,
physicsClientId=current_sim.client
)
for idx, q in enumerate(solution[:7]):
pb.resetJointState(
current_sim.robot_id,
idx,
q,
physicsClientId=current_sim.client
)
await asyncio.to_thread(move_robot_ee)
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
if state_payload:
await websocket.send_json(state_payload)
elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
pass
except WebSocketDisconnect:
print("Client disconnected")
except Exception as e:
print(f"WS Exception: {e}")
if __name__ == "__main__":
uvicorn.run("interactive_server:app", host="0.0.0.0", port=8000, reload=False)12# Created by pytest automatically.
*1234Signature: 8a477f597d28d172789f06886806bc55# This file is a cache directory tag created by pytest.# For information about cache directory tags, see:# https://bford.info/cachedir/spec.html12345678# pytest cache directory #
This directory contains data from the pytest's cache plugin,
which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
**Do not** commit this to version control.
See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.123{
"tests/test_new_pipeline.py::test_pipeline_executor_completes_pick_and_place": true
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253[
"tests/test_geofik.py::test_clamp_acos_input",
"tests/test_geofik.py::test_franka_geometry",
"tests/test_geofik.py::test_rotations",
"tests/test_geofik.py::test_wrap_angle",
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]",
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_di chuy\\u1ec3n lon s\\xfap v\\xe0o Slot_3]",
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_3_\\u0111\\u1ec3 v\\xe0o khay]",
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_4_\\u0111\\u1eb7t qu\\u1ea3 chu\\u1ed1i l\\xean b\\xe0n]",
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_5_\\u0111\\u1eb7t l\\xean b\\xe0n]",
"tests/test_llm_plan.py::test_rule_based_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]",
"tests/test_llm_plan.py::test_rule_based_planner_expected[Case_2_di chuy\\u1ec3n lon s\\xfap v\\xe0o Slot_3]",
"tests/test_llm_plan.py::test_rule_based_planner_expected[Case_3_\\u0111\\u1ec3 v\\xe0o khay]",
"tests/test_llm_plan.py::test_rule_based_planner_expected[Case_4_\\u0111\\u1eb7t qu\\u1ea3 chu\\u1ed1i l\\xean b\\xe0n]",
"tests/test_llm_plan.py::test_rule_based_planner_expected[Case_5_\\u0111\\u1eb7t l\\xean b\\xe0n]",
"tests/test_new_pipeline.py::test_contact_sampler_antipodal_constraints",
"tests/test_new_pipeline.py::test_grasp_candidate_generator",
"tests/test_new_pipeline.py::test_mesh_parser_loads_obj",
"tests/test_new_pipeline.py::test_pipeline_executor_completes_pick_and_place",
"tests/test_new_pipeline.py::test_rrt_connect_planner_finds_path",
"tests/test_occupancy.py::test_carried_object_is_excluded",
"tests/test_occupancy.py::test_carried_object_location_is_elsewhere",
"tests/test_occupancy.py::test_empty_table_is_fully_free",
"tests/test_occupancy.py::test_find_free_placements_avoids_occupied_region",
"tests/test_occupancy.py::test_object_larger_than_table_has_no_placement",
"tests/test_occupancy.py::test_occupied_area_tracks_object_footprint",
"tests/test_occupancy.py::test_reachable_filter_is_applied",
"tests/test_occupancy.py::test_tray_object_does_not_count_against_the_table",
"tests/test_pipeline.py::test_corridor_obstacle_detected",
"tests/test_pipeline.py::test_corridor_obstacle_not_detected_beyond_target",
"tests/test_pipeline.py::test_force_frictionless_is_finite_and_clamped",
"tests/test_pipeline.py::test_force_saturates_high_and_low",
"tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[-100.0]",
"tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[0.05]",
"tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[0.0]",
"tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[1.0]",
"tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[1000000.0]",
"tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[1000000000000.0]",
"tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[1e-09]",
"tests/test_pipeline.py::test_force_within_envelope_for_extreme_mass[50.0]",
"tests/test_pipeline.py::test_free_slot_prefers_reachable_order",
"tests/test_pipeline.py::test_grasp_offset_is_rotation_invariant[0.0]",
"tests/test_pipeline.py::test_grasp_offset_is_rotation_invariant[135.0]",
"tests/test_pipeline.py::test_grasp_offset_is_rotation_invariant[180.0]",
"tests/test_pipeline.py::test_grasp_offset_is_rotation_invariant[45.0]",
"tests/test_pipeline.py::test_grasp_offset_is_rotation_invariant[90.0]",
"tests/test_pipeline.py::test_grasp_rotation_actually_moves_world_point",
"tests/test_pipeline.py::test_grasp_survives_fast_translation",
"tests/test_pipeline.py::test_plan_verifier_detects_out_of_reach",
"tests/test_pipeline.py::test_rule_based_planner_two_step_pick_place",
"tests/test_task_nullspace.py::test_box_manifold_jacobian",
"tests/test_task_nullspace.py::test_cylinder_manifold_jacobian"
]1[]123456789101112131415161718192021222324252627282930313233343536373839404142434445# Sử dụng image Python 3.10 slim để nhẹ gọnFROM python:3.10-slim
# Biến môi trường để không tạo bytecode và log output trực tiếpENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1
# Thiết lập thư mục làm việcWORKDIR /app
# Cài đặt các gói thư viện hệ thống cần thiết cho PyBullet và hệ thống# libgl1-mesa-glx và libglib2.0-0 là cần thiết cho các thư viện C++ (như OpenCV/PyBullet)RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ libgl1-mesa-glx \ libglib2.0-0 \ && rm -rf /var/lib/apt/lists/*
# Copy file requirements.txt trước để tận dụng cache DockerCOPY requirements.txt .
# Cài đặt các thư viện PythonRUN pip install --no-cache-dir -r requirements.txt
# Copy toàn bộ mã nguồn vào imageCOPY . .
# Tạo một user không có quyền root theo yêu cầu bảo mật của Hugging Face Spaces (khuyến nghị)RUN useradd -m -u 1000 userUSER userENV HOME=/home/userENV PATH=/home/user/.local/bin:$PATH
# Thiết lập thư mục làm việc của user (Spaces thường map vào home của user)WORKDIR $HOME/app
# Copy lại code vào home của user và phân quyềnCOPY --chown=user . $HOME/app
# Mở cổng 7860 (cổng bắt buộc trên Hugging Face Spaces)EXPOSE 7860
# Lệnh khởi chạy server (sử dụng uvicorn chạy FastAPI app)# Lưu ý: "frontend.interactive_server:app" là tên module và biến chứa ứng dụng FastAPICMD ["uvicorn", "frontend.interactive_server:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163# Evaluation Evidences — LLM Planner Test Report
**Date:** 2026-06-19
**Environment:** Linux, Python 3.13.13, pytest 9.0.3
**Command executed:** `pytest -v tests/test_llm_plan.py`
**Test data:** [`tests/test_llm_expected.json`](tests/test_llm_expected.json) — 5 manual test cases
---
## 1. Test design (đúng yêu cầu)
| Loại | Số case | Case IDs |
|------|---------|----------|
| Happy path | 3 | 1, 2, 3 |
| Edge case | 1 | 4 |
| Error case | 1 | 5 |
| **Tổng** | **5** | |
Mỗi case ghi rõ **input** (`instruction` + `scene_state`) và **expected output** (`expected_plan`) trong
`tests/test_llm_expected.json`. Ba happy-path được chọn để mỗi case minh hoạ **một cấu trúc kế hoạch khác nhau**
(pick đơn lẻ / pick→slot→place / pick→tray→place), không trùng lặp.
---
## 2. Bằng chứng "không mock / không hardcode"
Đây là điểm cốt lõi của báo cáo. Mỗi case được kiểm chứng **độc lập bởi HAI bộ lập kế hoạch**, và cả hai
phải cho ra **đúng cùng một `expected_plan`** thì test mới pass:
1. **`RuleBasedPlanner`** — bộ suy luận xác định, chạy **offline** (không mạng, không API key).
*Test:* `test_rule_based_planner_expected`.
2. **`RemoteLLMPlanner`** — gọi **API LLM thật** qua endpoint OpenAI-compatible.
*Test:* `test_remote_llm_planner_expected`.
- **Model:** `google/gemma-3n-e2b-it`
- **Endpoint:** `https://integrate.api.nvidia.com/v1`
- Nếu **không** có API key trong môi trường, test này tự `skip` (xem `test_llm_plan.py:35`) —
tức là khi nó **PASSED** thì chắc chắn đã có một lệnh gọi mạng thật được thực hiện.
> Vì sao điều này chứng minh không mock: `expected_plan` **không** được nhúng vào prompt gửi cho LLM
> (xem `RemoteLLMPlanner.SYSTEM_PROMPT` — chỉ gửi scene + instruction). Việc một mô hình ngôn ngữ
> bên ngoài và một bộ luật offline **độc lập** cùng tạo ra y hệt chuỗi function-call cho thấy kết quả
> đến từ suy luận thực, không phải giá trị được hardcode.
### Lưu ý trung thực về error case
`RuleBasedPlanner` **không** kiểm tra trường `reachable`, nên "vật ngoài tầm với" **không** được dùng
làm error case (hai planner sẽ bất đồng). Ngoài ra, khi thử case "ra lệnh đặt xuống trong khi tay gắp
trống", LLM thật **không** tuân thủ ràng buộc và vẫn sinh `move_to + place_down` thay vì `[]` — nên case
đó cũng bị loại. Error case được giữ lại (Case 5: vật không tồn tại) là case mà **cả hai** planner
nhất quán trả về kế hoạch rỗng.
---
## 3. Kết quả chạy thực tế (Actual Output)
```text
============================= test session starts ==============================
platform linux -- Python 3.13.13, pytest-9.0.3, pluggy-1.6.0
rootdir: /media/minhnht31/data/vinuni/C2-App-151
configfile: pytest.ini
collected 10 items
tests/test_llm_plan.py::test_rule_based_planner_expected[Case_1_gắp quả chuối lên] PASSED [ 10%]
tests/test_llm_plan.py::test_rule_based_planner_expected[Case_2_di chuyển lon súp vào Slot_3] PASSED [ 20%]
tests/test_llm_plan.py::test_rule_based_planner_expected[Case_3_gắp bim bim bỏ vào khay] PASSED [ 30%]
tests/test_llm_plan.py::test_rule_based_planner_expected[Case_4_đặt vào khay] PASSED [ 40%]
tests/test_llm_plan.py::test_rule_based_planner_expected[Case_5_gắp con mèo lên] PASSED [ 50%]
tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_1_gắp quả chuối lên] PASSED [ 60%]
tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_di chuyển lon súp vào Slot_3] PASSED [ 70%]
tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_3_gắp bim bim bỏ vào khay] PASSED [ 80%]
tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_4_đặt vào khay] PASSED [ 90%]
tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_5_gắp con mèo lên] PASSED [100%]
============================= 10 passed in 14.95s ==============================
```
* **Tests collected:** 10 (5 cases × 2 planners)
* **Passed:** 10 · **Failed:** 0 · **Skipped:** 0
* **Status:** SUCCESS ✅ — `actual_plan == expected_plan` cho **mọi** case, ở **cả hai** planner.
---
## 4. Phân tích chi tiết từng case
Mỗi mục dưới đây: **Input** (instruction + trạng thái scene rút gọn) → **Expected = Actual** (kế hoạch
khớp ở cả `RuleBasedPlanner` offline và LLM thật).
### ✅ Case 1 — Happy path: pick đơn lẻ
* **Instruction:** `"gắp quả chuối lên"`
* **Input scene:** `carried_object = null`; banana@Slot_4, soup_can@Slot_2, chips_can@Slot_3.
* **Lý do:** Có động từ pick (`gắp`) + đ���i tượng (`quả chuối` → `banana`), **không** có đích đến →
chỉ sinh một bước `pick_up`, không tự thêm `move_to`/`place_down`.
* **Expected = Actual:**
```json
[
{"function": "pick_up", "args": {"object_id": "banana"}}
]
```
### ✅ Case 2 — Happy path: pick → slot → place
* **Instruction:** `"di chuyển lon súp vào Slot_3"`
* **Input scene:** `carried_object = null`; soup_can@Slot_5; `Slot_3` ∈ `free_slots`.
* **Lý do:** Tay gắp trống nên phải `pick_up` trước, rồi `move_to` đích `Slot_3` (đang trống) và
`place_down`.
* **Expected = Actual:**
```json
[
{"function": "pick_up", "args": {"object_id": "soup_can"}},
{"function": "move_to", "args": {"location_id": "Slot_3"}},
{"function": "place_down", "args": {}}
]
```
### ✅ Case 3 — Happy path: pick → tray → place
* **Instruction:** `"gắp bim bim bỏ vào khay"`
* **Input scene:** `carried_object = null`; chips_can@Slot_6; tray trống.
* **Lý do:** `bim bim` → `chips_can`; `khay` → `tray`. Tay gắp trống → `pick_up` rồi `move_to tray`
+ `place_down`.
* **Expected = Actual:**
```json
[
{"function": "pick_up", "args": {"object_id": "chips_can"}},
{"function": "move_to", "args": {"location_id": "tray"}},
{"function": "place_down", "args": {}}
]
```
### ✅ Case 4 — Edge case: tay gắp ĐANG giữ vật (one-gripper state)
* **Instruction:** `"đặt vào khay"`
* **Input scene:** `carried_object = "banana"` (đang cầm chuối); chỉ nêu đích, **không** nêu vật.
* **Lý do (edge):** Vì đã có vật trên tay (ràng buộc 1 gripper giữ tối đa 1 vật), planner **không**
được sinh `pick_up` mới — chỉ `move_to tray` + `place_down`. Đây là case dễ sai nếu planner máy móc
luôn bắt đầu bằng `pick_up`.
* **Expected = Actual:**
```json
[
{"function": "move_to", "args": {"location_id": "tray"}},
{"function": "place_down", "args": {}}
]
```
### ✅ Case 5 — Error case: vật không tồn tại
* **Instruction:** `"gắp con mèo lên"`
* **Input scene:** `carried_object = null`; scene chỉ có banana / soup_can / chips_can.
* **Lý do (error):** `con mèo` không khớp đối tượng nào trong scene và không có đích đến hợp lệ →
planner phải trả **kế hoạch rỗng** thay vì bịa ra hành động. Cả `RuleBasedPlanner` và LLM thật đều
trả `[]`.
* **Expected = Actual:**
```json
[]
```
---
## 5. Tự kiểm tra lại
```bash
# Offline (rule-based) — không cần API key:
pytest -v tests/test_llm_plan.py -k rule_based
# Có gọi LLM thật — cần OPENAI_API_KEY/LLM_API_KEY trong môi trường (hoặc .env):
pytest -v tests/test_llm_plan.py -k remote
```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295# GeoFIK: A fast and reliable geometric IK solver for the Franka arm
**GeoFIK** (**Geo**metric **F**ranka **IK**) is an analytical geometric solver for the inverse kinematics (IK) of the Franka arm. GeoFIK has the following advantages over other solvers:
* GeoFIK is ultra fast! It is an analytical solver, so the computational time is in the order of tens of microseconds on standard laptops. This is much faster than numerical solvers and, according to our experiments, also faster than the algebraic analytical solvers generated by IKFast.
* Unlike other analytical solvers, GeoFIK provides four different ways to resolve the 1-DOF redundancy of the Franka arm. Functions that solve the IK using $$q\_7$$, $$q\_6$$, $$q\_4$$ or the swivel angle as free variables are provided.
* Before computing the joint angles, GeoFIK finds the entire geometry of the arm by calculating the screw axes of the joints. Hence, the Jacobian matrices for each IK solution are returned at no significan extra computational cost.
* Due to its geometric nature, all possible solutions for the IK problem with redundancy solved are found. We proved that the maximum number is 8. Joint limits are checked before returning the solutions.
* All singularities are detected and handled efficiently using screw theory. The user can provide emergency values of joint angles to resolve the singularity.
For detailed information about the implementation, tests and experiments, see the preprint of our paper [arXiv:2503.03992v1](https://arxiv.org/abs/2503.03992v1).
## Requirements
This version has been tested with GCC compiler for C++ 17. The functions use the Eigen library which can be downloaded [here](https://eigen.tuxfamily.org). This version was tested with Eigen 3.4.0.
## Usage
### World and end-effector frames
GeoFIK uses frame $$E$$ as end-effector frame, and frame $$O$$ as world frame, as shown in the picture below. In [franka_ros](https://frankaemika.github.io/docs/franka_ros.html) $$E$$ and $$O$$ are named `panda_hand_tcp` and `panda_link0`, respectively.

Some applications, especially when the gripper is removed, may use the flage frame 8 (`panda_link8`) also called $$F$$ as end-effector frame. The transformation between this frame and frame $$E$$ is shown in the figure above and can be represented by the following transformation matrix $${}^{8}\_{E}$$𝐓:
```
T8E = [[ 0.70710678 0.70710678 0. 0. ]
[-0.70710678 0.70710678 0. 0. ]
[ 0. 0. 1. 0.1034 ]
[ 0. 0. 0. 1. ]]
```
Therefore, when working with frame 8, given a desired pose $${}^{O}\_{8}$$𝐓, the solver must be called with $${}^{O}\_{E}$$𝐓 = $${}^{O}\_{8}$$𝐓 $${}^{8}\_{E}$$𝐓.
### Functions provided
**Functions that only calculate joint angles**
All functions return the number of solutions found as an `unsigned int`. 8 solutions for joint angles are stored in an array `qsols` which is passed by reference by the caller. If a solution does not exist `nan` is assigned to all the entries of the corresponding row. If a joint angle is outside the joint limits in a found solution, `nan` is assigned to the joint angle.
---
```
unsigned int franka_ik_q7(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q7,
array<array<double, 7>, 8>& qsols,
const double q1_sing = PI / 2)
```
Solves the IK with $$q\_7$$ as free variable, generates joint angles of solutions.
* `r` position of frame $$E$$ in world frame $$O$$.
* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format).
* `q7` joint angle of joint 7 (radians).
* `qsols` array to store 8 solutions.
* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1))
---
```
unsigned int franka_ik_q6(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q6,
array<array<double, 7>, 8>& qsols,
const double q1_sing = PI / 2,
const double q7_sing = 0)
```
Solves the IK with $$q\_6$$ as free variable, generates joint angles of solutions.
* `r` position of frame $$E$$ in world frame $$O$$.
* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format).
* `q6` joint angle of joint 6 (radians).
* `qsols` array to store 8 solutions.
* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1))
* `q7_sing` [optional] emergency value of q7 in case of type-2 singularity (see our [paper](https://arxiv.org/abs/2503.03992v1)).
---
```
unsigned int franka_ik_q4(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q4,
array<array<double, 7>, 8>& qsols,
const double q1_sing = PI / 2,
const double q7_sing = 0)
```
Solves the IK with $$q\_4$$ as free variable, generates joint angles of solutions.
* `r` position of frame $$E$$ in world frame $$O$$.
* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format).
* `q4` joint angle of joint 4 (radians).
* `qsols` array to store 8 solutions.
* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1))
* `q7_sing` [optional] emergency value of q7 in case of type-2 singularity (see our [paper](https://arxiv.org/abs/2503.03992v1))
---
```
unsigned int franka_ik_swivel(const array<double, 3>& r,
const array<double, 9>& ROE,
const double theta,
array<array<double, 7>, 8>& qsols,
const double q1_sing = PI / 2,
const unsigned int n_points = 600)
```
Solves the IK with the swivel angle as free variable, generates joint angles of solutions. See our [paper](https://arxiv.org/abs/2503.03992v1) for the geometric definition of swivel angle used here. This is a numerical algorithm as no closed-form solution exists. However, since the solver only uses the strictly necessary geometric information in each iteration, the computational times on standard laptops range in the few hundreds of microseconds.
* `r` position of frame $$E$$ in world frame $$O$$.
* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format).
* `theta` swivel angle in radians (see paper for geometric defninition).
* `qsols` array to store 8 solutions.
* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1))
* `n_points` [optional] number of points to discretise the range of q7.
---
**Functions that calculate joint angles and Jacobian matrices**
The following functions include the optional parameter `Jacobian_ee` which allows to specify an end-effector frame for the Jacobian. Note that this can be different to the end-effector frame of the IK which is _always_ $$E$$. When working with frames $$F$$, $$8$$ or $$6$$, this parameter allows the user to get the Jacobian in the desired frame without having to transform it manually, saving computational time.
---
```
unsigned int franka_J_ik_q7(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q7,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles = false,
const char Jacobian_ee = 'E',
const double q1_sing = PI / 2)
```
Solves the IK with $$q\_7$$ as free variable, generates the joint angles and the Jacobians of all solutions.
* `r` position of frame $$E$$ in world frame $$O$$.
* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format).
* `q7` joint angle of joint 7 (radians).
* `Jsols` array to store 8 Jacobian solutions.
* `qsols` array to store 8 solutions.
* `joint_angles` [optional] if `false` only Jacobians are returned.
* `Jacobian_ee` [optional] end-effector frame of the Jacobian (`'E'`, `'F'`, `'8'` or `'6'`).
* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1))
---
```
unsigned int franka_J_ik_q6(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q6,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles = false,
const char Jacobian_ee = 'E',
const double q1_sing = PI / 2,
const double q7_sing = 0)
```
Solves the IK with $$q\_6$$ as free variable, generates the joint angles and the Jacobians of all solutions.
* `r` position of frame $$E$$ in world frame $$O$$.
* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format).
* `q6` joint angle of joint 6 (radians).
* `Jsols` array to store 8 Jacobian solutions.
* `qsols` array to store 8 solutions.
* `joint_angles` [optional] if `false` only Jacobians are returned.
* `Jacobian_ee` [optional] end-effector frame of the Jacobian (`'E'`, `'F'`, `'8'` or `'6'`).
* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1))
* `q7_sing` [optional] emergency value of $$q\_7$$ in case of type-2 singularity (see our [paper](https://arxiv.org/abs/2503.03992v1)).
---
```
unsigned int franka_J_ik_q4(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q4,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles = false,
const char Jacobian_ee = 'E',
const double q1_sing = PI / 2,
const double q7_sing = 0)
```
Solves the IK with $$q\_4$$ as free variable, generates the joint angles and the Jacobians of all solutions.
* `r` position of frame $$E$$ in world frame $$O$$.
* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format).
* `q4` joint angle of joint 4 (radians).
* `Jsols` array to store 8 Jacobian solutions.
* `qsols` array to store 8 solutions.
* `joint_angles` [optional] if `false` only Jacobians are returned.
* `Jacobian_ee` [optional] end-effector frame of the Jacobian (`'E'`, `'F'`, `'8'` or `'6'`).
* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1))
* `q7_sing` [optional] emergency value of $$q\_7$$ in case of type-2 singularity (see our [paper](https://arxiv.org/abs/2503.03992v1)).
---
```
unsigned int franka_J_ik_swivel(const array<double, 3>& r,
const array<double, 9>& ROE,
const double theta,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles = false,
const char Jacobian_ee = 'E',
const double q1_sing = PI / 2,
const unsigned int n_points = 600)
```
Solves the IK with the swivel angle as free variable, generates the joint angles and the Jacobians of all solutions.
* `r` position of frame $$E$$ in world frame $$O$$.
* `ROE` rotation matrix of frame $$E$$ with respect to frame $$O$$ (row-first format).
* `theta` swivel angle in radians (see paper for geometric defninition).
* `Jsols` array to store 8 Jacobian solutions.
* `qsols` array to store 8 solutions.
* `joint_angles` [optional] if `false` only Jacobians are returned.
* `Jacobian_ee` [optional] end-effector frame of the Jacobian (`'E'`, `'F'`, `'8'` or `'6'`).
* `q1_sing` [optional] emergency value of $$q\_1$$ in case of singularity at shoulder joints (type-1 singularity in our [paper](https://arxiv.org/abs/2503.03992v1))
* `n_points` [optional] number of points to discretise the range of $$q\_7$$.
---
**Other handy functions**
---
```
array<double, 7> J_to_q(const array<array<double, 6>, 7>& J,
const array<array<double, 3>, 3>& R,
const char ee = 'E')
```
Returns the joint angles given a Jacobian matrix and orientation of the end-effector frame.
* `J` transpose of Jacobian matrix.
* `R` the rotation matrix of end-effector frame with respect to frame $O$.
* `ee` [optional] name of end-effector frame (`'E'`, `'F'` or `'8'`).
---
```
array<array<double, 6>, 7> J_from_q(const array<double, 7>& q,
const char ee = 'E');
```
Computes the Jacobian given the joint angles.
* `q` joint angles, name of ee frame.
* `ee` [optional] Name of end-effector frame (`'E'`, `'F'`, `'8'`, ...,`'1'`).
---
```
Eigen::Matrix4d franka_fk(const array<double, 7>& q, const char ee = 'E');
```
Forward kinematics function. Returns the transformation matrix of the specified end-effector frame with respect to world frame $$O$$.
* `q` joint angles,
* `ee` name of ee frame (`'E'`, `'F'`, `'8'`, ...,`'1'`).
---
## Examples
The file `example_geofik.cpp` shows how to import GeoFIK, and how to call each of the solvers with case examples. For the fastest results, it is recommended to compile with optimization level 3, using a GCC compiler:
```
g++ example_geofik.cpp geofik.cpp -O3 -o example_geofik.exe
```
### Minimal example:
Consider the IK problem with end-effector position and orientation given by $${}^{O}\_{E}$$𝐓:
```
TOE = [[ 0.3522750000000002 0.8334980991082203 0.4256560000000001 -0.26617644]
[-0.6332361000000003 -0.12262271641620001 0.764183 0.31984145]
[ 0.6891402000000002 -0.5387433117066003 0.48460420000000004 0.76295964]
[ 0. 0. 0. 1. ]]
```
and a desired value for the fourth joint angle $$q\_4$$ = -2.3402. Then, the following code calls the solver and saves the solutions in the `qsols` array:
```
unsigned int nsols;
array<double, 9> ROE = { 0.3522750000000002, 0.8334980991082203, 0.4256560000000001,
-0.6332361000000003, -0.12262271641620001, 0.764183,
0.6891402000000002, -0.5387433117066003, 0.48460420000000004 };
array<double, 3> r = { -0.26617644,0.31984145,0.76295964 };
double q4 = -2.3402;
array<array<double, 7>, 8> qsols;
nsols = franka_ik_q4(r, ROE, q4, qsols);
```
The result is stored in `qsols`. `nan` is assigned to joint angles that are outside the joint limits, and to entire solutions that cannot be assamblied.
## Cite this work
This paper is currently under review. The ArXiv preprint can be found [here](https://arxiv.org/abs/2503.03992v1) and can be cited as:
* Lopez-Custodio PC, Gong Y, Figueredo LFC, “GeoFIK: A Fast and Reliable Geometric Solver for the IK of the Franka Arm based on Screw Theory Enabling Multiple Redundancy Parameters”, PREPRINT: arXiv:2503.03992v1 (2025)
```
@misc{lopezcustodio2025geofikfastreliablegeometric,
title={GeoFIK: A Fast and Reliable Geometric Solver for the IK of the Franka Arm based on Screw Theory Enabling Multiple Redundancy Parameters},
author={Pablo C. Lopez-Custodio and Yuhe Gong and Luis F. C. Figueredo},
year={2025},
eprint={2503.03992},
archivePrefix={arXiv},
primaryClass={cs.RO},
url={https://arxiv.org/abs/2503.03992},
}
```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273#include <iostream>
#include <array>
#include <vector>
#include <chrono>
#include "Eigen/Dense"
#include <iomanip>
using namespace std;
using namespace std::chrono;
#include "geofik.h"
// compile with: g++ example_geofik.cpp geofik.cpp -O3 -o example_geofik.exe
void print_results(const array<array<double, 7>, 8>& sols, const bool swivel = false, const double theta = 0.0);
void print_results_J(const array<array<array<double, 6>, 7>, 8>& Jsols, const array<array<double, 7>, 8>& qsols, const bool joint_angles, const bool swivel = false, const double theta = 0.0);
int main() {
unsigned int nsols = 0;
array<double, 9> ROE; // rotation matrix of frame E with respect to frame O
array<double, 3> r; // position vector of frame E with respect to frame O
double q7, q6, q4, theta; // free variables
bool joint_angles;
array<array<double, 7>, 8> qsols;
array<array<array<double, 6>, 7>, 8> Jsols;
high_resolution_clock::time_point start = high_resolution_clock::now();
high_resolution_clock::time_point end = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(end - start);
// TEST franka_ik_q7()
cout << endl << "=======================================================" << endl;
cout << "franka_ik_q7()" << endl;
cout << "=======================================================" << endl;
ROE = {0.6688331000000003,0.3170534383478098,0.6724130000000006,-0.6398146000000005,-0.2150772409286401,0.7378204999999999,0.3785492999999998,-0.9236984268883508,0.05900459999999996};
r = {0.61674948,0.32278029,0.56790512};
q7 = -0.37218362471412003 ;
start = high_resolution_clock::now();
nsols = franka_ik_q7(r, ROE, q7, qsols);
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
print_results(qsols);
cout << "number of solutions found:" << nsols;
cout << endl << "duration (only q):" << duration.count() << endl;
// second run
start = high_resolution_clock::now();
nsols = franka_ik_q7(r, ROE, q7, qsols);
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
cout << endl << "duration in second run:" << duration.count() << endl;
// TEST franka_ik_q6()
/*
cout << endl << "=======================================================" << endl;
cout << "franka_ik_q6()" << endl;
cout << "=======================================================" << endl;
//test parallel case:
ROE = {-0.6575819999999999,0.22565347159914026,0.7187951000000004,0.5218621000000001,-0.5516899774048302,0.6506136000000007,0.5433652999999999,0.8029437126709107,0.24502140000000006};
r = {0.65543571,0.5899264,0.59988412};
q6 = 3.141592653589793 ;
//test non-parallel case:
//ROE = { -0.1192774000000002,0.8774473359489797,0.4646064,0.47138319999999956,0.4618910375721001,-0.7513018999999999,-0.8738254000000001,0.12939431432541965,-0.4687071000000001 };
//r = { 0.43749227,-0.73488144,0.4951873 };
//q6 = 2.6179938779914944;
start = high_resolution_clock::now();
nsols = franka_ik_q6(r, ROE, q6, qsols);
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
print_results(qsols);
cout << "number of solutions found:" << nsols;
cout << endl << "duration:" << duration.count() << endl;
// second run
start = high_resolution_clock::now();
nsols = franka_ik_q6(r, ROE, q6, qsols);
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
cout << endl << "duration in second run:" << duration.count() << endl;
*/
// TEST franka_ik_q4()
/*
cout << endl << "=======================================================" << endl;
cout << "franka_ik_q4()" << endl;
cout << "=======================================================" << endl;
ROE = { 0.3522750000000002,0.8334980991082203,0.4256560000000001,-0.6332361000000003,-0.12262271641620001,0.764183,0.6891402000000002,-0.5387433117066003,0.48460420000000004 };
r = { -0.26617644,0.31984145,0.76295964 };
q4 = -2.3401949461109055;
start = high_resolution_clock::now();
nsols = franka_ik_q4(r, ROE, q4, qsols);
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
print_results(qsols);
cout << "number of solutions found:" << nsols;
cout << endl << "duration:" << duration.count() << endl;
//second run
start = high_resolution_clock::now();
nsols = franka_ik_q4(r, ROE, q4, qsols);
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
cout << endl << "duration in second run:" << duration.count() << endl;
*/
// TEST franka_ik_swivel()
/*
cout << endl << "=======================================================" << endl;
cout << "franka_ik_swivel()" << endl;
cout << "=======================================================" << endl;
ROE = { -0.5878745000000002,-0.7990239702980599,-0.12635000000000007,-0.16720689999999983,0.2728366411870001,-0.9474186000000001,0.7914831,-0.5358366439507003,-0.293996 };
r = { -0.15116089,-0.397596,0.47386124 };
theta = -0.3490658503988659;
start = high_resolution_clock::now();
nsols = franka_ik_swivel(r, ROE, theta, qsols);
end = high_resolution_clock::now();
print_results(qsols, true, theta);
duration = duration_cast<microseconds>(end - start);
cout << "Number of solutions found: " << nsols;
cout << endl << "duration:" << duration.count() << endl;
*/
// TEST franka_J_ik_q7()
/*
cout << endl << "=======================================================" << endl;
cout << "franka_J_ik_q7()" << endl;
cout << "=======================================================" << endl;
ROE = {0.6688331000000003,0.3170534383478098,0.6724130000000006,-0.6398146000000005,-0.2150772409286401,0.7378204999999999,0.3785492999999998,-0.9236984268883508,0.05900459999999996};
r = {0.61674948,0.32278029,0.56790512};
q7 = -0.37218362471412003 ;
ROE = { -0.189536, 0.0420467, -0.980973,
0.404078, -0.907217, -0.116958,
-0.894873, -0.418557, 0.15496 };
r = { 0.23189, -0.0815989, 0.607269 };
q7 = 0.771925;
joint_angles = true;
start = high_resolution_clock::now();
nsols = franka_J_ik_q7(r, ROE, q7, Jsols, qsols, joint_angles);
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
print_results_J(Jsols, qsols, joint_angles);
cout << "number of solutions found: " << nsols;
cout << endl<<"duration:" << duration.count() << endl;
*/
// TEST franka_J_ik_q6()
/*
cout << endl << "=======================================================" << endl;
cout << "franka_J_ik_q6()" << endl;
cout << "=======================================================" << endl;
//test parallel case:
//ROE = { -0.6575819999999999,0.22565347159914026,0.7187951000000004,0.5218621000000001,-0.5516899774048302,0.6506136000000007,0.5433652999999999,0.8029437126709107,0.24502140000000006 };
//r = { 0.65543571,0.5899264,0.59988412 };
//q6 = 3.141592653589793;
//test non-parallel case:
ROE = {-0.1192774000000002,0.8774473359489797,0.4646064,0.47138319999999956,0.4618910375721001,-0.7513018999999999,-0.8738254000000001,0.12939431432541965,-0.4687071000000001};
r = {0.43749227,-0.73488144,0.4951873};
q6 = 2.6179938779914944 ;
joint_angles = true;
start = high_resolution_clock::now();
nsols = franka_J_ik_q6(r, ROE, q6, Jsols, qsols, joint_angles, '8');
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
print_results_J(Jsols, qsols, joint_angles);
cout << "number of solutions found: " << nsols;
cout << endl << "duration:" << duration.count() << endl;
*/
// TEST franka_J_ik_q4()
/*
cout << endl << "=======================================================" << endl;
cout << "franka_J_ik_q4()" << endl;
cout << "=======================================================" << endl;
ROE = { 0.3522750000000002,0.8334980991082203,0.4256560000000001,-0.6332361000000003,-0.12262271641620001,0.764183,0.6891402000000002,-0.5387433117066003,0.48460420000000004 };
r = { -0.26617644,0.31984145,0.76295964 };
q4 = -2.3401949461109055;
joint_angles = true;
start = high_resolution_clock::now();
nsols = franka_J_ik_q4(r, ROE, q4, Jsols, qsols, joint_angles);
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
print_results_J(Jsols, qsols, joint_angles);
cout << "number of solutions found: " << nsols;
cout << endl << "duration:" << duration.count() << endl;
*/
// TEST franka_J_ik_swivel()
/*
cout << endl << "=======================================================" << endl;
cout << "franka_J_ik_swivel()" << endl;
cout << "=======================================================" << endl;
ROE = { -0.5878745000000002,-0.7990239702980599,-0.12635000000000007,-0.16720689999999983,0.2728366411870001,-0.9474186000000001,0.7914831,-0.5358366439507003,-0.293996 };
r = { -0.15116089,-0.397596,0.47386124 };
theta = -0.3490658503988659;
joint_angles = true;
start = high_resolution_clock::now();
nsols = franka_J_ik_swivel(r, ROE, theta, Jsols, qsols, joint_angles, 'F');
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
print_results_J(Jsols, qsols, joint_angles);
cout << "number of solutions found: " << nsols;
cout << endl << "duration:" << duration.count() << endl;
*/
return 0;
}
// functions to print results
void print_results(const array<array<double, 7>, 8>& sols, const bool swivel, const double theta) {
cout << "SOLUTIONS ...................." << endl;
Eigen::Matrix4d T;
double theta_res;
bool sol_in_lims;
for (int i = 0; i < sols.size(); i++) {
sol_in_lims = true;
cout << endl << "solution " << i + 1 << endl;
for (int j = 0; j < 7; j++) {
cout << "q_" << j + 1 << " = " << sols[i][j] * 180 / PI << endl;
if (isnan(sols[i][j]))
sol_in_lims = false;
}
// only print retrieved T if all joints are within limits:
if (sol_in_lims) {
T = franka_fk(sols[i]);
cout << "Forward kinematics for this solution:" << endl;
cout << T;
cout << endl;
if (swivel) {
theta_res = franka_swivel(sols[i]);
cout << "theta = " << theta_res << "rad or " << theta_res * 180 / PI << "degs" << endl;
cout << "error = " << theta - theta_res << "degs" <<endl;
}
}
}
}
void print_results_J(const array<array<array<double, 6>, 7>, 8>& Jsols, const array<array<double, 7>, 8>& qsols, const bool joint_angles, const bool swivel, const double theta) {
cout << "SOLUTIONS ...................." << endl;
double theta_res;
std::cout << std::fixed << std::setprecision(5);
bool sol_in_lims;
Eigen::Matrix4d T;
for (int i = 0; i < 8; i++) {
cout << endl << "solution " << i + 1 << endl;
cout << "Jacobian:" << endl;
for (int j = 0; j < 7; j++) {
for (int k = 0; k < 6; k++) {
cout << std::setw(10) << Jsols[i][j][k];
}
cout << endl;
}
if (joint_angles) {
sol_in_lims = true;
cout << "joint angles" << endl;
for (int j = 0; j < 7; j++) {
cout << "q_" << j + 1 << " = " << qsols[i][j] * 180 / PI << endl;
if (isnan(qsols[i][j]))
sol_in_lims = false;
}
if (sol_in_lims) {
T = franka_fk(qsols[i]);
cout << "Forward kinematics for this solution:" << endl;
cout << T;
cout << endl;
if (swivel) {
theta_res = franka_swivel(qsols[i]);
cout << "theta = " << theta_res << "rad or " << theta_res * 180 / PI << "degs" << endl;
cout << "error = " << theta - theta_res << endl;
}
}
}
cout << endl;
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108/**
* @file geofik.cpp
* @brief functions for the IK of the Franka arm.
*
* @details notation:
* - `r_PQ_O`: position vector of point P with respect to point Q measured in frame O.
* - `ROF`: Rotation matrix representing the orientation of a frame F with respect to frame O.
*
* @author Pablo Lopez-Custodio
* @date 2025-02-08
* @version 1.0
*/
#include "geofik.h"
#include <iostream>
#include <vector>
#define d1 0.333
#define d3 0.316
#define a4 0.0825
#define a5 0.0825
#define d5 0.384
#define a7 0.088
// dE = 0.107 + 0.1034
#define dE 0.2104
// b1 = sqrt(d3*d3 + a4*a4)
#define b1 0.3265918706887849
// b2 = sqrt(d5*d5 + a5*a5)
#define b2 0.39276233271534583
// beta1 = arctan(a4/d3)
#define beta1 0.25537561488738186
// beta2 = arctan(a5/d5)
#define beta2 0.21162680876562978
// toletance for entering in singularity mode
# define SING_TOL 1e-5
// error threshold for swivel angle solver
// # define ERR_THRESH 0.01 // this slightly smaller than 1deg
# define ERR_THRESH 0.002 // this slightly smaller than (3deg)*(3deg)
// max number of points in discretisation for swivel angle solver
const unsigned int MAX_N_POINTS = 1000;
const array<double, 7> q_low = { -2.8973, -1.7628, -2.8973, -3.0718, -2.8973, -0.0175, -2.8973 };
const array<double, 7> q_up = { 2.8973, 1.762, 2.8973, -0.0698, 2.8973, 3.7525, 2.8973 };
const array<double, 7> q_mid = { 0.0, 0.0, 0.0, -1.5708, 0.0, 1.8675, 0.0 };
// Jacobian at home configuration (orientation only)
const Eigen::Matrix<double, 3, 7> J0_S({ {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{0.0, 1.0, 0.0, -1.0, 0.0, -1.0, 0.0},
{1.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0} });
Eigen::Matrix3d tmp_R;
Eigen::Matrix<double, 3, 7> tmp_J;
Eigen::Matrix<double, 6, 7> tmp_J_6d;
Eigen::Matrix<double, 3, 7> J_old;
Eigen::Matrix<double, 3, 4> J_old_low;
Eigen::Vector3d s;
void R_axis_angle(const Eigen::Vector3d& s, double theta) {
double x = s[0];
double y = s[1];
double z = s[2];
double ct = cos(theta);
double st = sin(theta);
double one_minus_ct = 1 - ct;
tmp_R << ct + x * x * one_minus_ct, x* y* one_minus_ct - z * st, x* z* one_minus_ct + y * st,
y* x* one_minus_ct + z * st, ct + y * y * one_minus_ct, y* z* one_minus_ct - x * st,
z* x* one_minus_ct - y * st, z* y* one_minus_ct + x * st, ct + z * z * one_minus_ct;
}
void R_axis_angle(const array<double, 3>& s, double theta) {
double x = s[0];
double y = s[1];
double z = s[2];
double ct = cos(theta);
double st = sin(theta);
double one_minus_ct = 1 - ct;
tmp_R << ct + x * x * one_minus_ct, x* y* one_minus_ct - z * st, x* z* one_minus_ct + y * st,
y* x* one_minus_ct + z * st, ct + y * y * one_minus_ct, y* z* one_minus_ct - x * st,
z* x* one_minus_ct - y * st, z* y* one_minus_ct + x * st, ct + z * z * one_minus_ct;
}
array<double, 3> Cross(const Eigen::Vector3d& u, const Eigen::Vector3d& v) {
return array<double, 3> {u[1] * v[2] - v[1] * u[2], v[0] * u[2] - u[0] * v[2], u[0] * v[1] - v[0] * u[1]};
}
array<double, 3> Cross(const array<double, 3>& u, const array<double, 3>& v) {
return array<double, 3> {u[1] * v[2] - v[1] * u[2], v[0] * u[2] - u[0] * v[2], u[0] * v[1] - v[0] * u[1]};
}
array<double, 3> Cross(const array<double, 3>& u, const Eigen::Vector3d& v) {
return array<double, 3> {u[1] * v[2] - v[1] * u[2], v[0] * u[2] - u[0] * v[2], u[0] * v[1] - v[0] * u[1]};
}
array<double, 3> Cross(const Eigen::Vector3d& u, const array<double, 3>& v) {
return array<double, 3> {u[1] * v[2] - v[1] * u[2], v[0] * u[2] - u[0] * v[2], u[0] * v[1] - v[0] * u[1]};
}
void Cross_(const array<double, 3>& u, const Eigen::Vector3d& v, array<double, 3>& w) {
w[0] = u[1] * v[2] - v[1] * u[2];
w[1] = v[0] * u[2] - u[0] * v[2];
w[2] = u[0] * v[1] - v[0] * u[1];
}
void Cross_(const array<double, 3>& u, const array<double, 3>& v, array<double, 3>& w) {
w[0] = u[1] * v[2] - v[1] * u[2];
w[1] = v[0] * u[2] - u[0] * v[2];
w[2] = u[0] * v[1] - v[0] * u[1];
}
double Dot(const Eigen::Vector3d& u, const Eigen::Vector3d& v) {
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
}
double Dot(const array<double, 3>& u, const array<double, 3>& v) {
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
}
double Dot(const array<double, 3>& u, const Eigen::Vector3d& v) {
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
}
double Dot(const Eigen::Vector3d& u, const array<double, 3>& v) {
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
}
double Norm(const Eigen::Vector3d& u) {
return sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]);
}
double Norm(const array<double, 3>& u) {
return sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]);
}
void J_dir(const array<double, 3>& s2, const array<double, 3>& s3, const array<double, 3>& s4, const array<double, 3>& s5, const array<double, 3>& s6, const array<double, 3>& s7) {
tmp_J << 0, s2[0], s3[0], s4[0], s5[0], s6[0], s7[0],
0, s2[1], s3[1], s4[1], s5[1], s6[1], s7[1],
1, s2[2], s3[2], s4[2], s5[2], s6[2], s7[2];
}
void save_J_sol(const array<double, 3>& s2,
const array<double, 3>& s3,
const array<double, 3>& s4,
const array<double, 3>& s5,
const array<double, 3>& s6,
const array<double, 3>& s7,
const array<double, 3>& r4,
const array<double, 3>& r5,
const array<double, 3>& r_EO_O,
array<array<array<double, 6>, 7>, 8>& Jsols,
const int index,
const char Jacobian_ee) {
// saves the two Jacobian solutions for the given joint axes at Jsols[2*index] and Jsols[2*index+1].
// Jacobian_ee is the frame of the Jacobian end-effector ('6', '8', 'F' or 'E')
// r4 = r_4S_O
// r5 = r_5S_O
array<double, 3> r_1ee_O, r_4ee_O, r_5ee_O;
if (Jacobian_ee == '6') {
// r_P6_O = r_PS_O + r_S6_O
// r_PS_O - r_6S_O remember r_6S_O = r_5S_O
r_1ee_O = { -r5[0], -r5[1], -r5[2] };
r_4ee_O = { r4[0] - r5[0], r4[1] - r5[1] , r4[2] - r5[2] };
r_5ee_O = { 0, 0 , 0 };
}
else if (Jacobian_ee == '8' || Jacobian_ee == 'F') {
// r_PF_O = r_PE_O + r_EF_O
// = r_PS_O - rEO_O + rSO_O + r_EF_O
// = r_PS_O - rEO_O + (0,0,d1) + 0.1034*s7_O
r_1ee_O = { -r_EO_O[0] + 0.1034 * s7[0], -r_EO_O[1] + 0.1034 * s7[1], d1 - r_EO_O[2] + 0.1034 * s7[2] };
r_4ee_O = { r4[0] - r_EO_O[0] + 0.1034 * s7[0], r4[1] - r_EO_O[1] + 0.1034 * s7[1], d1 + r4[2] - r_EO_O[2] + 0.1034 * s7[2] };
r_5ee_O = { r5[0] - r_EO_O[0] + 0.1034 * s7[0], r5[1] - r_EO_O[1] + 0.1034 * s7[1], d1 + r5[2] - r_EO_O[2] + 0.1034 * s7[2] };
}
else {
// r_PE_O = r_PS_O + r_SE_O
// = r_PS_O - r_ES_O
// = r_PS_O - (r_EO_O + r_OS_O) = r_PS_O - r_EO_O + r_SO_O
r_1ee_O = { -r_EO_O[0], -r_EO_O[1], d1 - r_EO_O[2] };
r_4ee_O = { r4[0] - r_EO_O[0], r4[1] - r_EO_O[1], d1 + r4[2] - r_EO_O[2] };
r_5ee_O = { r5[0] - r_EO_O[0], r5[1] - r_EO_O[1], d1 + r5[2] - r_EO_O[2] };
}
array<double, 3> m;
Jsols[2 * index][0] = { 0, 0, 1, r_1ee_O[1], -r_1ee_O[0], 0 }; // r_1ee_O x (0,0,1) = (r_1ee_O[1], -r_1ee_O[0], 0)
Jsols[2 * index + 1][0] = { 0, 0, 1, r_1ee_O[1], -r_1ee_O[0], 0 };
Cross_(r_1ee_O, s2, m); // r_2ee_O = r_1ee_O
Jsols[2 * index][1] = { s2[0], s2[1], s2[2], m[0], m[1], m[2] };
Jsols[2 * index + 1][1] = { -s2[0], -s2[1], -s2[2], -m[0], -m[1], -m[2] }; // second solution of spherical shoulder
Cross_(r_1ee_O, s3, m); // r3_ee = r1_ee
Jsols[2 * index][2] = { s3[0], s3[1], s3[2], m[0], m[1], m[2] };
Jsols[2 * index + 1][2] = { s3[0], s3[1], s3[2], m[0], m[1], m[2] };
Cross_(r_4ee_O, s4, m);
Jsols[2 * index][3] = { s4[0], s4[1], s4[2], m[0], m[1], m[2] };
Jsols[2 * index + 1][3] = { s4[0], s4[1], s4[2], m[0], m[1], m[2] };
Cross_(r_5ee_O, s5, m);
Jsols[2 * index][4] = { s5[0], s5[1], s5[2], m[0], m[1], m[2] };
Jsols[2 * index + 1][4] = { s5[0], s5[1], s5[2], m[0], m[1], m[2] };
Cross_(r_5ee_O, s6, m); // r6 = r5
Jsols[2 * index][5] = { s6[0], s6[1], s6[2], m[0], m[1], m[2] };
Jsols[2 * index + 1][5] = { s6[0], s6[1], s6[2], m[0], m[1], m[2] };
if (Jacobian_ee == '6') {
Jsols[2 * index][6] = { 0, 0, 0, 0, 0, 0 };
Jsols[2 * index + 1][6] = { 0, 0, 0, 0, 0, 0 };
}
else {
Jsols[2 * index][6] = { s7[0], s7[1], s7[2], 0, 0, 0 };
Jsols[2 * index + 1][6] = { s7[0], s7[1], s7[2], 0, 0, 0 };
}
}
double signed_angle(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, const Eigen::Vector3d& s) {
return atan2(Dot(Cross(v1, v2), s), Dot(v1, v2));
}
double signed_angle(const array<double, 3>& v1, const array<double, 3>& v2, const array<double, 3>& s) {
//return atan2(s[2]*(v1[0]*v2[1] - v1[1]*v2[0]) - s[1]*(v1[0]*v2[2] - v1[2]*v2[0]) + s[0]*(v1[1]*v2[2] - v1[2]*v2[1]), v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]);
return atan2(Dot(Cross(v1, v2), s), Dot(v1, v2));
}
void check_limits(array<double, 7>& q, int n) {
for (int i=0; i < n; i++) {
q[i] = q_mid[i] + atan2(sin(q[i] - q_mid[i]), cos(q[i] - q_mid[i]));
if (q[i] < q_low[i] || q[i] > q_up[i]) q[i] = NAN;
}
}
// whole rotational part of J
array<double, 6> q_from_J(const Eigen::Matrix<double, 3, 7>& J) {
const int dof = 7;
array<double, dof - 1> q;
J_old = J0_S; // [3,dof]
for (int i = 0; i < dof - 1; i++) {
s = J.col(i);
q[i] = signed_angle(J_old.col(i + 1), J.col(i + 1), s);
if (i == dof - 2) break;
R_axis_angle(s, q[i]);
J_old.block(0, i + 1, 3, dof - (i + 1)) = tmp_R * J_old.block(0, i + 1, 3, dof - (i + 1));
}
return q;
}
// lower rotationa part of J
array<double, 3> q_from_low_J(const Eigen::Matrix<double, 3, 7>& J) {
const int dof = 4;
array<double, dof - 1> q;
J_old_low = J0_S.block(0, 0, 3, dof); // [3,dof]
for (int i = 0; i < dof - 1; i++) {
s = J.col(i);
q[i] = signed_angle(J_old_low.col(i + 1), J.col(i + 1), s);
if (i == dof - 2) break;
R_axis_angle(s, q[i]);
J_old_low.block(0, i + 1, 3, dof - (i + 1)) = tmp_R * J_old_low.block(0, i + 1, 3, dof - (i + 1));
}
return q;
}
// whole Jacobian and q
array<double, 7> J_to_q(const array<array<double, 6>, 7>& J, const array<array<double, 3>, 3>& R, const char ee) {
// J is the transpose of the Jacobian
// R is the rotation matrix of frame ee
// ee must be a frame attached to the gripper: "E", "F" or "8".
Eigen::Matrix<double, 3, 7> Jrot;
Jrot << J[0][0], J[1][0], J[2][0], J[3][0], J[4][0], J[5][0], J[6][0],
J[0][1], J[1][1], J[2][1], J[3][1], J[4][1], J[5][1], J[6][1],
J[0][2], J[1][2], J[2][2], J[3][2], J[4][2], J[5][2], J[6][2];
const int dof = 7;
array<double, dof> q;
array<double, 3> i7, ie, s6, s7;
s6 = { J[5][0] , J[5][1] , J[5][2] };
s7 = { J[6][0] , J[6][1] , J[6][2] };
Cross_(s6, s7, i7);
ie = { R[0][0], R[1][0], R[2][0] };
q[6] = signed_angle(i7, ie, s7) + (ee == 'E' ? -PI / 4 : 0);
J_old = J0_S; // [3,dof]
for (int i = 0; i < dof - 1; i++) {
s = Jrot.col(i);
q[i] = signed_angle(J_old.col(i + 1), Jrot.col(i + 1), s);
if (i == dof - 2) break;
R_axis_angle(s, q[i]);
J_old.block(0, i + 1, 3, dof - (i + 1)) = tmp_R * J_old.block(0, i + 1, 3, dof - (i + 1));
}
return q;
}
void column_1s_times_vec(const array<double, 9>& R, const array<double, 3>& v, array<double, 3>& res) {
res[0] = R[0] * v[0] + R[1] * v[1] + R[2] * v[2];
res[1] = R[3] * v[0] + R[4] * v[1] + R[5] * v[2];
res[2] = R[6] * v[0] + R[7] * v[1] + R[8] * v[2];
}
void rotate_by_axis_angle(const array<double, 3>& s, const double theta, const array<double, 3>& v, array<double, 3>& res) {
R_axis_angle(s, theta);
res[0] = tmp_R(0, 0) * v[0] + tmp_R(0, 1) * v[1] + tmp_R(0, 2) * v[2];
res[1] = tmp_R(1, 0) * v[0] + tmp_R(1, 1) * v[1] + tmp_R(1, 2) * v[2];
res[2] = tmp_R(2, 0) * v[0] + tmp_R(2, 1) * v[1] + tmp_R(2, 2) * v[2];
}
Eigen::Matrix4d T_rpy(const double r, const double p, const double y, const double px, const double py, const double pz) {
Eigen::Matrix4d T;
T << cos(p) * cos(y), cos(y)* sin(p)* sin(r) - cos(r) * sin(y), sin(r)* sin(y) + cos(r) * cos(y) * sin(p), px,
cos(p)* sin(y), cos(r)* cos(y) + sin(p) * sin(r) * sin(y), cos(r)* sin(p)* sin(y) - cos(y) * sin(r), py,
-sin(p), cos(p)* sin(r), cos(p)* cos(r), pz,
0, 0, 0, 1;
return T;
}
Eigen::Matrix4d T_rot_z(const double theta, const double px = 0.0, const double py = 0.0, const double pz = 0.0) {
Eigen::Matrix4d T;
T << cos(theta), -sin(theta), 0, px,
sin(theta), cos(theta), 0, py,
0, 0, 1, pz,
0, 0, 0, 1;
return T;
}
Eigen::Matrix<double, 6, 6> Adj_trans(const double x, const double y, const double z) {
Eigen::Matrix<double, 6, 6> Adj = Eigen::Matrix<double, 6, 6>::Identity();
Adj.block<3, 3>(3, 0) << 0, -z, y,
z, 0, -x,
-y, x, 0;
return Adj;
}
void get_frame_transforms(array<Eigen::Matrix4d, 9>& Ti, const array<double, 7>& q) {
// gets all the transformation matrices of adjascent frames for joint angles q
Ti[0] = T_rpy(0, 0, 0, 0, 0, 0.333) * T_rot_z(q[0]); // T01
Ti[1] = T_rpy(-PI / 2, 0, 0, 0, 0, 0) * T_rot_z(q[1]); // T12
Ti[2] = T_rpy(PI / 2, 0, 0, 0, -0.316, 0) * T_rot_z(q[2]); // T23
Ti[3] = T_rpy(PI / 2, 0, 0, 0.0825, 0, 0) * T_rot_z(q[3]); // T34
Ti[4] = T_rpy(-PI / 2, 0, 0, -0.0825, 0.384, 0) * T_rot_z(q[4]); // T45
Ti[5] = T_rpy(PI / 2, 0, 0, 0, 0, 0) * T_rot_z(q[5]); // T56
Ti[6] = T_rpy(PI / 2, 0, 0, 0.088, 0, 0) * T_rot_z(q[6]); // T67
Ti[7] = T_rpy(0, 0, 0, 0, 0, 0.107); // T78
Ti[8] = T_rot_z(-PI / 4, 0, 0, 0.1034); // T8E
}
unsigned int ee_number(const char ee) {
if (ee == 'E') // ask default value first
return 9;
if (ee == 'F' || ee == '8')
return 8;
if (ee == '1' || ee == '2' || ee == '3' || ee == '4' || ee == '5' || ee == '6' || ee == '7')
return ee - '0';
return 9;
}
array<array<double, 6>, 7> J_from_q(const array<double, 7>& q, const char ee) {
// returns J^T for a given vector of joint angles, q. The end-effector frame is ee
// OUTPUT: J^T \in R^(7,6): array<array<double,6>,7>
// INPUT: q \in R^7, array<double,7>
// ee
Eigen::Vector3d s, r, m;
unsigned int een = ee_number(ee);
unsigned int cols = een >= 7 ? 7 : een;
Eigen::Matrix<double, 6, 7> J6d;
array<Eigen::Matrix4d, 9> Ti;
get_frame_transforms(Ti, q);
Eigen::Matrix4d T = Ti[0]; // T01
J6d.col(0) << 0, 0, 1, 0, 0, 0;
for (int i = 1; i < een; i++) {
T = T * Ti[i]; // T0{i+1} = T0{i}*T{i}{i+1}
if (i < 7) {
s = T.block<3, 1>(0, 2);
r = T.block<3, 1>(0, 3);
m = r.cross(s);
J6d.col(i) << s[0], s[1], s[2], m[0], m[1], m[2];
}
}
J6d = Adj_trans(-T(0, 3), -T(1, 3), -T(2, 3)) * J6d;
array<array<double, 6>, 7> Jarr;
for (int i = 0; i < cols; i++)
Jarr[i] = { J6d(0,i), J6d(1,i), J6d(2,i), J6d(3,i), J6d(4,i), J6d(5,i) };
for (int i = cols; i < 7; i++)
Jarr[i] = { 0, 0, 0, 0, 0, 0 };
return Jarr;
}
Eigen::Matrix4d franka_fk(const array<double, 7>& q, const char ee) {
// Forward kinematics function
// INPUT: joint angles q, and end effector name ee
// OUTPUT: TOee is the transformation matrix of frame ee w.r.t. frame O
unsigned int een = ee_number(ee);
array<Eigen::Matrix4d, 9> Ti;
get_frame_transforms(Ti, q);
Eigen::Matrix4d TOee = Ti[0];
for (int i = 1; i < een; i++)
TOee = TOee * Ti[i];
return TOee;
}
void franka_fk_all_frames(array<Eigen::Matrix4d, 9>& Ts, const array<double, 7>& q) {
// Forward kinematics function saving in Ts the transformation matrices of all frames w.r.t. frame O
array<Eigen::Matrix4d, 9> Ti;
get_frame_transforms(Ti, q);
Ts[0] = Ti[0];
for (int i = 1; i < 9; i++)
Ts[i] = Ts[i - 1] * Ti[i];
}
unsigned int franka_ik_q7(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q7,
array<array<double, 7>, 8>& qsols,
const double q1_sing) {
// IK with q7 as free variable
// INPUT: r = r_EO_O, position of frame E in frame O
// ROE, orientation of frame E in frame O
// q7, joint angle of joint 7
// qsols, array to store 8 solutions
// q1_sing, emergency value of q1 in case of singularity at shoulder joints.
// OUTPUT: number of solutions found.
// ri = r_iS_O, i = 1,2,3,4,5,6,7
// si = s_i_O
Eigen::Vector3d i_E_O(ROE[0], ROE[3], ROE[6]);
array<double, 3> k_E_O = { ROE[2], ROE[5], ROE[8] };
R_axis_angle(k_E_O, -(q7 - PI / 4));
Eigen::Vector3d i_6_O = tmp_R * i_E_O;
array<double, 3> s6;
Cross_(k_E_O, i_6_O, s6);
array<double, 3> r6 = { r[0] - dE * k_E_O[0] - a7 * i_6_O[0], r[1] - dE * k_E_O[1] - a7 * i_6_O[1], r[2] - d1 - dE * k_E_O[2] - a7 * i_6_O[2] };
double l = Norm(r6);
double tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2);
if (tmp > 1) {
if ((tmp - 1) * (tmp - 1) < SING_TOL* SING_TOL) {
tmp = 1;
}
else {
cout << "ERROR: unable to assembly kinematic chain";
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
}
return 0;
}
}
double actmp = acos(tmp);
double alpha2 = beta2 + actmp;
array<double, 3> k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l };
array<double, 3> i_C_O;
Cross_(k_C_O, s6, i_C_O);
tmp = Norm(i_C_O);
i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp };
array<double, 3> j_C_O;
Cross_(k_C_O, i_C_O, j_C_O);
double ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2];
double rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2];
array<array<double, 3>, 4> s5s;
double sa2, ca2;
int n_alphs = 1;
unsigned int n_sols = 0;
if (d3 + d5 < l && l < b1 + b2) n_alphs = 2;
double v[3];
for (int i = 0; i < n_alphs; i++) {
sa2 = sin(alpha2);
ca2 = cos(alpha2);
tmp = -rz * ca2 / (ry * sa2);
if (tmp * tmp > 1){
if (fabs(fabs(tmp) - 1.0) < 0.04)
tmp = tmp > 0.0 ? 1.0 : -1.0;
else
continue;
}
tmp = asin(tmp);
v[0] = -sa2 * cos(tmp);
v[1] = -sa2 * sin(tmp);
v[2] = -ca2;
s5s[n_sols] = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2],
i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2],
i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] };
tmp = 2 * sa2 * cos(tmp);
//s5[n_sols+1] = s5s[n_sols] + (2*sa2*cos(tmp)*i_C_O);
s5s[n_sols + 1] = { s5s[n_sols][0] + tmp * i_C_O[0],
s5s[n_sols][1] + tmp * i_C_O[1],
s5s[n_sols][2] + tmp * i_C_O[2] };
n_sols += 2;
alpha2 = beta2 - actmp;
}
array<double, 6> sol1;
array<double, 3> sol2;
array<double, 3> s4, r4, s3, s2, s5;
for (int i = 0; i < n_sols; i++) {
s5 = s5s[i];
Cross_(s5, r6, s4);
tmp = Norm(s4);
s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp };
Cross_(s5, s4, r4);
r4 = { r6[0] - d5 * s5[0] + a5 * r4[0], r6[1] - d5 * s5[1] + a5 * r4[1], r6[2] - d5 * s5[2] + a5 * r4[2] };
R_axis_angle(s4, beta1);
s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2],
tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2],
tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] };
tmp = Norm(s3);
s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp };
tmp = s3[1] * s3[1] + s3[0] * s3[0];
if (tmp > SING_TOL*SING_TOL) {
s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 };
}
else {
s2 = { sin(q1_sing), cos(q1_sing), 0 };
}
J_dir(s2, s3, s4, s5, s6, k_E_O);
sol1 = q_from_J(tmp_J);
tmp_J.col(1) = -1 * tmp_J.col(1);
sol2 = q_from_low_J(tmp_J);
qsols[2 * i] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 };
check_limits(qsols[2 * i], 7);
qsols[2 * i + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * i][3], qsols[2 * i][4], qsols[2 * i][5], qsols[2 * i][6] };
check_limits(qsols[2 * i + 1], 3);
}
for (int i = 2 * n_sols; i < 8; i++)
fill(qsols[i].begin(), qsols[i].end(), NAN);
return 2 * n_sols;
}
unsigned int franka_ik_q4(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q4,
array<array<double, 7>, 8>& qsols,
const double q1_sing,
const double q7_sing) {
// IK with q4 as free variable
// INPUT: r = r_EO_O, position of frame E in frame O
// ROE, orientation of frame E in frame O (row-first format)
// q4, joint angle of joint 4
// qsols, array to store 8 solutions
// q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
// q7_sing, emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity).
// OUTPUT: number of solutions found.
// ri = r_iS_O, i = 1,2,3,4,5,6,7
// si = s_i_O
array<double, 3> r_ES_O = { r[0], r[1], r[2] - d1 };
array<double, 3> tmp_v = { r_ES_O[1] * ROE[8] - r_ES_O[2] * ROE[5],
r_ES_O[2] * ROE[2] - r_ES_O[0] * ROE[8],
r_ES_O[0] * ROE[5] - r_ES_O[1] * ROE[2] };
if (tmp_v[0] * tmp_v[0] + tmp_v[1] * tmp_v[1] + tmp_v[2] * tmp_v[2] < SING_TOL)
return franka_ik_q7(r, ROE, q7_sing, qsols, q1_sing);
array<double, 3> r_O7S_O = { r_ES_O[0] - dE * ROE[2], r_ES_O[1] - dE * ROE[5], r_ES_O[2] - dE * ROE[8] };
array<double, 3> r_O7S_E = { ROE[0] * r_O7S_O[0] + ROE[3] * r_O7S_O[1] + ROE[6] * r_O7S_O[2],
ROE[1] * r_O7S_O[0] + ROE[4] * r_O7S_O[1] + ROE[7] * r_O7S_O[2],
ROE[2] * r_O7S_O[0] + ROE[5] * r_O7S_O[1] + ROE[8] * r_O7S_O[2] };
double alpha = q4 + beta1 + beta2 - PI;
double lo2 = b1 * b1 + b2 * b2 - 2 * b1 * b2 * cos(alpha);
double lp2 = lo2 - r_O7S_E[2] * r_O7S_E[2];
// fixed triangle condition
if (lp2 < 0) {
if (lp2 * lp2 < SING_TOL * SING_TOL)
lp2 = 0;
else {
cout << "\nERROR: unable to assembly kinematic chain\n";
for (int i = 0; i < 8; ++i)
fill(qsols[i].begin(), qsols[i].end(), NAN);
return 0;
}
}
double gamma2 = beta2 + asin(b1 * sin(alpha) / sqrt(lo2));
double cg2 = cos(gamma2), sg2 = sin(gamma2);
double Lp2 = r_O7S_E[0] * r_O7S_E[0] + r_O7S_E[1] * r_O7S_E[1], phi = atan2(-r_O7S_E[1], -r_O7S_E[0]);
double tmp = (Lp2 + a7 * a7 - lp2) / (2 * sqrt(Lp2) * a7);
// fixed condition
if (tmp > 1.0) {
if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL)
tmp = 1.0;
else {
cout << "\nERROR: unable to assembly kinematic chain\n";
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
}
return 0;
}
}
/*
if ((tmp - 1) * (tmp - 1) < SING_TOL*SING_TOL)
tmp = 1.0;
if (tmp > 1.0) {
cout << "\nERROR: unable to assembly kinematic chain\n";
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
}
return 0;
}
*/
double psi = acos(tmp), ry, rz;
double q7s[2] = { -phi - psi - 3 * PI / 4, -phi + psi - 3 * PI / 4 };
double gammas[2] = { 0,0 };
unsigned int ind = 0;
array<double, 3> s2, s3, s4, s5, s6, r4, r6, i_C_O, j_C_O, k_C_O;
array<double, 6> sol1;
array<double, 3> sol2;
for (auto q7 : q7s) {
tmp_v = { cos(-q7 + 3 * PI / 4), sin(-q7 + 3 * PI / 4), 0 };
s6 = { ROE[0] * tmp_v[0] + ROE[1] * tmp_v[1], ROE[3] * tmp_v[0] + ROE[4] * tmp_v[1], ROE[6] * tmp_v[0] + ROE[7] * tmp_v[1] };
tmp_v = { -a7 * cos(-q7 + PI / 4), -a7 * sin(-q7 + PI / 4), 0 };
r6 = { ROE[0] * tmp_v[0] + ROE[1] * tmp_v[1], ROE[3] * tmp_v[0] + ROE[4] * tmp_v[1], ROE[6] * tmp_v[0] + ROE[7] * tmp_v[1] };
r6 = { r6[0] + r_O7S_O[0], r6[1] + r_O7S_O[1], r6[2] + r_O7S_O[2] };
tmp = Norm(r6);
k_C_O = { -r6[0] / tmp, -r6[1] / tmp, -r6[2] / tmp };
Cross_(k_C_O, s6, i_C_O);
tmp = Norm(i_C_O);
i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp };
Cross_(k_C_O, i_C_O, j_C_O);
ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2];
rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2];
tmp = -rz * cg2 / (ry * sg2);
if (tmp * tmp > 1) continue;
tmp = asin(tmp);
gammas[0] = tmp;
gammas[1] = PI - tmp;
for (auto gamma : gammas) {
tmp_v = { -sg2 * cos(gamma), -sg2 * sin(gamma), -cg2 };
s5 = { i_C_O[0] * tmp_v[0] + j_C_O[0] * tmp_v[1] + k_C_O[0] * tmp_v[2],
i_C_O[1] * tmp_v[0] + j_C_O[1] * tmp_v[1] + k_C_O[1] * tmp_v[2],
i_C_O[2] * tmp_v[0] + j_C_O[2] * tmp_v[1] + k_C_O[2] * tmp_v[2] };
Cross_(s5, r6, s4);
tmp = Norm(s4);
s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp };
Cross_(s5, s4, r4);
r4 = { r6[0] - d5 * s5[0] + a5 * r4[0], r6[1] - d5 * s5[1] + a5 * r4[1], r6[2] - d5 * s5[2] + a5 * r4[2] };
R_axis_angle(s4, beta1);
s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2],
tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2],
tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] };
tmp = Norm(s3);
s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp };
tmp = s3[1] * s3[1] + s3[0] * s3[0];
if (tmp > SING_TOL* SING_TOL)
s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 };
else
s2 = { sin(q1_sing), cos(q1_sing), 0 };
J_dir(s2, s3, s4, s5, s6, array<double, 3>{ROE[2], ROE[5], ROE[8]});
sol1 = q_from_J(tmp_J);
tmp_J.col(1) = -1 * tmp_J.col(1);
sol2 = q_from_low_J(tmp_J);
qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 };
check_limits(qsols[2 * ind], 7);
qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] };
check_limits(qsols[2 * ind + 1], 3);
ind++;
}
}
for (int i = 2 * ind; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
}
return 2 * ind;
}
unsigned int franka_ik_q6_parallel(const array<double, 3>& r_ES_O,
const array<double, 9>& ROE,
const int sgn,
array<array<double, 7>, 8>& qsols,
const double q1_sing) {
// Parallel case of the IK with q6 as free variable. Only called by franka_ik_q6(), not by the user.
// INPUT: r_ES_O, ROE, sgn = sign(cos(q6)), qsols, q1_sing.
// OUTPUT: number of solutions found.
// NOTATION:
// ri = r_iS_O, i = 1,2,3,4,5,6,7
// si = s_i_O
// Q is a frame that is parallel to frame E and has origin at Q
array<double, 3> s7 = { ROE[2],ROE[5],ROE[8] };
array<double, 3> r_QS_O = { r_ES_O[0] + (-dE + sgn * d5) * s7[0], r_ES_O[1] + (-dE + sgn * d5) * s7[1], r_ES_O[2] + (-dE + sgn * d5) * s7[2] };
array<double, 3> r_SQ_Q = { -ROE[0] * r_QS_O[0] - ROE[3] * r_QS_O[1] - ROE[6] * r_QS_O[2],
-ROE[1] * r_QS_O[0] - ROE[4] * r_QS_O[1] - ROE[7] * r_QS_O[2],
-ROE[2] * r_QS_O[0] - ROE[5] * r_QS_O[1] - ROE[8] * r_QS_O[2] };
double tmp = b1 * b1 - r_SQ_Q[2] * r_SQ_Q[2];
if (tmp * tmp < SING_TOL*SING_TOL)
tmp = 0;
if (tmp < 0) {
cout << "ERROR: unable to assembly kinematic chain";
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
}
return 0;
}
double lp = sqrt(tmp);
array<double, 3> r_SpQ_Q = { r_SQ_Q[0], r_SQ_Q[1], 0 };
double l_SpQ = sqrt(r_SQ_Q[0] * r_SQ_Q[0] + r_SQ_Q[1] * r_SQ_Q[1]);
double alphas[2], Ls[2];
double q7;
Ls[0] = a5 + lp;
Ls[1] = a5 - lp;
array<double, 3> tmp_v, r_O6pQ_Q, i_4_Q, r_O4Q_Q, s6_Q, r_O6_Q, s4_Q, s3_Q, s2, s3, s4, s5, s6;
Eigen::Matrix<double, 3, 4> partial_J_Q, partial_J_O;
Eigen::Matrix3d ROQ;
ROQ << ROE[0], ROE[1], ROE[2],
ROE[3], ROE[4], ROE[5],
ROE[6], ROE[7], ROE[8];
const array<double, 3> k{ {0,0,1} };
array<double, 3> s5_Q{ {0,0,-1.0 * sgn} };
int tmp_sgn;
unsigned int ind = 0;
array<double, 6> sol1;
array<double, 3> sol2;
for (auto L : Ls) {
tmp = (-L * L + a7 * a7 + l_SpQ * l_SpQ) / (2 * a7 * l_SpQ);
if ((tmp - 1) * (tmp - 1) < SING_TOL)
tmp = 1;
else if ((tmp + 1) * (tmp + 1) < SING_TOL)
tmp = -1;
if (tmp * tmp > 1)
continue;
alphas[0] = acos(tmp);
alphas[1] = -acos(tmp);
for (auto alpha : alphas) {
rotate_by_axis_angle(k, alpha, r_SpQ_Q, r_O6pQ_Q);
r_O6pQ_Q = { a7 * r_O6pQ_Q[0] / l_SpQ, a7 * r_O6pQ_Q[1] / l_SpQ, a7 * r_O6pQ_Q[2] / l_SpQ };
i_4_Q = { r_SpQ_Q[0] - r_O6pQ_Q[0], r_SpQ_Q[1] - r_O6pQ_Q[1], r_SpQ_Q[2] - r_O6pQ_Q[2] };
tmp = Norm(i_4_Q);
tmp_sgn = L < 0 ? -1 : 1;
i_4_Q = { tmp_sgn * i_4_Q[0] / tmp, tmp_sgn * i_4_Q[1] / tmp, tmp_sgn * i_4_Q[2] / tmp };
r_O4Q_Q = { r_O6pQ_Q[0] + a5 * i_4_Q[0], r_O6pQ_Q[1] + a5 * i_4_Q[1], r_O6pQ_Q[2] + a5 * i_4_Q[2] };
Cross_(r_O6pQ_Q, k, s6_Q);
r_O6_Q = { r_O6pQ_Q[0], r_O6pQ_Q[1], r_O6pQ_Q[2] - sgn * d5 };
Cross_(i_4_Q, s5_Q, s4_Q);
tmp_v = { r_O4Q_Q[0] - r_SQ_Q[0], r_O4Q_Q[1] - r_SQ_Q[1], r_O4Q_Q[2] - r_SQ_Q[2] };
rotate_by_axis_angle(s4_Q, beta1, tmp_v, s3_Q);
tmp = Norm(s3_Q);
partial_J_Q << s3_Q[0] / tmp, s4_Q[0], s5_Q[0], s6_Q[0],
s3_Q[1] / tmp, s4_Q[1], s5_Q[1], s6_Q[1],
s3_Q[2] / tmp, s4_Q[2], s5_Q[2], s6_Q[2];
partial_J_O = ROQ * partial_J_Q;
s3 = { partial_J_O(0,0), partial_J_O(1,0), partial_J_O(2,0) };
s4 = { partial_J_O(0,1), partial_J_O(1,1), partial_J_O(2,1) };
s5 = { partial_J_O(0,2), partial_J_O(1,2), partial_J_O(2,2) };
s6 = { partial_J_O(0,3), partial_J_O(1,3), partial_J_O(2,3) };
q7 = atan2(r_O6pQ_Q[1], -r_O6pQ_Q[0]) + PI / 4;
tmp = s3[1] * s3[1] + s3[0] * s3[0];
if (tmp > SING_TOL* SING_TOL)
s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 };
else
s2 = { sin(q1_sing), cos(q1_sing), 0 };
J_dir(s2, s3, s4, s5, s6, s7);
sol1 = q_from_J(tmp_J);
tmp_J.col(1) = -1 * tmp_J.col(1);
sol2 = q_from_low_J(tmp_J);
qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 };
check_limits(qsols[2 * ind], 7);
qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] };
check_limits(qsols[2 * ind + 1], 3);
ind++;
}
}
for (int i = 2 * ind; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
}
return 2 * ind;
}
unsigned int franka_ik_q6(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q6,
array<array<double, 7>, 8>& qsols,
const double q1_sing,
const double q7_sing) {
// IK with q6 as free variable
// INPUT: r = r_EO_O, position of frame E in frame O
// ROE, orientation of frame E in frame O (row-first format)
// q6, joint angle of joint 6
// qsols, array to store 8 solutions
// q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
// q7_sing, emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity).
// OUTPUT: number of solutions found.
// NOTATION:
// ri = r_iS_O, i = 1,2,3,4,5,6,7
// si = s_i_O
array<double, 3> r_ES_O = { r[0], r[1], r[2] - d1 };
array<double, 3> tmp_v = { r_ES_O[1] * ROE[8] - r_ES_O[2] * ROE[5],
r_ES_O[2] * ROE[2] - r_ES_O[0] * ROE[8],
r_ES_O[0] * ROE[5] - r_ES_O[1] * ROE[2] };
if (tmp_v[0] * tmp_v[0] + tmp_v[1] * tmp_v[1] + tmp_v[2] * tmp_v[2] < SING_TOL)
return franka_ik_q7(r, ROE, q7_sing, qsols, q1_sing);
if (sin(q6) * sin(q6) < SING_TOL* SING_TOL) // PARALLEL CASE:
return franka_ik_q6_parallel(r_ES_O, ROE, cos(q6) >= 0 ? 1 : -1, qsols, q1_sing);
// NON-PARALLEL CASE:
array<double, 3> s7 = { ROE[2],ROE[5],ROE[8] };
double gamma1 = PI - q6;
double cg1 = cos(gamma1);
double sg1 = sin(gamma1);
array<double, 3> r_O7S_O = { r_ES_O[0] - dE * ROE[2], r_ES_O[1] - dE * ROE[5], r_ES_O[2] - dE * ROE[8] };
array<double, 3> r_PS_O = { r_O7S_O[0] + (a7 / tan(gamma1)) * s7[0], r_O7S_O[1] + (a7 / tan(gamma1)) * s7[1], r_O7S_O[2] + (a7 / tan(gamma1)) * s7[2] };
double lP = Norm(r_PS_O);
double lC = a7 / sg1;
double Cx = -(ROE[0] * r_PS_O[0] + ROE[3] * r_PS_O[1] + ROE[6] * r_PS_O[2]);
double Cy = -(ROE[1] * r_PS_O[0] + ROE[4] * r_PS_O[1] + ROE[7] * r_PS_O[2]);
double Cz = -(ROE[2] * r_PS_O[0] + ROE[5] * r_PS_O[1] + ROE[8] * r_PS_O[2]);
double c = sqrt(a5 * a5 + (lC + d5) * (lC + d5));
double tmp = (-b1 * b1 + lP * lP + c * c) / (2 * lP * c);
//cout << "tmp at triangle: " << tmp;
if (tmp > 1.0) {
if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL)
tmp = 1.0;
else {
cout << "ERROR: unable to assembly kinematic chain";
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
}
return 0;
}
}
double tau = acos(tmp);
unsigned int n_gamma_sols = 1;
if ((d3 + d5 + lC < lP) && (lP < b1 + c)) n_gamma_sols = 2;
double gamma2s[2];
if (d5 < -lC)
gamma2s[0] = tau + atan(a5 / (d5 + lC)) + PI;
else
gamma2s[0] = tau + atan(a5 / (d5 + lC));
if (n_gamma_sols > 1)
gamma2s[1] = gamma2s[0] - 2 * tau;
array<array<double, 3>, 4> s5s;
double q7s[4];
double d, u1, u2;
unsigned int n_sols = 0;
for (int i = 0; i < n_gamma_sols; i++) {
d = lP * cos(gamma2s[i]);
tmp = (d + Cz * cg1) / (sqrt(Cx * Cx * sg1 * sg1 + Cy * Cy * sg1 * sg1));
//cout << "tmp at cone: " << tmp;
if (tmp > 1) {
if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL)
tmp = 1;
else
continue;
}
else if (tmp < -1) {
if ((tmp + 1) * (tmp + 1) < SING_TOL * SING_TOL)
tmp = -1;
else
continue;
}
u1 = asin(tmp);
u2 = atan2(Cx * sg1, Cy * sg1);
//cout << "u1 = " << u1 << endl;
//cout << "u2 = " << u2 << endl;
q7s[n_sols] = 5*PI/4 - u1 + u2;
tmp_v = { -sg1 * cos(u1 - u2), -sg1 * sin(u1 - u2), cg1 };
column_1s_times_vec(ROE, tmp_v, s5s[n_sols]);
n_sols++;
q7s[n_sols] = PI/4 + u1 + u2;
tmp_v = { -sg1 * cos(PI - u1 - u2), -sg1 * sin(PI - u1 - u2), cg1 };
column_1s_times_vec(ROE, tmp_v, s5s[n_sols]);
n_sols++;
}
array<double, 3> s2, s3, s4, s6, r4, r6;
array<double, 6> sol1;
array<double, 3> sol2;
for (int i=0; i < n_sols; i++) {
r6 = { r_PS_O[0] - lC * s5s[i][0], r_PS_O[1] - lC * s5s[i][1], r_PS_O[2] - lC * s5s[i][2] };
tmp_v = { r_O7S_O[0] - r6[0], r_O7S_O[1] - r6[1], r_O7S_O[2] - r6[2] };
Cross_(s7, tmp_v, s6);
tmp = Norm(s6);
s6 = { s6[0] / tmp,s6[1] / tmp,s6[2] / tmp };
Cross_(s5s[i], r6, s4);
tmp = Norm(s4);
s4 = { s4[0] / tmp,s4[1] / tmp,s4[2] / tmp };
Cross_(s5s[i], s4, tmp_v);
r4 = { r6[0] - d5 * s5s[i][0] + a5 * tmp_v[0], r6[1] - d5 * s5s[i][1] + a5 * tmp_v[1], r6[2] - d5 * s5s[i][2] + a5 * tmp_v[2] };
rotate_by_axis_angle(s4, beta1, r4, s3);
tmp = Norm(s3);
s3 = { s3[0] / tmp,s3[1] / tmp,s3[2] / tmp };
tmp = s3[1] * s3[1] + s3[0] * s3[0];
if (tmp > SING_TOL*SING_TOL)
s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 };
else
s2 = { sin(q1_sing), cos(q1_sing), 0 };
J_dir(s2, s3, s4, s5s[i], s6, s7);
sol1 = q_from_J(tmp_J);
tmp_J.col(1) = -1 * tmp_J.col(1);
sol2 = q_from_low_J(tmp_J);
qsols[2 * i] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7s[i] };
check_limits(qsols[2 * i], 7);
qsols[2 * i + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * i][3], qsols[2 * i][4], qsols[2 * i][5], qsols[2 * i][6] };
check_limits(qsols[2 * i + 1], 3);
}
for (int i = 2 * n_sols; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
}
return 2 * n_sols;
}
// FUNCTIONS FOR SWIVEL ANGLE
array<double, 2> theta_err_from_q7_explore_around_sing(double& q7m,
const double theta,
const Eigen::Vector3d& i_E_O,
const array<double, 3>& k_E_O,
Eigen::Vector3d& i_6_O,
const array<double, 3>& n1_O,
const array<double, 3>& r_O7S_O,
const array<double, 3>& u_O7S_O,
const double q7step,
const unsigned int n_fine) {
array<double, 3> s6, r6, k_C_O, i_C_O, j_C_O, s4, r4, n2_O, v;
array<double, 2> errs;
array<array<double, 3>, 2> s5s;
double l, tmp, actmp, alpha2, ry, rz, sa2, ca2;
double best_q7 = q7m;
array<double, 2> min_errs = { 1e15 , 1e15 };
double min_err = 1e15;
double q7up = q7m + q7step / 2;
double q7j = q7m - q7step / 2;
while (q7j < q7up) {
R_axis_angle(k_E_O, -(q7j - PI / 4));
i_6_O = tmp_R * i_E_O;
Cross_(k_E_O, i_6_O, s6);
r6 = { r_O7S_O[0] - a7 * i_6_O[0], r_O7S_O[1] - a7 * i_6_O[1], r_O7S_O[2] - a7 * i_6_O[2] };
l = Norm(r6);
tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2);
if (tmp > 1) {
if ((tmp - 1) * (tmp - 1) < SING_TOL)
tmp = 1;
else{
q7j += q7step / (2 * n_fine);
continue;
}
}
actmp = acos(tmp);
alpha2 = beta2 + actmp;
k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l };
i_C_O = Cross(k_C_O, s6);
tmp = Norm(i_C_O);
i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp };
Cross_(k_C_O, i_C_O, j_C_O);
ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2];
rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2];
sa2 = sin(alpha2);
ca2 = cos(alpha2);
tmp = -rz * ca2 / (ry * sa2);
if (tmp * tmp > 1)
{
q7j += q7step / (2 * n_fine);
continue;
}
tmp = asin(tmp);
v = { -sa2 * cos(tmp), -sa2 * sin(tmp), -ca2 };
s5s[0] = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2],
i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2],
i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] };
tmp = 2 * sa2 * cos(tmp);
s5s[1] = { s5s[0][0] + tmp * i_C_O[0],
s5s[0][1] + tmp * i_C_O[1],
s5s[0][2] + tmp * i_C_O[2] };
for (int i = 0; i < 2; i++) {
s4 = Cross(s5s[i], r6);
tmp = Norm(s4);
s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp };
Cross_(s5s[i], s4, r4);
r4 = { r6[0] - d5 * s5s[i][0] + a5 * r4[0],
r6[1] - d5 * s5s[i][1] + a5 * r4[1],
r6[2] - d5 * s5s[i][2] + a5 * r4[2] };
Cross_(r_O7S_O, r4, n2_O);
tmp = Dot(n2_O, s4);
if (tmp < 0)
n2_O = { -n2_O[0], -n2_O[1], -n2_O[2] };
errs[i] = acos(cos(theta - signed_angle(n1_O, n2_O, u_O7S_O)));
errs[i] *= errs[i];
}
if (errs[0] < min_err || errs[1] < min_err) {
best_q7 = q7j;
min_errs[0] = errs[0];
min_errs[1] = errs[1];
min_err = (errs[0] < errs[1]) ? errs[0] : errs[1];
}
q7j += q7step / (2 * n_fine);
}
q7m = best_q7;
return min_errs;
}
array<double, 2> theta_err_from_q7(double& q7,
const double theta,
const Eigen::Vector3d& i_E_O,
const array<double, 3>& k_E_O,
Eigen::Vector3d& i_6_O,
const array<double, 3>& n1_O,
const array<double, 3>& r_O7S_O,
const array<double, 3>& u_O7S_O,
const double q7step,
const unsigned int n_fine) {
// Calculates the error in swivel angle given the necessary geometry, q7, and the desired swivel angle theta
// NOTATION: u_O7S_O = r_O7S_O/norm(r_O7S_O), precalculated to improve speed
array<double, 2> errs;
R_axis_angle(k_E_O, -(q7 - PI / 4));
i_6_O = tmp_R * i_E_O;
array<double, 3> s6;
Cross_(k_E_O, i_6_O, s6);
//r6 = r_O7S_O - a7 * i_6_O
array<double, 3> r6 = { r_O7S_O[0] - a7 * i_6_O[0], r_O7S_O[1] - a7 * i_6_O[1], r_O7S_O[2] - a7 * i_6_O[2] };
double l = Norm(r6);
double tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2);
//cout << "\ttmp at triangle condition = " << tmp << endl;
if (tmp > 1) {
if ((tmp - 1) * (tmp - 1) < SING_TOL)
tmp = 1;
else
return array<double, 2>{1e10, 1e10};
}
else if (tmp > 0.9 && n_fine > 0)
{
return theta_err_from_q7_explore_around_sing(q7, theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7step, n_fine);
}
double actmp = acos(tmp);
double alpha2 = beta2 + actmp;
array<double, 3> k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l };
array<double, 3> i_C_O = Cross(k_C_O, s6);
tmp = Norm(i_C_O);
i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp };
array<double, 3> j_C_O;
Cross_(k_C_O, i_C_O, j_C_O);
double ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2];
double rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2];
double sa2, ca2;
sa2 = sin(alpha2);
ca2 = cos(alpha2);
tmp = -rz * ca2 / (ry * sa2);
//cout << "\ttmp at cone condition: " << tmp << endl;
if (tmp * tmp > 1) {
if (tmp * tmp < 1.2 && n_fine > 0) {
//cout << "\texploring around current value of q7" << endl;
// errs = theta_err_from_q7_explore_around_sing(q7, theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7step, n_fine);
//cout << "\tbest q7 found: " << q7 * 180 / PI << " with errs: " << errs[0] << ", " << errs[1] << endl;
// return errs;
return theta_err_from_q7_explore_around_sing(q7, theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7step, n_fine);
}
else
return array<double, 2>{1e15, 1e15};
}
if (tmp * tmp > 0.8 && n_fine > 0)
{
//cout << "\texploring around current value of q7" << endl;
// errs = theta_err_from_q7_explore_around_sing(q7, theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7step, n_fine);
//cout << "\tbest q7 found: " << q7 * 180 / PI << " with errs: " << errs[0] << ", " << errs[1] <<endl;
// return errs;
return theta_err_from_q7_explore_around_sing(q7, theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7step, n_fine);
}
tmp = asin(tmp);
double v[3] = { -sa2 * cos(tmp), -sa2 * sin(tmp), -ca2 };
array<array<double, 3>, 2> s5s;
s5s[0] = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2],
i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2],
i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] };
tmp = 2 * sa2 * cos(tmp);
s5s[1] = { s5s[0][0] + tmp * i_C_O[0],
s5s[0][1] + tmp * i_C_O[1],
s5s[0][2] + tmp * i_C_O[2] };
array<double, 3> s4, r4, n2_O;
for (int i = 0; i < 2; i++) {
s4 = Cross(s5s[i], r6);
tmp = Norm(s4);
s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp };
Cross_(s5s[i], s4, r4);
r4 = { r6[0] - d5 * s5s[i][0] + a5 * r4[0],
r6[1] - d5 * s5s[i][1] + a5 * r4[1],
r6[2] - d5 * s5s[i][2] + a5 * r4[2] };
Cross_(r_O7S_O, r4, n2_O);
tmp = Dot(n2_O, s4);
if (tmp < 0)
n2_O = { -n2_O[0], -n2_O[1], -n2_O[2] };
errs[i] = acos(cos(theta - signed_angle(n1_O, n2_O, u_O7S_O)));
errs[i] *= errs[i];
}
return errs;
}
void franka_ik_q7_one_sol(const double q7,
const Eigen::Vector3d& i_E_O,
const array<double, 3>& k_E_O,
Eigen::Vector3d& i_6_O,
const array<double, 3>& r_O7S_O,
const unsigned int branch,
array<array<double, 7>, 8>& qsols,
unsigned int ind,
const double q1_sing) {
// returns the two solution related to one single branch of the IK with q7 as free variable. The results are stored in qsols[s*ind] and qsols[2*ind+1]
R_axis_angle(k_E_O, -(q7 - PI / 4));
i_6_O = tmp_R * i_E_O;
array<double, 3> s6 = Cross(k_E_O, i_6_O);
array<double, 3> r6 = { r_O7S_O[0] - a7 * i_6_O[0], r_O7S_O[1] - a7 * i_6_O[1], r_O7S_O[2] - a7 * i_6_O[2] };
double l = Norm(r6);
double tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2);
// The exception tmp*tmp>1 was already handled when Errs was generated
//cout << "FINAL tmp triangle: " << tmp << endl;
if (tmp > 1) tmp = 1;
double actmp = acos(tmp);
double alpha2 = beta2 + actmp;
array<double, 3> k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l };
array<double, 3> i_C_O = Cross(k_C_O, s6);
tmp = Norm(i_C_O);
i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp };
array<double, 3> j_C_O = Cross(k_C_O, i_C_O);
double ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2];
double rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2];
array<array<double, 3>, 4> s5s;
double sa2, ca2;
sa2 = sin(alpha2);
ca2 = cos(alpha2);
tmp = -rz * ca2 / (ry * sa2);
// The exception tmp*tmp>1 was already handled when Errs was generated
//cout << "FINAL tmp cone: " << tmp << endl;
//cout << "cone variables: rz = " << rz << ", ry = " << ry << ", ca2 = " << ca2 << ", sa2 = " << sa2 << "" << endl;
tmp = asin(tmp);
double v[3] = { -sa2 * cos(tmp), -sa2 * sin(tmp), -ca2 };
array<double, 3> s5;
s5 = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2],
i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2],
i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] };
if (branch == 1) {
tmp = 2 * sa2 * cos(tmp);
s5 = { s5[0] + tmp * i_C_O[0],
s5[1] + tmp * i_C_O[1],
s5[2] + tmp * i_C_O[2] };
}
array<double, 3> s4, r4, s3, s2;
array<double, 6> sol1;
array<double, 3> sol2;
s4 = Cross(s5, r6);
tmp = Norm(s4);
s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp };
r4 = Cross(s5, s4);
r4 = { r6[0] - d5 * s5[0] + a5 * r4[0],
r6[1] - d5 * s5[1] + a5 * r4[1],
r6[2] - d5 * s5[2] + a5 * r4[2] };
R_axis_angle(s4, beta1);
s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2],
tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2],
tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] };
tmp = Norm(s3);
s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp };
tmp = s3[1] * s3[1] + s3[0] * s3[0];
if (tmp > SING_TOL*SING_TOL)
s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 };
else
s2 = { sin(q1_sing), cos(q1_sing), 0 };
J_dir(s2, s3, s4, s5, s6, k_E_O);
sol1 = q_from_J(tmp_J);
tmp_J.col(1) = -1 * tmp_J.col(1);
sol2 = q_from_low_J(tmp_J);
qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 };
check_limits(qsols[2 * ind], 7);
qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] };
check_limits(qsols[2 * ind + 1], 3);
}
unsigned int franka_ik_swivel(const array<double, 3>& r,
const array<double, 9>& ROE,
const double theta,
array<array<double, 7>, 8>& qsols,
const double q1_sing,
const unsigned int n_points,
const unsigned int n_fine_search) {
// IK with swivel angle as free variable (numerical)
// INPUT: r = r_EO_O, position of frame E in frame O
// ROE, orientation of frame E in frame O (row-first format)
// theta, swivel angle (see paper for geometric defninition)
// qsols, array to store 8 solutions
// q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
// n_points, number of points to discretise the range of q7.
// OUTPUT: number of solutions found.
// NOTATION:
// ri = r_iS_O,
// si - s_i_O
array<double, 3> k_E_O = { ROE[2], ROE[5], ROE[8] };
array<double, 3> r_O7S_O = { r[0] - dE * k_E_O[0], r[1] - dE * k_E_O[1], r[2] - d1 - dE * k_E_O[2] };
double tmp = sqrt(r_O7S_O[1] * r_O7S_O[1] + r_O7S_O[0] * r_O7S_O[0]);
if (tmp < SING_TOL) {
cout << "ERROR: n1_O is undefined";
for (int i = 0; i < 8; i++)
fill(qsols[i].begin(), qsols[i].end(), NAN);
return 0;
}
array<double, 3> n1_O = { r_O7S_O[1] / tmp, -r_O7S_O[0] / tmp, 0 };
Eigen::Vector3d i_E_O(ROE[0], ROE[3], ROE[6]);
Eigen::Vector3d i_6_O;
tmp = Norm(r_O7S_O);
array<double, 3> u_O7S_O = { r_O7S_O[0] / tmp, r_O7S_O[1] / tmp, r_O7S_O[2] / tmp };
double q7_step = (q_up[6] - q_low[6]) / (n_points - 1);
double q7;
array<array<double, 2>, MAX_N_POINTS> Errs;
array<unsigned int, MAX_N_POINTS> close_cases_b0;
array<unsigned int, MAX_N_POINTS> close_cases_b1;
array<double, MAX_N_POINTS> q7s;
//cout << "\nn1_O = " << n1_O[0] << ", " << n1_O[1] << ", " << n1_O[2] << endl;
unsigned int n_close_cases_b0 = 0;
unsigned int n_close_cases_b1 = 0;
for (int i = 0; i < n_points; i++) {
q7s[i] = q_low[6] + i * q7_step;
//cout << "\nq7 = " << q7s[i]*180/PI << endl;
Errs[i] = theta_err_from_q7(q7s[i], theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7_step, n_fine_search);
//cout << "errors at q7 = " << q7s[i]*180/PI << " are " << Errs[i][0] << ", " << Errs[i][1] << endl;
if (Errs[i][0] < ERR_THRESH)
{
close_cases_b0[n_close_cases_b0] = i;
n_close_cases_b0 += 1;
//cout << "saved q7 (b0) = " << q7s[i]*180/PI << endl;
}
if (Errs[i][1] < ERR_THRESH)
{
close_cases_b1[n_close_cases_b1] = i;
n_close_cases_b1 += 1;
//cout << "saved q7 (b1) = " << q7s[i] * 180 / PI << endl;
}
}
if (n_close_cases_b0 + n_close_cases_b1 == 0) {
for (int i = 0; i < 8; i++)
fill(qsols[i].begin(), qsols[i].end(), NAN);
return 0;
}
// identify repeated cases i.e. cases where several consecutive solutions passed the threshold
unsigned int min;
vector<array<unsigned int, 2>> best(0);
if (n_close_cases_b0 > 0) {
min = close_cases_b0[0];
for (int i = 1; i < n_close_cases_b0; i++) {
if (close_cases_b0[i] == close_cases_b0[i - 1] + 1) {
if (Errs[close_cases_b0[i]][0] < Errs[min][0]) {
min = close_cases_b0[i];
}
}
else {
best.push_back({ min, 0 });
min = close_cases_b0[i];
}
}
best.push_back({ min, 0 });
}
if (n_close_cases_b1 > 0) {
min = close_cases_b1[0];
for (int i = 1; i < n_close_cases_b1; i++) {
if (close_cases_b1[i] == close_cases_b1[i - 1] + 1) {
if (Errs[close_cases_b1[i]][1] < Errs[min][1]) {
min = close_cases_b1[i];
}
}
else {
best.push_back({ min, 1 });
min = close_cases_b1[i];
}
}
best.push_back({ min, 1 });
}
unsigned int n_sols = static_cast<unsigned int>(best.size());
if (n_sols > 4) {
//cout << "\nWARNING: Number of solutions is" << 2 * n_sols << "- Only the first 8 solutions found will be returned.\n";
n_sols = 4;
}
// interpolation
double e0, e1, e2, e3, q71, q72, q7_opt;
array<unsigned int, 2> m;
for (int i = 0; i < n_sols; i++) {
m = best[i];
q7_opt = q7s[m[0]];
if (m[0] > 1 && m[0] < n_points - 2) {
if (Errs[m[0] - 2][m[1]] < ERR_THRESH && Errs[m[0] + 2][m[1]] < ERR_THRESH) {
if (Errs[m[0] + 1][m[1]] < Errs[m[0] - 1][m[1]]) {
// 0=i-1, 1=i, 2=i+1, 3=i+2
e0 = Errs[m[0] - 1][m[1]];
e1 = Errs[m[0]][m[1]];
e2 = Errs[m[0] + 1][m[1]];
e3 = Errs[m[0] + 2][m[1]];
q71 = q7s[m[0]];
q72 = q7s[m[0] + 1];
}
else {
// 0=i-2, 1=i-1, 2=i, 3=i+1
e0 = Errs[m[0] - 2][m[1]];
e1 = Errs[m[0] - 1][m[1]];
e2 = Errs[m[0]][m[1]];
e3 = Errs[m[0] + 1][m[1]];
q71 = q7s[m[0] - 1];
q72 = q7s[m[0]];
}
tmp = ((e1 - e0) * q71 - (e3 - e2) * q72 + (e2 - e1) * q7_step) / (e1 - e0 - e3 + e2);
if (tmp > q71 && tmp < q72)
q7_opt = tmp;
}
}
franka_ik_q7_one_sol(q7_opt, i_E_O, k_E_O, i_6_O, r_O7S_O, m[1], qsols, i, q1_sing);
}
for (int i = 2 * n_sols; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
}
return 2 * n_sols;
}
double franka_swivel(const array<double, 7>& q) {
// swivel angle for a configuration q
array<Eigen::Matrix4d, 9> Ts;
franka_fk_all_frames(Ts, q);
array<double, 3> r4 = { Ts[3](0,3), Ts[3](1,3), Ts[3](2,3) - d1 };
array<double, 3> r7 = { Ts[6](0,3), Ts[6](1,3), Ts[6](2,3) - d1 };
array<double, 3> s4 = { Ts[3](0,2), Ts[3](1,2), Ts[3](2,2) };
double tmp = sqrt(r7[1] * r7[1] + r7[0] * r7[0]);
if (tmp < SING_TOL) {
cout << "ERROR: n1_O is undefined";
return NAN;
}
array<double, 3> n1_O = { r7[1] / tmp, -r7[0] / tmp, 0 };
array<double, 3> n2_O;
Cross_(r7, r4, n2_O);
tmp = Dot(n2_O, s4);
if (tmp < 0)
n2_O = { -n2_O[0], -n2_O[1], -n2_O[2] };
tmp = Norm(r7);
return signed_angle(n1_O, n2_O, array<double, 3>{r7[0] / tmp, r7[1] / tmp, r7[2] / tmp});
}
// FUNCTIONS FOR JACOBIAN MATRIX ==========================================================================
unsigned int franka_J_ik_q7(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q7,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles,
const char Jacobian_ee,
const double q1_sing) {
// IK to calculate Jacobian and joint angles with q7 as free variable.
// INPUT: r = r_EO_O, position of frame E in frame O
// ROE, orientation of frame E in frame O (row-first format)
// q7, value of joint angle of joint 7
// Jsols, array to store 8 Jacobian solutions
// qsols, array to store 8 joint-angle solutions
// joint_angles, if false only Jacobians are returned
// Jacobian_ee, end-effector frame of the Jacobian, not the IK. Only 'E', 'F', '8' and '6' are supported.
// q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
// OUTPUT: number of solutions found.
// NOTATION:
// ri = r_iS_O,
// si - s_i_O,
Eigen::Vector3d i_E_O(ROE[0], ROE[3], ROE[6]);
array<double, 3> k_E_O = { ROE[2], ROE[5], ROE[8] };
R_axis_angle(k_E_O, -(q7 - PI / 4));
Eigen::Vector3d i_6_O = tmp_R * i_E_O;
array<double, 3> s6;
Cross_(k_E_O, i_6_O, s6);
array<double, 3> r6 = { r[0] - dE * k_E_O[0] - a7 * i_6_O[0], r[1] - dE * k_E_O[1] - a7 * i_6_O[1], r[2] - d1 - dE * k_E_O[2] - a7 * i_6_O[2] };
double l = Norm(r6);
double tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2);
if (tmp > 1) {
if ((tmp - 1) * (tmp - 1) < SING_TOL) {
tmp = 1;
}
else {
cout << "ERROR: unable to assembly kinematic chain";
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
for (auto& row : Jsols[i])
fill(row.begin(), row.end(), NAN);
}
return 0;
}
}
double actmp = acos(tmp);
double alpha2 = beta2 + actmp;
array<double, 3> k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l };
array<double, 3> i_C_O = Cross(k_C_O, s6);
tmp = Norm(i_C_O);
i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp };
array<double, 3> j_C_O = Cross(k_C_O, i_C_O);
double ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2];
double rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2];
array<array<double, 3>, 4> s5s;
double sa2, ca2;
int n_alphs = 1;
unsigned int n_sols = 0;
if (d3 + d5 < l && l < b1 + b2) n_alphs = 2;
double v[3];
for (int i = 0; i < n_alphs; i++) {
sa2 = sin(alpha2);
ca2 = cos(alpha2);
tmp = -rz * ca2 / (ry * sa2);
if (tmp * tmp > 1)
continue;
tmp = asin(tmp);
v[0] = -sa2 * cos(tmp);
v[1] = -sa2 * sin(tmp);
v[2] = -ca2;
s5s[n_sols] = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2],
i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2],
i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] };
tmp = 2 * sa2 * cos(tmp);
//s5[n_sols+1] = s5s[n_sols] + (2*sa2*cos(tmp)*i_C_O);
s5s[n_sols + 1] = { s5s[n_sols][0] + tmp * i_C_O[0],
s5s[n_sols][1] + tmp * i_C_O[1],
s5s[n_sols][2] + tmp * i_C_O[2] };
n_sols += 2;
alpha2 = beta2 - actmp;
}
//Jsols.resize(2 * n_sols);
//vector<array<double, 7>> sols;
array<double, 6> sol1;
array<double, 3> sol2;
array<double, 3> s4, r4, s3, s2, s5;
for (int i = 0; i < n_sols; i++) {
s5 = s5s[i];
Cross_(s5, r6, s4);
tmp = Norm(s4);
s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp };
//r4 = r6 - d5 * s5 + a5 * Cross(s5, s4);
Cross_(s5, s4, r4);
r4 = { r6[0] - d5 * s5[0] + a5 * r4[0], r6[1] - d5 * s5[1] + a5 * r4[1], r6[2] - d5 * s5[2] + a5 * r4[2] };
//s3 = R_axis_angle(s4, beta1) * r4;
R_axis_angle(s4, beta1);
s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2],
tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2],
tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] };
tmp = Norm(s3);
s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp };
tmp = s3[1] * s3[1] + s3[0] * s3[0];
if (tmp > SING_TOL * SING_TOL) {
s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 };
}
else {
s2 = { sin(q1_sing), cos(q1_sing), 0 };
}
save_J_sol(s2, s3, s4, s5, s6, k_E_O, r4, r6, r, Jsols, i, Jacobian_ee);
if (joint_angles) {
J_dir(s2, s3, s4, s5, s6, k_E_O);
sol1 = q_from_J(tmp_J);
tmp_J.col(1) = -1 * tmp_J.col(1);
sol2 = q_from_low_J(tmp_J);
qsols[2 * i] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 };
check_limits(qsols[2 * i], 7);
qsols[2 * i + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * i][3], qsols[2 * i][4], qsols[2 * i][5], qsols[2 * i][6] };
check_limits(qsols[2 * i + 1], 3);
}
}
for (int i = 2 * n_sols; i < 8; ++i) {
for (auto& row : Jsols[i])
fill(row.begin(), row.end(), NAN);
}
for (int i = joint_angles ? 2 * n_sols : 0; i < 8; i++)
fill(qsols[i].begin(), qsols[i].end(), NAN);
return 2 * n_sols;
}
unsigned int franka_J_ik_q4(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q4,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles,
const char Jacobian_ee,
const double q1_sing,
const double q7_sing) {
// IK to calculate Jacobian and joint angles with q4 as free variable.
// INPUT: r = r_EO_O, position of frame E in frame O
// ROE, orientation of frame E in frame O (row-first format)
// q4, value of joint angle of joint 4
// Jsols, array to store 8 Jacobian solutions
// qsols, array to store 8 joint-angle solutions
// joint_angles, if false only Jacobians are returned
// Jacobian_ee, end-effector frame of the Jacobian, not the IK. Only 'E', 'F', '8' and '6' are supported.
// q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
// q7_sing, emergency value of q7 in case S7 intersects S (type-2 singularity)
// OUTPUT: number of solutions found.
// NOTATION:
// ri = r_iS_O,
// si - s_i_O,
array<double, 3> r_ES_O = { r[0], r[1], r[2] - d1 };
array<double, 3> tmp_v = { r_ES_O[1] * ROE[8] - r_ES_O[2] * ROE[5],
r_ES_O[2] * ROE[2] - r_ES_O[0] * ROE[8],
r_ES_O[0] * ROE[5] - r_ES_O[1] * ROE[2] };
if (tmp_v[0] * tmp_v[0] + tmp_v[1] * tmp_v[1] + tmp_v[2] * tmp_v[2] < SING_TOL)
return franka_J_ik_q7(r, ROE, q7_sing, Jsols, qsols, joint_angles, Jacobian_ee, q1_sing);
array<double, 3> r_O7S_O = { r_ES_O[0] - dE * ROE[2], r_ES_O[1] - dE * ROE[5], r_ES_O[2] - dE * ROE[8] };
array<double, 3> r_O7S_E = { ROE[0] * r_O7S_O[0] + ROE[3] * r_O7S_O[1] + ROE[6] * r_O7S_O[2],
ROE[1] * r_O7S_O[0] + ROE[4] * r_O7S_O[1] + ROE[7] * r_O7S_O[2],
ROE[2] * r_O7S_O[0] + ROE[5] * r_O7S_O[1] + ROE[8] * r_O7S_O[2] };
double alpha = q4 + beta1 + beta2 - PI;
double lo2 = b1 * b1 + b2 * b2 - 2 * b1 * b2 * cos(alpha);
double lp2 = lo2 - r_O7S_E[2] * r_O7S_E[2];
if (lp2 < 0) {
if (lp2 * lp2 < SING_TOL * SING_TOL)
lp2 = 0;
else {
cout << "\nERROR: unable to assembly kinematic chain\n";
for (int i = 0; i < 8; ++i)
fill(qsols[i].begin(), qsols[i].end(), NAN);
return 0;
}
}
double gamma2 = beta2 + asin(b1 * sin(alpha) / sqrt(lo2));
double cg2 = cos(gamma2), sg2 = sin(gamma2);
double Lp2 = r_O7S_E[0] * r_O7S_E[0] + r_O7S_E[1] * r_O7S_E[1], phi = atan2(-r_O7S_E[1], -r_O7S_E[0]);
double tmp = (Lp2 + a7 * a7 - lp2) / (2 * sqrt(Lp2) * a7);
if (tmp > 1.0) {
if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL)
tmp = 1.0;
else {
cout << "\nERROR: unable to assembly kinematic chain\n";
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
}
return 0;
}
}
double psi = acos(tmp), ry, rz;
double q7s[2] = { -phi - psi - 3 * PI / 4, -phi + psi - 3 * PI / 4 };
double gammas[2] = { 0,0 };
size_t ind = 0;
array<double, 3> s2, s3, s4, s5, s6, r4, r6, i_C_O, j_C_O, k_C_O;
array<double, 3> s7 = { ROE[2],ROE[5],ROE[8] };
array<double, 6> sol1;
array<double, 3> sol2;
for (auto q7 : q7s) {
tmp_v = { cos(-q7 + 3 * PI / 4), sin(-q7 + 3 * PI / 4), 0 };
s6 = { ROE[0] * tmp_v[0] + ROE[1] * tmp_v[1], ROE[3] * tmp_v[0] + ROE[4] * tmp_v[1], ROE[6] * tmp_v[0] + ROE[7] * tmp_v[1] };
tmp_v = { -a7 * cos(-q7 + PI / 4), -a7 * sin(-q7 + PI / 4), 0 };
r6 = { ROE[0] * tmp_v[0] + ROE[1] * tmp_v[1], ROE[3] * tmp_v[0] + ROE[4] * tmp_v[1], ROE[6] * tmp_v[0] + ROE[7] * tmp_v[1] };
r6 = { r6[0] + r_O7S_O[0], r6[1] + r_O7S_O[1], r6[2] + r_O7S_O[2] };
tmp = Norm(r6);
k_C_O = { -r6[0] / tmp, -r6[1] / tmp, -r6[2] / tmp };
Cross_(k_C_O, s6, i_C_O);
tmp = Norm(i_C_O);
i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp };
Cross_(k_C_O, i_C_O, j_C_O);
ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2];
rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2];
tmp = -rz * cg2 / (ry * sg2);
if (tmp * tmp > 1) continue;
tmp = asin(tmp);
gammas[0] = tmp;
gammas[1] = PI - tmp;
for (auto gamma : gammas) {
tmp_v = { -sg2 * cos(gamma), -sg2 * sin(gamma), -cg2 };
s5 = { i_C_O[0] * tmp_v[0] + j_C_O[0] * tmp_v[1] + k_C_O[0] * tmp_v[2],
i_C_O[1] * tmp_v[0] + j_C_O[1] * tmp_v[1] + k_C_O[1] * tmp_v[2],
i_C_O[2] * tmp_v[0] + j_C_O[2] * tmp_v[1] + k_C_O[2] * tmp_v[2] };
Cross_(s5, r6, s4);
tmp = Norm(s4);
s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp };
Cross_(s5, s4, r4);
r4 = { r6[0] - d5 * s5[0] + a5 * r4[0], r6[1] - d5 * s5[1] + a5 * r4[1], r6[2] - d5 * s5[2] + a5 * r4[2] };
R_axis_angle(s4, beta1);
s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2],
tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2],
tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] };
tmp = Norm(s3);
s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp };
tmp = s3[1] * s3[1] + s3[0] * s3[0];
if (tmp > SING_TOL*SING_TOL)
s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 };
else
s2 = { sin(q1_sing), cos(q1_sing), 0 };
save_J_sol(s2, s3, s4, s5, s6, s7, r4, r6, r, Jsols, ind, Jacobian_ee);
if (joint_angles) {
J_dir(s2, s3, s4, s5, s6, s7);
sol1 = q_from_J(tmp_J);
tmp_J.col(1) = -1 * tmp_J.col(1);
sol2 = q_from_low_J(tmp_J);
qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 };
check_limits(qsols[2 * ind], 7);
qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] };
check_limits(qsols[2 * ind + 1], 3);
}
ind++;
}
}
for (int i = 2 * ind; i < 8; ++i) {
for (auto& row : Jsols[i])
fill(row.begin(), row.end(), NAN);
}
for (int i = joint_angles ? 2 * ind : 0; i < 8; i++)
fill(qsols[i].begin(), qsols[i].end(), NAN);
return 2 * ind;
}
unsigned int franka_J_ik_q6_parallel(const array<double, 3>& r,
const array<double, 3>& r_ES_O,
const array<double, 9>& ROE,
const int sgn,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles,
const char Jacobian_ee,
const double q1_sing) {
// Parallel case of the Jacobian IK with q6 as free variable. Only called by franka_J_ik_q6(), not by the user.
// INPUT: r, r_ES_O, ROE, sgn = sign(cos(q6)), Jsols, qsols, joint_angles, Jacobian_ee, q1_sing.
// OUTPUT: number of solutions found.
// NOTATION:
// ri = r_iS_O, i = 1,2,3,4,5,6,7
// si = s_i_O
// Q is a frame that is parallel to frame E and has origin at Q (Q is called E' in the paper)
array<double, 3> s7 = { ROE[2],ROE[5],ROE[8] };
array<double, 3> r_QS_O = { r_ES_O[0] + (-dE + sgn * d5) * s7[0], r_ES_O[1] + (-dE + sgn * d5) * s7[1], r_ES_O[2] + (-dE + sgn * d5) * s7[2] };
array<double, 3> r_SQ_Q = { -ROE[0] * r_QS_O[0] - ROE[3] * r_QS_O[1] - ROE[6] * r_QS_O[2],
-ROE[1] * r_QS_O[0] - ROE[4] * r_QS_O[1] - ROE[7] * r_QS_O[2],
-ROE[2] * r_QS_O[0] - ROE[5] * r_QS_O[1] - ROE[8] * r_QS_O[2] };
double tmp = b1 * b1 - r_SQ_Q[2] * r_SQ_Q[2];
if (tmp * tmp < SING_TOL * SING_TOL)
tmp = 0;
if (tmp < 0) {
cout << "ERROR: unable to assembly kinematic chain";
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
for (auto& row : Jsols[i])
fill(row.begin(), row.end(), NAN);
}
return 0;
}
double lp = sqrt(tmp);
array<double, 3> r_SpQ_Q = { r_SQ_Q[0], r_SQ_Q[1], 0 };
double l_SpQ = sqrt(r_SQ_Q[0] * r_SQ_Q[0] + r_SQ_Q[1] * r_SQ_Q[1]);
double alphas[2], Ls[2];
double q7;
Ls[0] = a5 + lp,
Ls[1] = a5 - lp;
array<double, 3> tmp_v, r_O6pQ_Q, i_4_Q, r_O4Q_Q, s6_Q, r_O6Q_Q, s4_Q, s3_Q, s2, s3, s4, s5, s6, r4, r6;
Eigen::Matrix<double, 3, 4> partial_J_Q, partial_J_O;
Eigen::Matrix<double, 3, 2> rs;
Eigen::Matrix3d ROQ;
ROQ << ROE[0], ROE[1], ROE[2],
ROE[3], ROE[4], ROE[5],
ROE[6], ROE[7], ROE[8];
const array<double, 3> k{ {0,0,1} };
array<double, 3> s5_Q{ {0,0,-1.0 * sgn} };
int tmp_sgn;
unsigned int ind = 0;
array<double, 6> sol1;
array<double, 3> sol2;
for (auto L : Ls) {
tmp = (-L * L + a7 * a7 + l_SpQ * l_SpQ) / (2 * a7 * l_SpQ);
if ((tmp - 1) * (tmp - 1) < SING_TOL)
tmp = 1;
else if ((tmp + 1) * (tmp + 1) < SING_TOL)
tmp = -1;
if (tmp * tmp > 1)
continue;
alphas[0] = acos(tmp);
alphas[1] = -acos(tmp);
for (auto alpha : alphas) {
rotate_by_axis_angle(k, alpha, r_SpQ_Q, r_O6pQ_Q);
r_O6pQ_Q = { a7 * r_O6pQ_Q[0] / l_SpQ, a7 * r_O6pQ_Q[1] / l_SpQ, a7 * r_O6pQ_Q[2] / l_SpQ };
i_4_Q = { r_SpQ_Q[0] - r_O6pQ_Q[0], r_SpQ_Q[1] - r_O6pQ_Q[1], r_SpQ_Q[2] - r_O6pQ_Q[2] };
tmp = Norm(i_4_Q);
tmp_sgn = L < 0 ? -1 : 1;
i_4_Q = { tmp_sgn * i_4_Q[0] / tmp, tmp_sgn * i_4_Q[1] / tmp, tmp_sgn * i_4_Q[2] / tmp };
r_O4Q_Q = { r_O6pQ_Q[0] + a5 * i_4_Q[0], r_O6pQ_Q[1] + a5 * i_4_Q[1], r_O6pQ_Q[2] + a5 * i_4_Q[2] };
Cross_(r_O6pQ_Q, k, s6_Q);
r_O6Q_Q = { r_O6pQ_Q[0], r_O6pQ_Q[1], r_O6pQ_Q[2] - sgn * d5 };
rs << r_O4Q_Q[0], r_O6Q_Q[0],
r_O4Q_Q[1], r_O6Q_Q[1],
r_O4Q_Q[2], r_O6Q_Q[2];
rs = ROQ * rs; // r_O4Q_O, r_O6Q_O
r4 = { rs(0,0) + r_QS_O[0], rs(1,0) + r_QS_O[1], rs(2,0) + r_QS_O[2] };
r6 = { rs(0,1) + r_QS_O[0], rs(1,1) + r_QS_O[1], rs(2,1) + r_QS_O[2] };
Cross_(i_4_Q, s5_Q, s4_Q);
tmp_v = { r_O4Q_Q[0] - r_SQ_Q[0], r_O4Q_Q[1] - r_SQ_Q[1], r_O4Q_Q[2] - r_SQ_Q[2] };
rotate_by_axis_angle(s4_Q, beta1, tmp_v, s3_Q);
tmp = Norm(s3_Q);
//s3_Q = {s3_Q[0]/tmp,s3_Q[1]/tmp,s3_Q[2]/tmp};
partial_J_Q << s3_Q[0] / tmp, s4_Q[0], s5_Q[0], s6_Q[0],
s3_Q[1] / tmp, s4_Q[1], s5_Q[1], s6_Q[1],
s3_Q[2] / tmp, s4_Q[2], s5_Q[2], s6_Q[2];
partial_J_O = ROQ * partial_J_Q;
s3 = { partial_J_O(0,0), partial_J_O(1,0), partial_J_O(2,0) };
s4 = { partial_J_O(0,1), partial_J_O(1,1), partial_J_O(2,1) };
s5 = { partial_J_O(0,2), partial_J_O(1,2), partial_J_O(2,2) };
s6 = { partial_J_O(0,3), partial_J_O(1,3), partial_J_O(2,3) };
q7 = atan2(r_O6pQ_Q[1], -r_O6pQ_Q[0]) + PI / 4;
tmp = s3[1] * s3[1] + s3[0] * s3[0];
if (tmp > SING_TOL*SING_TOL)
s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 };
else
s2 = { sin(q1_sing), cos(q1_sing), 0 };
save_J_sol(s2, s3, s4, s5, s6, s7, r4, r6, r, Jsols, ind, Jacobian_ee);
if (joint_angles) {
J_dir(s2, s3, s4, s5, s6, s7);
sol1 = q_from_J(tmp_J);
tmp_J.col(1) = -1 * tmp_J.col(1);
sol2 = q_from_low_J(tmp_J);
qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 };
check_limits(qsols[2 * ind], 7);
qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] };
check_limits(qsols[2 * ind + 1], 3);
}
ind++;
}
}
for (int i = 2 * ind; i < 8; ++i) {
for (auto& row : Jsols[i])
fill(row.begin(), row.end(), NAN);
}
for (int i = joint_angles ? 2 * ind : 0; i < 8; i++)
fill(qsols[i].begin(), qsols[i].end(), NAN);
return 2 * ind;
}
unsigned int franka_J_ik_q6(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q6,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles,
const char Jacobian_ee,
const double q1_sing,
const double q7_sing) {
// IK to calculate Jacobian and joint angles with q6 as free variable.
// INPUT: r = r_EO_O, position of frame E in frame O
// ROE, orientation of frame E in frame O (row-first format)
// q6, value of joint angle of joint 6
// Jsols, array to store 8 Jacobian solutions
// qsols, array to store 8 joint-angle solutions
// joint_angles, if false only Jacobians are returned
// Jacobian_ee, end-effector frame of the Jacobian, not the IK. Only 'E', 'F', '8' and '6' are supported.
// q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
// q7_sing, emergency value of q7 in case S7 intersects S (type-2 singularity)
// OUTPUT: number of solutions found.
// NOTATION:
// ri = r_iS_O,
// si - s_i_O,
array<double, 3> r_ES_O = { r[0], r[1], r[2] - d1 };
array<double, 3> tmp_v = { r_ES_O[1] * ROE[8] - r_ES_O[2] * ROE[5],
r_ES_O[2] * ROE[2] - r_ES_O[0] * ROE[8],
r_ES_O[0] * ROE[5] - r_ES_O[1] * ROE[2] };
if (tmp_v[0] * tmp_v[0] + tmp_v[1] * tmp_v[1] + tmp_v[2] * tmp_v[2] < SING_TOL)
return franka_J_ik_q7(r, ROE, q7_sing, Jsols, qsols, joint_angles, Jacobian_ee, q1_sing);
if (sin(q6) * sin(q6) < SING_TOL* SING_TOL)
// PARALLEL CASE:
return franka_J_ik_q6_parallel(r, r_ES_O, ROE, cos(q6) >= 0 ? 1 : -1, Jsols, qsols, joint_angles, Jacobian_ee, q1_sing);
// NON-PARALLEL CASE:
array<double, 3> s7 = { ROE[2],ROE[5],ROE[8] };
double gamma1 = PI - q6;
double cg1 = cos(gamma1);
double sg1 = sin(gamma1);
array<double, 3> r_O7S_O = { r_ES_O[0] - dE * ROE[2], r_ES_O[1] - dE * ROE[5], r_ES_O[2] - dE * ROE[8] };
array<double, 3> r_PS_O = { r_O7S_O[0] + (a7 / tan(gamma1)) * s7[0], r_O7S_O[1] + (a7 / tan(gamma1)) * s7[1], r_O7S_O[2] + (a7 / tan(gamma1)) * s7[2] };
double lP = Norm(r_PS_O);
double lC = a7 / sg1;
double Cx = -(ROE[0] * r_PS_O[0] + ROE[3] * r_PS_O[1] + ROE[6] * r_PS_O[2]);
double Cy = -(ROE[1] * r_PS_O[0] + ROE[4] * r_PS_O[1] + ROE[7] * r_PS_O[2]);
double Cz = -(ROE[2] * r_PS_O[0] + ROE[5] * r_PS_O[1] + ROE[8] * r_PS_O[2]);
double c = sqrt(a5 * a5 + (lC + d5) * (lC + d5));
double tmp = (-b1 * b1 + lP * lP + c * c) / (2 * lP * c);
if (tmp > 1.0) {
if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL)
tmp = 1.0;
else {
cout << "ERROR: unable to assembly kinematic chain";
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
for (auto& row : Jsols[i])
fill(row.begin(), row.end(), NAN);
}
return 0;
}
}
double tau = acos(tmp);
unsigned int n_gamma_sols = 1;
if ((d3 + d5 + lC < lP) && (lP < b1 + c)) n_gamma_sols = 2;
double gamma2s[2];
if (d5 < -lC)
gamma2s[0] = tau + atan(a5 / (d5 + lC)) + PI;
else
gamma2s[0] = tau + atan(a5 / (d5 + lC));
if (n_gamma_sols > 1)
gamma2s[1] = gamma2s[0] - 2 * tau;
array<array<double, 3>, 4> s5s;
double q7s[4];
double d, u1, u2;
unsigned int n_sols = 0;
for (int i = 0; i < n_gamma_sols; i++) {
d = lP * cos(gamma2s[i]);
tmp = (d + Cz * cg1) / (sqrt(Cx * Cx * sg1 * sg1 + Cy * Cy * sg1 * sg1));
if (tmp > 1) {
if ((tmp - 1) * (tmp - 1) < SING_TOL * SING_TOL)
tmp = 1;
else
continue;
}
else if (tmp < -1) {
if ((tmp + 1) * (tmp + 1) < SING_TOL * SING_TOL)
tmp = -1;
else
continue;
}
u1 = asin(tmp);
u2 = atan2(Cx * sg1, Cy * sg1);
q7s[n_sols] = 5 * PI / 4 - u1 + u2;
tmp_v = { -sg1 * cos(u1 - u2), -sg1 * sin(u1 - u2), cg1 };
column_1s_times_vec(ROE, tmp_v, s5s[n_sols]);
n_sols++;
q7s[n_sols] = PI / 4 + u1 + u2;
tmp_v = { -sg1 * cos(PI - u1 - u2), -sg1 * sin(PI - u1 - u2), cg1 };
column_1s_times_vec(ROE, tmp_v, s5s[n_sols]);
n_sols++;
}
array<double, 3> s2, s3, s4, s6, r4, r6;
array<double, 6> sol1;
array<double, 3> sol2;
for (int i=0; i < n_sols; i++) {
r6 = { r_PS_O[0] - lC * s5s[i][0], r_PS_O[1] - lC * s5s[i][1], r_PS_O[2] - lC * s5s[i][2] };
tmp_v = { r_O7S_O[0] - r6[0], r_O7S_O[1] - r6[1], r_O7S_O[2] - r6[2] };
Cross_(s7, tmp_v, s6);
tmp = Norm(s6);
s6 = { s6[0] / tmp,s6[1] / tmp,s6[2] / tmp };
Cross_(s5s[i], r6, s4);
tmp = Norm(s4);
s4 = { s4[0] / tmp,s4[1] / tmp,s4[2] / tmp };
Cross_(s5s[i], s4, tmp_v);
r4 = { r6[0] - d5 * s5s[i][0] + a5 * tmp_v[0], r6[1] - d5 * s5s[i][1] + a5 * tmp_v[1], r6[2] - d5 * s5s[i][2] + a5 * tmp_v[2] };
rotate_by_axis_angle(s4, beta1, r4, s3);
tmp = Norm(s3);
s3 = { s3[0] / tmp,s3[1] / tmp,s3[2] / tmp };
tmp = s3[1] * s3[1] + s3[0] * s3[0];
if (tmp > SING_TOL* SING_TOL)
s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 };
else
s2 = { sin(q1_sing), cos(q1_sing), 0 };
save_J_sol(s2, s3, s4, s5s[i], s6, s7, r4, r6, r, Jsols, i, Jacobian_ee);
if (joint_angles) {
J_dir(s2, s3, s4, s5s[i], s6, s7);
sol1 = q_from_J(tmp_J);
tmp_J.col(1) = -1 * tmp_J.col(1);
sol2 = q_from_low_J(tmp_J);
qsols[2 * i] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7s[i] };
check_limits(qsols[2 * i], 7);
qsols[2 * i + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * i][3], qsols[2 * i][4], qsols[2 * i][5], qsols[2 * i][6] };
check_limits(qsols[2 * i + 1], 3);
}
}
for (int i = 2 * n_sols; i < 8; ++i) {
for (auto& row : Jsols[i])
fill(row.begin(), row.end(), NAN);
}
for (int i = joint_angles ? 2 * n_sols : 0; i < 8; i++)
fill(qsols[i].begin(), qsols[i].end(), NAN);
return 2 * n_sols;
}
// FUNCTIONS FOR SWIVEL ANGLE (JACOBIAN)
void franka_J_ik_q7_one_sol(const double q7,
const Eigen::Vector3d& i_E_O,
const array<double, 3>& k_E_O,
Eigen::Vector3d& i_6_O,
const array<double, 3>& r_O7S_O,
const array<double, 3>& r,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
unsigned int ind,
const bool joint_angles,
const char Jacobian_ee,
const unsigned int branch,
const double q1_sing) {
// returns the two solution related to one single branch of the IK with q7 as free variable. The results are stored in Jsols[2*ind] and Jsols[2*ind+1]
R_axis_angle(k_E_O, -(q7 - PI / 4));
i_6_O = tmp_R * i_E_O;
array<double, 3> s6 = Cross(k_E_O, i_6_O);
array<double, 3> r6 = { r_O7S_O[0] - a7 * i_6_O[0], r_O7S_O[1] - a7 * i_6_O[1], r_O7S_O[2] - a7 * i_6_O[2] };
double l = Norm(r6);
double tmp = (b1 * b1 - l * l - b2 * b2) / (-2 * l * b2);
// The exception tmp*tmp>1 was already handled when Errs was generated
if (tmp > 1) tmp = 1;
double actmp = acos(tmp);
double alpha2 = beta2 + actmp;
array<double, 3> k_C_O = { -r6[0] / l, -r6[1] / l, -r6[2] / l };
array<double, 3> i_C_O = Cross(k_C_O, s6);
tmp = Norm(i_C_O);
i_C_O = { i_C_O[0] / tmp, i_C_O[1] / tmp, i_C_O[2] / tmp };
array<double, 3> j_C_O = Cross(k_C_O, i_C_O);
double ry = s6[0] * j_C_O[0] + s6[1] * j_C_O[1] + s6[2] * j_C_O[2];
double rz = s6[0] * k_C_O[0] + s6[1] * k_C_O[1] + s6[2] * k_C_O[2];
array<array<double, 3>, 4> s5s;
double sa2, ca2;
sa2 = sin(alpha2);
ca2 = cos(alpha2);
tmp = -rz * ca2 / (ry * sa2);
// The exception tmp*tmp>1 was already handled when Errs was generated
tmp = asin(tmp);
double v[3] = { -sa2 * cos(tmp), -sa2 * sin(tmp), -ca2 };
array<double, 3> s5;
s5 = { i_C_O[0] * v[0] + j_C_O[0] * v[1] + k_C_O[0] * v[2],
i_C_O[1] * v[0] + j_C_O[1] * v[1] + k_C_O[1] * v[2],
i_C_O[2] * v[0] + j_C_O[2] * v[1] + k_C_O[2] * v[2] };
if (branch == 1) {
tmp = 2 * sa2 * cos(tmp);
s5 = { s5[0] + tmp * i_C_O[0],
s5[1] + tmp * i_C_O[1],
s5[2] + tmp * i_C_O[2] };
}
array<double, 3> s4, r4, s3, s2;
array<double, 6> sol1;
array<double, 3> sol2;
s4 = Cross(s5, r6);
tmp = Norm(s4);
s4 = { s4[0] / tmp, s4[1] / tmp, s4[2] / tmp };
r4 = Cross(s5, s4);
r4 = { r6[0] - d5 * s5[0] + a5 * r4[0],
r6[1] - d5 * s5[1] + a5 * r4[1],
r6[2] - d5 * s5[2] + a5 * r4[2] };
R_axis_angle(s4, beta1);
s3 = { tmp_R(0,0) * r4[0] + tmp_R(0,1) * r4[1] + tmp_R(0,2) * r4[2],
tmp_R(1,0) * r4[0] + tmp_R(1,1) * r4[1] + tmp_R(1,2) * r4[2],
tmp_R(2,0) * r4[0] + tmp_R(2,1) * r4[1] + tmp_R(2,2) * r4[2] };
tmp = Norm(s3);
s3 = { s3[0] / tmp, s3[1] / tmp, s3[2] / tmp };
tmp = s3[1] * s3[1] + s3[0] * s3[0];
if (tmp > SING_TOL* SING_TOL)
s2 = { -s3[1] / sqrt(tmp), s3[0] / sqrt(tmp), 0 };
else
s2 = { sin(q1_sing), cos(q1_sing), 0 };
save_J_sol(s2, s3, s4, s5, s6, k_E_O, r4, r6, r, Jsols, ind, Jacobian_ee);
if (joint_angles) {
J_dir(s2, s3, s4, s5, s6, k_E_O);
sol1 = q_from_J(tmp_J);
tmp_J.col(1) = -1 * tmp_J.col(1);
sol2 = q_from_low_J(tmp_J);
qsols[2 * ind] = { sol1[0], sol1[1], sol1[2], sol1[3], sol1[4], sol1[5], q7 };
check_limits(qsols[2 * ind], 7);
qsols[2 * ind + 1] = { sol2[0], sol2[1], sol2[2], qsols[2 * ind][3], qsols[2 * ind][4], qsols[2 * ind][5], qsols[2 * ind][6] };
check_limits(qsols[2 * ind + 1], 3);
}
}
unsigned int franka_J_ik_swivel(const array<double, 3>& r,
const array<double, 9>& ROE,
const double theta,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles,
const char Jacobian_ee,
const double q1_sing,
const unsigned int n_points,
const unsigned int n_fine_search) {
// IK to calculate Jacobian and joint angles with swivel angle as free variable (numerical).
// INPUT: r = r_EO_O, position of frame E in frame O
// ROE, orientation of frame E in frame O (row-first format)
// theta, swivel angle (see paper for gemetric definition)
// Jsols, array to store 8 Jacobian solutions
// qsols, array to store 8 joint-angle solutions
// joint_angles, if false only Jacobians are returned
// Jacobian_ee, end-effector frame of the Jacobian, not the IK. Only 'E', 'F', '8' and '6' are supported.
// q1_sing, emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
// n_points, number of points to descritise the range of q7
// OUTPUT: number of solutions found.
// NOTATION:
// ri = r_iS_O,
// si - s_i_O,
array<double, 3> k_E_O = { ROE[2], ROE[5], ROE[8] };
//r_O7S_O = r_EO_O + r_OS_O + r_O7E_O = r_EO_O - (0,0,d1) - dE*k_E_O
array<double, 3> r_O7S_O = { r[0] - dE * k_E_O[0], r[1] - dE * k_E_O[1], r[2] - d1 - dE * k_E_O[2] };
double tmp = sqrt(r_O7S_O[1] * r_O7S_O[1] + r_O7S_O[0] * r_O7S_O[0]);
if (tmp < SING_TOL) {
cout << "ERROR: n1_O is undefined";
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
for (auto& row : Jsols[i])
fill(row.begin(), row.end(), NAN);
}
return 0;
}
array<double, 3> n1_O = { r_O7S_O[1] / tmp, -r_O7S_O[0] / tmp, 0 };
Eigen::Vector3d i_E_O(ROE[0], ROE[3], ROE[6]);
Eigen::Vector3d i_6_O;
tmp = Norm(r_O7S_O);
array<double, 3> u_O7S_O = { r_O7S_O[0] / tmp, r_O7S_O[1] / tmp, r_O7S_O[2] / tmp };
double q7_step = (q_up[6] - q_low[6]) / (n_points - 1);
double q7;
array<array<double, 2>, MAX_N_POINTS> Errs;
array<unsigned int, MAX_N_POINTS> close_cases_b0;
array<unsigned int, MAX_N_POINTS> close_cases_b1;
array<double, MAX_N_POINTS> q7s;
unsigned int n_close_cases_b0 = 0;
unsigned int n_close_cases_b1 = 0;
for (int i = 0; i < n_points; i++) {
q7s[i] = q_low[6] + i * q7_step;
Errs[i] = theta_err_from_q7(q7s[i], theta, i_E_O, k_E_O, i_6_O, n1_O, r_O7S_O, u_O7S_O, q7_step, n_fine_search);
if (Errs[i][0] < ERR_THRESH)
{
close_cases_b0[n_close_cases_b0] = i;
n_close_cases_b0 += 1;
}
if (Errs[i][1] < ERR_THRESH)
{
close_cases_b1[n_close_cases_b1] = i;
n_close_cases_b1 += 1;
}
}
if (n_close_cases_b0 + n_close_cases_b1 == 0) {
for (int i = 0; i < 8; ++i) {
fill(qsols[i].begin(), qsols[i].end(), NAN);
for (auto& row : Jsols[i])
fill(row.begin(), row.end(), NAN);
}
return 0;
}
// identify repeated cases i.e. cases where several consecutive solutions passed the threshold
unsigned int min;
vector<array<unsigned int, 2>> best(0);
if (n_close_cases_b0 > 0) {
min = close_cases_b0[0];
for (int i = 1; i < n_close_cases_b0; i++) {
if (close_cases_b0[i] == close_cases_b0[i - 1] + 1) {
if (Errs[close_cases_b0[i]][0] < Errs[min][0]) {
min = close_cases_b0[i];
}
}
else {
best.push_back({ min, 0 });
min = close_cases_b0[i];
}
}
best.push_back({ min, 0 });
}
if (n_close_cases_b1 > 0) {
min = close_cases_b1[0];
for (int i = 1; i < n_close_cases_b1; i++) {
if (close_cases_b1[i] == close_cases_b1[i - 1] + 1) {
if (Errs[close_cases_b1[i]][1] < Errs[min][1]) {
min = close_cases_b1[i];
}
}
else {
best.push_back({ min, 1 });
min = close_cases_b1[i];
}
}
best.push_back({ min, 1 });
}
unsigned int n_sols = static_cast<unsigned int>(best.size());
if (n_sols > 4) {
//cout << "\nWARNING: Number of solutions is" << 2 * n_sols << "- Only the first 8 solutions found will be returned.\n";
n_sols = 4;
}
// interpolation
double e0, e1, e2, e3, q71, q72, q7_opt;
array<unsigned int, 2> m;
for (int i = 0; i < n_sols; i++) {
m = best[i];
q7_opt = q7s[m[0]];
if (m[0] > 1 && m[0] < n_points - 2) {
if (Errs[m[0] - 2][m[1]] < ERR_THRESH && Errs[m[0] + 2][m[1]] < ERR_THRESH) {
if (Errs[m[0] + 1][m[1]] < Errs[m[0] - 1][m[1]]) {
// 0=i-1, 1=i, 2=i+1, 3=i+2
e0 = Errs[m[0] - 1][m[1]];
e1 = Errs[m[0]][m[1]];
e2 = Errs[m[0] + 1][m[1]];
e3 = Errs[m[0] + 2][m[1]];
q71 = q7s[m[0]];
q72 = q7s[m[0] + 1];
}
else {
// 0=i-2, 1=i-1, 2=i, 3=i+1
e0 = Errs[m[0] - 2][m[1]];
e1 = Errs[m[0] - 1][m[1]];
e2 = Errs[m[0]][m[1]];
e3 = Errs[m[0] + 1][m[1]];
q71 = q7s[m[0] - 1];
q72 = q7s[m[0]];
}
tmp = ((e1 - e0) * q71 - (e3 - e2) * q72 + (e2 - e1) * q7_step) / (e1 - e0 - e3 + e2);
if (tmp > q71 && tmp < q72)
q7_opt = tmp;
}
}
franka_J_ik_q7_one_sol(q7_opt, i_E_O, k_E_O, i_6_O, r_O7S_O, r, Jsols, qsols, i, joint_angles, Jacobian_ee, m[1], q1_sing);
}
for (int i = 2 * n_sols; i < 8; ++i) {
for (auto& row : Jsols[i])
fill(row.begin(), row.end(), NAN);
}
for (int i = joint_angles ? 2 * n_sols : 0; i < 8; i++)
fill(qsols[i].begin(), qsols[i].end(), NAN);
return 2 * n_sols;
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201#ifndef GEOFIK_H
#define GEOFIK_H
#include <array>
#include <vector>
#include <eigen3/Eigen/Dense>
using namespace std;
constexpr double PI = 3.14159265359;
/**
* @brief Computes the joint angles given a Jacobian and the rotation matrix of the ee frame.
* @param J transpose of J.
* @param R the rotation matrix of ee frame with respect to frame O.
* @param ee [optional] name of ee frame ('E', 'F' or '8').
* @return joint angles q.
*/
array<double, 7> J_to_q(const array<array<double, 6>, 7>& J, const array<array<double, 3>, 3>& R, const char ee = 'E');
/**
* @brief Computes the Jacobian given the joint angles.
* @param q joint angles, name of ee frame.
* @param ee [optional] Name of ee frame ('E', 'F', '8', ...,'1').
* @return transpose of J.
*/
array<array<double, 6>, 7> J_from_q(const array<double, 7>& q, const char ee = 'E');
/**
* @brief Forward kinematics.
* @param q joint angles,
* @param ee name of ee frame ('E', 'F', '8', ...,'1').
* @return transformation matrix of ee frame with respect to frame O.
*/
Eigen::Matrix4d franka_fk(const array<double, 7>& q, const char ee = 'E');
/**
* @brief IK with q7 as free variable.
* @param r position of frame E with respect to frame O.
* @param ROE rotation matrix of frame E with respect to frame O (row-first format).
* @param q7 joint angle of joint 7 (radians)
* @param qsols array to store 8 solutions
* @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
* @return number of solutions found.
*/
unsigned int franka_ik_q7(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q7,
array<array<double, 7>, 8>& qsols,
const double q1_sing = PI / 2);
/**
* @brief IK with q4 as free variable.
* @param r position of frame E with respect to frame O.
* @param ROE rotation matrix of frame E with respect to frame O (row-first format).
* @param q4 joint angle of joint 4 (radians)
* @param qsols array to store 8 solutions
* @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
* @param q7_sing [optional] emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity).
* @return number of solutions found.
*/
unsigned int franka_ik_q4(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q4,
array<array<double, 7>, 8>& qsols,
const double q1_sing = PI / 2,
const double q7_sing = 0);
/**
* @brief IK with q6 as free variable.
* @param r position of frame E with respect to frame O.
* @param ROE rotation matrix of frame E with respect to frame O (row-first format).
* @param q6 joint angle of joint 6 (radians)
* @param qsols array to store 8 solutions
* @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
* @param q7_sing [optional] emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity).
* @return number of solutions found.
*/
unsigned int franka_ik_q6(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q6,
array<array<double, 7>, 8>& qsols,
const double q1_sing = PI / 2,
const double q7_sing = 0);
/**
* @brief IK with swivel angle as free variable (numerical).
* @param r position of frame E with respect to frame O.
* @param ROE rotation matrix of frame E with respect to frame O (row-first format).
* @param theta swivel angle in radians (see paper for geometric defninition)
* @param qsols array to store 8 solutions
* @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
* @param n_points [optional] number of points to discretise the range of q7.
* @return number of solutions found.
*/
unsigned int franka_ik_swivel(const array<double, 3>& r,
const array<double, 9>& ROE,
const double theta,
array<array<double, 7>, 8>& qsols,
const double q1_sing = PI / 2,
const unsigned int n_points = 500,
const unsigned int n_fine_search = 3);
/**
* @brief Calculates the swivel angle given the joint angles q.
* @param q joint angles.
* @return swivel angle theta (see paper for geometric defninition).
*/
double franka_swivel(const array<double, 7>& q);
/**
* @brief IK to calculate Jacobian and joint angles with q7 as free variable.
* @param r position of frame E with respect to frame O.
* @param ROE rotation matrix of frame E with respect to frame O (row-first format).
* @param q7 joint angle of joint 7 (radians).
* @param Jsols array to store 8 solutions for the Jacobians.
* @param qsols array to store 8 solutions for the joint angles.
* @param joint_angles [optional] if false only Jacobians are returned.
* @param Jacobian_ee [optional] ee frame of the Jacobian, not the IK ('E', 'F', '8' or '6').
* @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
* @return number of solutions found.
*/
unsigned int franka_J_ik_q7(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q7,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles = false,
const char Jacobian_ee = 'E',
const double q1_sing = PI / 2);
/**
* @brief IK to calculate Jacobian and joint angles with q4 as free variable.
* @param r position of frame E with respect to frame O.
* @param ROE rotation matrix of frame E with respect to frame O (row-first format).
* @param q4 joint angle of joint 4 (radians).
* @param Jsols array to store 8 solutions for the Jacobians.
* @param qsols array to store 8 solutions for the joint angles.
* @param joint_angles [optional] if false only Jacobians are returned.
* @param Jacobian_ee [optional] ee frame of the Jacobian, not the IK ('E', 'F', '8' or '6').
* @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
* @param q7_sing [optional] emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity).
* @return number of solutions found.
*/
unsigned int franka_J_ik_q4(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q4,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles = false,
const char Jacobian_ee = 'E',
const double q1_sing = PI / 2,
const double q7_sing = 0);
/**
* @brief IK to calculate Jacobian and joint angles with q6 as free variable.
* @param r position of frame E with respect to frame O.
* @param ROE rotation matrix of frame E with respect to frame O (row-first format).
* @param q6 joint angle of joint 6 (radians).
* @param Jsols array to store 8 solutions for the Jacobians.
* @param qsols array to store 8 solutions for the joint angles.
* @param joint_angles [optional] if false only Jacobians are returned.
* @param Jacobian_ee [optional] ee frame of the Jacobian, not the IK ('E', 'F', '8' or '6').
* @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
* @param q7_sing [optional] emergency value of q7 in case of singularity of S7 intersecting S (type-2 singularity).
* @return number of solutions found.
*/
unsigned int franka_J_ik_q6(const array<double, 3>& r,
const array<double, 9>& ROE,
const double q6,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles = false,
const char Jacobian_ee = 'E',
const double q1_sing = PI / 2,
const double q7_sing = 0);
/**
* @brief IK to calculate Jacobian and joint angles with swivel angle as free variable (numerical).
* @param r position of frame E with respect to frame O.
* @param ROE rotation matrix of frame E with respect to frame O (row-first format).
* @param theta swivel angle in radians (see paper for geometric defninition).
* @param Jsols array to store 8 solutions for the Jacobians.
* @param qsols array to store 8 solutions for the joint angles.
* @param joint_angles [optional] if false only Jacobians are returned.
* @param Jacobian_ee [optional] ee frame of the Jacobian, not the IK ('E', 'F', '8' or '6').
* @param q1_sing [optional] emergency value of q1 in case of singularity at shoulder joints (type-1 singularity).
* @param n_points [optional] number of points to discretise the range of q7.
* @return number of solutions found.
*/
unsigned int franka_J_ik_swivel(const array<double, 3>& r,
const array<double, 9>& ROE,
const double theta,
array<array<array<double, 6>, 7>, 8>& Jsols,
array<array<double, 7>, 8>& qsols,
const bool joint_angles = false,
const char Jacobian_ee = 'E',
const double q1_sing = PI / 2,
const unsigned int n_points = 600,
const unsigned int n_fine_search = 3);
#endif12345678910---title: Robotemoji: 📉colorFrom: pinkcolorTo: purplesdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# LLM-Panda: Robotic Pick-and-Place SimulatorLLM-Panda is a PyBullet simulation environment where a Franka Emika Panda robot arm follows natural-language commands to pick, move, and place tabletop objects. It uses an LLM-based semantic planner (or an offline rule-based keyword planner) to generate high-level plans, while deterministic Python controllers handle inverse kinematics (IK), reachability checks, collision avoidance, and grasp stability.---## 🚀 Setup InstructionsFollow these steps to set up the simulator on your local machine:1. **Clone the Repository:**```bashgit clone https://github.com/AI20K-Build-Cohort-2/C2-App-151.gitcd C2-App-151```2. **Create and Activate a Virtual Environment:*** **Linux/macOS:**```bashpython3 -m venv .venvsource .venv/bin/activate```* **Windows:**```powershellpython -m venv .venv.\.venv\Scripts\Activate.ps1```3. **Install Core Dependencies:**```bashpip install -r requirements.txt```4. **Install Local YCB Objects Assets Package:**The simulator utilizes YCB dataset models for the physical objects. Unzip the assets and install the package locally:```bashunzip pybullet-object-models.zippip install -e pybullet-object-models/pybullet-object-models```5. **Configure Environment Variables:**Copy the example environment file and configure your API keys:```bashcp .env.example .env```---## ⚙️ Environment VariablesThe application loads environment variables from the `.env` file in the root directory.| Variable | Description | Example Value || --- | --- | --- || `OPENAI_API_KEY` | API Key for the OpenAI model or compatible NVIDIA Integrate endpoints. | `sk-proj-...` or `nvapi-...` || `LLM_API_KEY` | Alternate fallback API Key variable name. | `nvapi-...` || `OPENAI_MODEL` | The LLM model name used for semantic planning. | `google/gemma-3n-e2b-it` or `gpt-4o` || `OPENAI_BASE_URL` | Base endpoint URL for compatible services. | `https://integrate.api.nvidia.com/v1` || `LLM_BASE_URL` | Alternate fallback Base URL variable name. | `https://api.deepseek.com` || `LOG_LEVEL` | Logging verbosity level. | `INFO` or `DEBUG` |---## 💬 Sample QueriesThe planner resolves Vietnamese/English synonyms and spelling typos, mapping them to the correct objects (`banana`, `soup_can`, `chips_can`) and destinations (`tray`, `Slot_1`..`Slot_6`).### Level 1: Basic Commands* `gắp quả chuối lên` (Grasp banana and hold)* `nhấc lon súp` (Grasp tomato soup can)* `để vào khay` (Place currently held object in the tray)* `di chuyển lon snack vào Slot_3` (Pick up chips can and place at Slot_3)### Level 2: Synonyms & Typos* `gắp hộp snák bỏ vô khay` (Handles accents and Vietnamese synonyms like "vô")* `nhặt lon canh lên` (Recognizes "lon canh" as soup can)* `gắp bim bim bỏ vào khay` (Maps "bim bim" to chips can)* `gắp lon sup bỏ vào trây` (Handles spelling typos)### Level 3: Sequential Actions* `di chuyển snack vào slot 3 và di chuyển lon súp vào khay`* `gắp lon súp đặt vào slot 2 và gắp quả chuối đặt vào khay`* `di chuyển quả chuối vào slot 5 rồi di chuyển snack vào khay`### Level 4: Spatial Adjacency (Relative Placements)* `đặt lon súp xuống cạnh bim bim` (Calculates neighboring empty slot)* `đặt quả chuối cạnh lon súp`* `đặt quả chuối vào slot trống hàng đầu`* `đặt lon súp vào slot bên trái khay`### Level 5: Obstacle Clearing (Collision Avoidance)* `dọn dẹp đường đi và gắp quả chuối vào khay` (If banana is blocked, picks up obstacle, moves it to a free slot, then picks and places banana)* `gắp quả chuối đặt vào khay` (Triggers obstacle clearing if neighbor count >= 1)### Level 6: Advanced Swap* `đổi vị trí quả chuối và snack` (Swaps the positions of the two items using a temporary free slot)* `hoán đổi vị trí giữa bim bim và quả chuối vàng`* `hãy đổi vị trí lon súp với quả chuối`---## 🛠 Running the Application* **Run with PyBullet 3D GUI (Offline Rule-Based Planner):**```bashpython main.py --llm rule --gui```* **Run with PyBullet 3D GUI (Remote LLM Planner - requires API key in `.env`):**```bashpython main.py --llm openai --gui```* **Run Python Test Suite:**```bashpytest -v```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265# LLM-Panda — Cánh tay Franka Panda điều khiển bằng Text-LLM (PyBullet)
Mô phỏng pick-and-place theo kiến trúc **"LLM làm Planner + Grasp Database ở tầng thực thi"**. Một LLM *chỉ-văn-bản* đọc mô tả cảnh dạng ký hiệu rồi xuất ra một chuỗi lời gọi hàm (`pick_up` / `place_at`); tầng thực thi xác định (deterministic) biến kế hoạch đó thành chuyển động tránh va chạm.
> [!NOTE]
> LLM chỉ **lập kế hoạch ở mức ngữ nghĩa** (gắp vật nào, đặt ở đâu). Toàn bộ hình học, IK, lực kẹp, va chạm do code xử lý → an toàn, tái lập được, và không phụ thuộc việc LLM có "biết" tọa độ hay không.
---
## 1. Tổng quan kiến trúc
```
┌─────────────────────────────────────────────────────┐
câu lệnh NL │ LLMAgent │
────────────► │ RuleBasedPlanner (mặc định, offline, EN/VI) │
│ RemoteLLMPlanner (OpenAI-compatible) │
└───────────────┬─────────────────────────────────────┘
│ kế hoạch JSON: [{pick_up}, {place_at}]
▼
┌─────────────────────────────────────────────────────┐
│ Executor (main.py) │
└───────┬───────────────┬───────────────┬─────────────┘
▼ ▼ ▼
SceneManager GraspPlanner RobotController
(Module 1) (Module 2) (Module 3)
world→text grasp pose IK + pick 3 pha
│
▼
GripperController
(Module 4) lực kẹp
```
Vòng lặp một lệnh:
1. **SceneManager** quét thế giới (`getBasePositionAndOrientation`, `getAABB`), gắn mỗi vật vào một vị trí ký hiệu (`Slot_1..6` hoặc `tray`) → chuỗi JSON.
2. **LLMAgent** nhận JSON đó + câu lệnh, trả về danh sách lời gọi hàm.
3. **Executor** duyệt từng lời gọi:
- `pick_up` → GraspPlanner tính world grasp pose → RobotController.pick.
- `place_at` → tra tọa độ slot/tray → RobotController.place.
---
## 2. Cài đặt & chạy
### Bước 1: Cài đặt các thư viện Python cơ bản
```bash
pip install -r requirements.txt # pybullet, numpy, pytest, python-dotenv, openai
```
### Bước 2: Cài đặt mô hình vật thể YCB (`pybullet-object-models.zip`)
Dự án sử dụng các mô hình vật thể thực tế từ bộ dữ liệu YCB. Bạn cần giải nén file zip cục bộ và cài đặt gói ở chế độ editable để PyBullet có thể nạp các mô hình này:
1. **Giải nén file zip:**
```bash
unzip pybullet-object-models.zip
```
2. **Cài đặt thư viện cục bộ:**
```bash
pip install -e pybullet-object-models/pybullet-object-models
```
> [!TIP]
> Khi tải các mô hình YCB này, hệ thống sẽ tự động truyền cờ `pb.URDF_USE_MATERIAL_COLORS_FROM_MTL` để hiển thị đúng họa tiết hình ảnh (texture) visual thực tế từ các file `.obj` và `.mtl` đi kèm, thay vì chỉ hiển thị hình dạng collision màu trắng đơn sắc.
---
## 3. Cách chạy mô phỏng
CLI hỗ trợ **2 chế độ**:
**a) One-shot** — chạy đúng 1 lệnh rồi thoát:
```bash
python main.py --gui -c "Pick up the banana and place it in the tray"
python main.py -c "gắp quả chuối đặt vào Slot_2" # headless (không giao diện)
python main.py --gui --idle 20 -c "..." # giữ cửa sổ 20 giây sau khi chạy
```
**b) Interactive (REPL)** — mặc định khi không truyền `-c`, giữ thế giới sống và gõ lệnh liên tục:
```bash
python main.py --gui # mở GUI rồi vào shell tương tác
python main.py -i -c "..." # chạy 1 lệnh trước, sau đó đi vào shell
```
Trong shell tương tác:
```
panda> gắp quả chuối đặt vào tray # câu lệnh ngôn ngữ tự nhiên
panda> :scene # in scene state hiện tại (JSON)
panda> :reset 9 # random lại vị trí vật (seed 9)
panda> :home # đưa tay về tư thế nghỉ
panda> :help # trợ giúp
panda> :quit # thoát (hoặc Ctrl-D / Ctrl-C)
```
### Các tham số CLI
| Tham số | Mặc định | Ý nghĩa |
| -------------------- | -------- | ------------------------------------------------ |
| `--gui` | tắt | Mở cửa sổ mô phỏng PyBullet 3D |
| `-c`, `--command` | `None` | Câu lệnh NL (EN/VI). Nếu không truyền sẽ vào REPL |
| `-i`, `--interactive`| tắt | Vào shell tương tác (sau khi chạy `-c` nếu có) |
| `--seed` | `0` | Seed ngẫu nhiên để phân bổ vị trí các vật thể |
| `--llm` | `openai` | Chọn planner: `rule` (offline) hoặc `openai` |
| `--idle` | `5.0` | Số giây giữ cửa sổ GUI sau một lần chạy one-shot |
Log mẫu của một lần chạy thành công:
```
[SCENE] banana is at Slot_5; soup_can is at Slot_3; chips_can is at Slot_2; tray is empty
[USER ] gắp quả chuối vào khay
[PLAN ] [{'function': 'pick_up', 'args': {'object_id': 'banana'}}, {'function': 'place_at', 'args': {'location_id': 'tray'}}]
[ACT ] pick_up(banana) grasp@[0.522, 0.134, 0.349]
[GRIP ] force=40.0 N holding=True
[ACT ] place_at(tray) -> [0.42, 0.45, 0.3]
[FINAL] banana is at tray; soup_can is at Slot_3; chips_can is at Slot_2; tray holds banana
```
---
## 4. Mô tả cảnh (Scene)
- **Robot**: Franka Emika Panda, đế cố định tại gốc `(0,0,0)`. Khớp tay `0–6` (7 DOF), ngón kẹp `9/10` (hành trình 0–0.04 m), TCP = link `11`.
- **Bàn**: hộp chữ nhật, **mặt bàn ở z = 0.30 m** (đã kiểm chứng IK với tới, sai số < 1 mm cho mọi slot/tray). Tâm `(0.50, 0.0)`.
- **Lưới 6 slot** (2 hàng × 3 cột), tọa độ `(x, y, 0.30)`:
| Cột → | x=0.40 | x=0.50 | x=0.60 |
| ------------ | -------- | -------- | -------- |
| hàng y=−0.15 | `Slot_1` | `Slot_2` | `Slot_3` |
| hàng y=+0.15 | `Slot_4` | `Slot_5` | `Slot_6` |
- **Tray** (khay cố định) tại `(0.50, 0.45, 0.30)`, ngay ngoài mép +y của bàn.
- **Vật thể** (sinh ngẫu nhiên trên 3 slot khác nhau theo `--seed`):
- `banana` — quả chuối, khối lượng 0.066 kg, ma sát 0.8, class `banana`.
- `soup_can` — lon súp cà chua, khối lượng 0.349 kg, ma sát 0.8, class `can`.
- `chips_can` — lon snack khoai tây chiên, khối lượng 0.205 kg, ma sát 0.5, class `chips`.
Mọi hằng số hình học và vật lý nằm trong [llm_panda/config.py](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/config.py).
---
## 5. Chi tiết các module
### Module 1 — `scene_manager.py`
Chuyển trạng thái vật lý → văn bản cho LLM.
| Hàm | Mô tả |
| --- | --- |
| `register_object(id,name,cls)` | Đăng ký một body để xuất hiện trong scene state |
| `get_world_pose(id)` | Bọc `p.getBasePositionAndOrientation` |
| `get_aabb(id)` | Bọc `p.getAABB` |
| `classify_location(pos)` | Gắn tọa độ → `tray` / `Slot_*` / `elsewhere` theo bán kính |
| `get_scene_state()` | Dict có cấu trúc (objects, slots, tray) |
| `get_scene_state_text()` | **Chuỗi JSON sạch** nạp thẳng vào prompt LLM |
### Module 2 — `grasp_planner.py`
Cơ sở dữ liệu grasp theo từng class + phép biến đổi cứng sang world.
- `local_to_world(world_pos, world_ori, local_pos, local_euler)`: đổi Euler→Quaternion (`p.getQuaternionFromEuler`) rồi `p.multiplyTransforms(...)` → **world grasp pose chính xác kể cả khi vật xoay**.
- `compute_grasp_pose(object_id, object_class)`: lấy world pose của vật, đọc local pose từ database, biến đổi sang world.
- **Fallback**: vật không có trong DB → grasp top-down ở **trung điểm mặt trên AABB** (`_aabb_fallback_grasp`).
Định dạng [data/grasp_database.json](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/data/grasp_database.json):
```json
{
"can": {
"local_position": [0.0, 0.0, 0.02],
"local_euler": [3.14159, 0.0, 0.0]
},
"chips": {
"local_position": [0.0, 0.0, 0.10],
"local_euler": [3.14159, 0.0, 0.0]
},
"banana": {
"local_position": [0.0, 0.0, 0.01],
"local_euler": [3.14159, 0.0, 0.0]
},
"default": {
"local_position": [0.0, 0.0, 0.0],
"local_euler": [3.14159, 0.0, 0.0]
}
}
```
`local_position` = offset TCP so với tâm vật (m); `local_euler` = hướng kẹp trong hệ vật (rad). `[π,0,0]` = kẹp thẳng từ trên xuống.
### Module 3 — `robot_controller.py`
IK + quỹ đạo pick 3 pha an toàn.
- `move_to_pose(pos, ori, steps)`: giải IK (`p.calculateInverseKinematics`) rồi **nội suy trong không gian khớp** để chuyển động mượt.
- `pick(object_id, grasp_pos, grasp_ori)`:
1. Mở kẹp + di tới **pre-grasp** (cao hơn điểm gắp 10 cm).
2. Hạ thẳng xuống grasp pose, **đóng kẹp với lực và liên kết đã tính** (nhằm đảm bảo không tuột).
3. Nhấc vật lên (lift 20 cm trên mặt bàn).
- `place(target_pos)`: di lên trên đích → hạ xuống → mở kẹp → rút lên.
- `isolate_object_collisions(id)`: **chỉ má ngón mới va chạm với vật**, vô hiệu hóa va chạm của mọi link tay khác trong lúc tiếp cận → tránh huých lệch vật trước khi kẹp.
### Module 4 — `gripper_controller.py`
Mô hình lực kẹp dựa trên vật lý thật.
- `calculate_optimal_force(object_id)`: đọc khối lượng + ma sát qua `p.getDynamicsInfo`, áp công thức **lực kẹp ma sát tối thiểu**:
```
F_g = m · (g + a) · Sf / (n_contacts · μ)
```
rồi **kẹp vào ngưỡng phần cứng [40 N, 140 N]**. Bền với input suy biến: μ→0 không gây inf/NaN (bão hòa về max), mass âm → về sàn 40 N.
- `open()` / `close(force)` / `grasp(object_id)`: điều khiển ngón qua `setJointMotorControl2` và tạo liên kết vật lý (`pb.createConstraint`) để gắp chắc chắn hơn.
- `is_holding(object_id)`: True nếu má ngón kẹp tiếp xúc và giữ chặt vật thể.
### LLM Agent — `llm_agent.py`
- **`RuleBasedPlanner`**: khớp từ khóa song ngữ EN/VI (`banana/chuối`, `can/súp`, `chips/bim bim/snack`, `gắp/pick`, `tray/khay`, `Slot_N`...) và xuất kế hoạch — **chạy offline, không cần API key**.
- **`RemoteLLMPlanner`**: gọi LLM thật qua API OpenAI-compatible (OpenAI mặc định), cùng schema kế hoạch JSON.
**Bật LLM thật** — cần `pip install openai python-dotenv`, rồi đặt key trong `.env` (tự nạp) hoặc biến môi trường:
```dotenv
# .env (đã được .gitignore — KHÔNG commit)
OPENAI_API_KEY=sk-proj-...
# OPENAI_MODEL=gpt-4o-mini # tùy chọn (mặc định gpt-4o-mini)
```
Chạy bằng cờ CLI:
```bash
python main.py --llm openai -c "gắp quả chuối đặt vào khay"
python main.py --gui --llm openai # shell tương tác, planner OpenAI
```
---
## 6. Kiểm thử
```bash
pytest tests/ -v # 17 test, tất cả pass thành công
```
| Nhóm test | Nội dung |
| --- | --- |
| **Bất biến phép biến đổi** | Offset grasp **không đổi** khi xoay vật 0/45/90/135/180° |
| **Lực kẹp** | Lực kẹp hợp lệ trong dải [40 N, 140 N] với mọi giá trị mass/ma sát |
| **Grasp stability (tích hợp)** | Gắp lon súp → tịnh tiến nhanh → kiểm tra vật **không tuột/rơi** (sai số < 0.10 m) |
---
## 7. Khắc phục sự cố
| Hiện tượng | Nguyên nhân / cách xử lý |
| --- | --- |
| `--gui` không mở cửa sổ | Máy headless (không có màn hình). Bỏ `--gui` để chạy DIRECT. |
| Lỗi `Connection ... GUI` | Đang chạy qua SSH không X-forwarding. Dùng `ssh -X` hoặc headless. |
| Robot không với tới đích | Đích ngoài vùng làm việc — giữ slot trong x∈[0.4,0.6], y∈[±0.15]. |
| Vật tuột khi nhấc | Tăng lực kẹp của ngón, hoặc giảm khối lượng/tốc độ của cánh tay. |
| Planner trả kế hoạch rỗng | Câu lệnh không khớp tên/loại vật hoặc thiếu đích (`tray`/`Slot_N`). |
---
## 8. Cấu trúc thư mục
```
C2-App-151/
├── main.py # Executor + entry point (CLI)
├── requirements.txt
├── README_LLM_PANDA.md # (file này)
├── pybullet-object-models.zip # File nén chứa mô hình vật thể YCB thực tế
├── pybullet-object-models/ # Thư mục giải nén chứa package pybullet_object_models cục bộ
├── llm_panda/
│ ├── __init__.py
│ ├── config.py # hình học + kết nối + hằng số vật lý (đã validate IK)
│ ├── scene_manager.py # Module 1
│ ├── grasp_planner.py # Module 2
│ ├── robot_controller.py # Module 3
│ ├── gripper_controller.py # Module 4
│ ├── llm_agent.py # NL → function-call plan
│ └── data/grasp_database.json
```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230# Phân Tích Toàn Diện Hệ Thống LLM-Panda
Tài liệu này cung cấp một cái nhìn chi tiết và toàn diện về kiến trúc hệ thống, luồng dữ liệu, các thuật toán cốt lõi, logic điều khiển và các ràng buộc vật lý/an toàn của kho lưu trữ **LLM-Panda** (ngoại trừ phần frontend).
---
## 1. Tổng Quan Hệ Thống
Hệ thống **LLM-Panda** là một ứng dụng mô phỏng cánh tay robot công nghiệp **Franka Emika Panda** trong môi trường vật lý **PyBullet**. Mục tiêu chính của hệ thống là nhận các câu lệnh điều khiển bằng ngôn ngữ tự nhiên (tiếng Anh hoặc tiếng Việt), phân tích trạng thái môi trường hiện tại, lập kế hoạch hành động (planning), kiểm tra tính khả thi và an toàn (verification), sau đó thực thi các chuyển động vật lý để thực hiện các tác vụ gắp và thả vật thể (Pick-and-Place) các vật thể thuộc tập dữ liệu YCB (như chuối, lon súp, lon chips) trên một mặt bàn có các ô chứa (slots) hoặc khay (tray).
---
## 2. Kiến Trúc Các Thành Phần (Component Architecture)
Hệ thống được tổ chức dạng module rõ ràng, phân tách giữa phần lập kế hoạch logic và phần thực thi phần cứng/vật lý:
```mermaidflowchart TB subgraph Planning ["Lập kế hoạch & An toàn"] Agent["llm_agent.py<br/>(LLMAgent)"] Rule["llm_agent.py<br/>(RuleBasedPlanner)"] Remote["llm_agent.py<br/>(RemoteLLMPlanner)"] Verifier["plan_verifier.py<br/>(PlanVerifier)"] end
subgraph Execution ["Thực thi Mô phỏng & Vật lý"] Sim["main.py<br/>(PandaSimulation)"] Scene["scene_manager.py<br/>(SceneManager)"] Grasp["grasp_planner.py<br/>(GraspPlanner)"] Robot["robot_controller.py<br/>(RobotController)"] Gripper["gripper_controller.py<br/>(GripperController)"] end
subgraph ConfigData ["Cấu hình & Dữ liệu"] Config["config.py<br/>(Hình học, Lực, Khớp)"] GDB["data/grasp_database.json<br/>(Toạ độ grasp cục bộ)"] end
Sim --> Agent Sim --> Scene Sim --> Robot Sim --> Gripper Sim --> Grasp Agent --> Rule Agent --> Remote Agent --> Verifier
Scene --> Config Robot --> Config Gripper --> Config Grasp --> Config Grasp --> GDB```
### Chi tiết các file trong `llm_panda/`:
1. **[config.py](file:///c:/Users/admin/C2-App-151/llm_panda/config.py)**: Chứa toàn bộ hằng số hình học và tham số vật lý của hệ thống. * *Kích thước & Vị trí bàn*: Tâm bàn `(0.5, 0.0)`, chiều cao mặt bàn `TABLE_TOP_Z = 0.30` m. * *Lưới Slots*: Gồm 6 ô cố định từ `Slot_1` đến `Slot_6` sắp xếp thành 2 hàng, 3 cột trên bàn. * *Khay chứa (Tray)*: Kích thước $40 \times 28$ cm tại vị trí `(0.5, 0.45, 0.30)`. * *Giới hạn robot*: Chỉ số các khớp xoay cánh tay (0-6), khớp tịnh tiến ngón tay (9, 10), và điểm kẹp cuối TCP (11). * *Lực*: Lực kẹp ngón tay tối thiểu `40.0` N, tối đa `140.0` N. Lực dẫn động cánh tay tối đa `200.0` N. * *Quỹ đạo*: Chiều cao nâng chuẩn khi tiếp cận `PRE_GRASP_HEIGHT = 10` cm, chiều cao nâng di chuyển `LIFT_HEIGHT = 25` cm. (Check)2. **[scene_manager.py](file:///c:/Users/admin/C2-App-151/llm_panda/scene_manager.py) (Module 1 - Quản lý Cảnh)**: * Theo dõi danh sách các body ID vật thể trong PyBullet (`banana`, `soup_can`, `chips_can`). * Ánh xạ toạ độ vật lý $x, y, z$ của vật thể thành các nhãn logic: `Slot_1`..`Slot_6`, `tray`, hoặc `elsewhere` dựa trên khoảng cách planar. * Quản lý **Occupancy Grid**: Lưới raster 2D mặt bàn (độ phân giải 1cm) để tính toán vùng chiếm dụng và tìm vị trí trống an toàn (`find_free_placements`) bằng thuật toán Summed-Area Table (SAT).3. **[grasp_planner.py](file:///c:/Users/admin/C2-App-151/llm_panda/grasp_planner.py) (Module 2 - Kế Hoạch Gắp)**: * Chuyển đổi toạ độ gắp từ hệ toạ độ cục bộ (object frame) trong `grasp_database.json` sang hệ toạ độ thế giới (world frame) dựa trên tư thế hiện tại của vật thể thông qua phép nhân ma trận biến đổi rigid transform (`pb.multiplyTransforms`). Phép toán này giúp điểm gắp bất biến khi vật thể bị xoay (rotation-invariant). * Cung cấp phương án dự phòng (fallback) gắp từ trên xuống tại tâm AABB nếu vật thể không có trong database.4. **[robot_controller.py](file:///c:/Users/admin/C2-App-151/llm_panda/robot_controller.py) (Module 3 - Bộ Điều Khiển Robot)**: * Giải động học nghịch (Inverse Kinematics - IK) cho 7 khớp của robot. * Kiểm tra khả năng chạm tới (reachability) và phát hiện va chạm tự động của cánh tay với bàn/khay. * Điều khiển chuyển động nội suy mượt mà qua các khớp. * Tính toán chiều cao tránh vật cản động dựa trên các vật thể nằm trên hành lang di chuyển (`_get_corridor_max_z`). * Tự động cách ly va chạm trong quá trình tiếp cận để tránh robot chạm lệch vật trước khi kẹp.5. **[gripper_controller.py](file:///c:/Users/admin/C2-App-151/llm_panda/gripper_controller.py) (Module 4 - Bộ Điều Khiển Kẹp)**: * Tính toán lực kẹp tối ưu dựa trên khối lượng và hệ số ma sát của vật thể được đọc từ môi trường mô phỏng. * Sử dụng cơ chế **Rigid Constraint** (`JOINT_FIXED`) trong PyBullet để cố định vật thể vào tay robot khi gắp thành công, giúp mô phỏng ổn định, không bị rung lắc vật lý hoặc tuột vật.6. **[llm_agent.py](file:///c:/Users/admin/C2-App-151/llm_panda/llm_agent.py) (Planning Layer)**: * Đóng vai trò là Manager tiếp nhận lệnh từ người dùng và trạng thái cảnh từ Scene Manager để dịch sang một chuỗi hành động thô gồm: `pick_up`, `move_to`, `place_down`. * **RuleBasedPlanner**: Lập kế hoạch cục bộ, bilingual (Anh/Việt) dựa trên từ khoá, tính toán khoảng cách để tự động dọn vật cản (obstacle clearing) và tự động cất vật đang cầm trước khi gắp vật mới. Có cơ chế nhận diện từ khoá "lại" để chạy lại plan gần nhất. * **RemoteLLMPlanner**: Lập kế hoạch bằng LLM thông qua API tương thích OpenAI (như OpenAI, DeepSeek, Gemini). Có prompt hệ thống chi tiết mô tả đầy đủ các ràng buộc vật lý, không gian làm việc và dọn dẹp vật cản. Hỗ trợ cơ chế exponential backoff khi gặp lỗi giới hạn tần suất gọi API (Rate Limit 429).7. **[plan_verifier.py](file:///c:/Users/admin/C2-App-151/llm_panda/plan_verifier.py) (Safety Layer)**: * Kiểm tra tĩnh tính khả thi cấu trúc của kế hoạch trước khi thực thi nhằm phát hiện sớm các lỗi nghiêm trọng (ví dụ: gắp vật không tồn tại, gắp vật ngoài tầm với, gắp liên tiếp 2 vật, đặt vật khi tay trống).
---
## 3. Quy Trình Luồng Dữ Liệu & Thực Thi (Data & Control Flow)
Quy trình xử lý một câu lệnh của hệ thống diễn ra theo các bước tuần tự sau:
```mermaidsequenceDiagram autonumber actor User as Người dùng participant Sim as PandaSimulation (main.py) participant Scene as SceneManager participant Agent as LLMAgent participant PV as PlanVerifier participant GP as GraspPlanner participant RC as RobotController participant GC as GripperController participant PB as PyBullet
User->>Sim: Nhập lệnh NL (ví dụ: "gắp chuối bỏ vào khay") Sim->>Scene: get_scene_state(reachability_fn, carried_object) Scene->>PB: getBasePositionAndOrientation / getAABB Scene-->>Sim: Trạng thái cảnh JSON (vị trí logic, occupancy, reachability) Sim->>Agent: plan(nl_command, state_json) Agent->>PV: check(plan, state) PV-->>Agent: Trả về danh sách cảnh báo (nếu có) Agent-->>Sim: Trả về danh sách bước hành động hợp lệ (đã lọc schema)
loop Với mỗi hành động trong kế hoạch alt pick_up(object_id) Sim->>GP: compute_grasp_pose(object_id, class) GP->>PB: Đọc tư thế vật thể GP-->>Sim: Trả về grasp_pos, grasp_ori (world frame) Sim->>RC: pick(object_id, grasp_pos, grasp_ori) RC->>RC: Tính toán safe_z (tránh các vật cản dọc đường đi) RC->>PB: Cách ly va chạm (chỉ cho phép finger pads chạm vật) RC->>RC: Di chuyển 3 bước trực giao đến grasp_pos RC->>GC: grasp(object_id) GC->>PB: Tạo khớp liên kết cố định (Fixed Constraint) RC->>RC: Nâng vật lên chiều cao an toàn (lift_z) RC-->>Sim: Trả về kết quả gắp (is_holding=True) else move_to(location_id) Sim->>RC: move_to_pose(above_z ở trên target_pos) RC->>RC: Tính toán above_z dựa trên corridor cản và chiều cao vật cầm RC->>PB: IK + Di chuyển cánh tay Sim->>Sim: Lưu vị trí đích tạm thời (_pending_target_pos) else place_down() Sim->>RC: place(target_pos) RC->>RC: Hạ thẳng đứng xuống target_pos (có cộng thêm clearance và obj_height) RC->>GC: open() GC->>PB: Xoá bỏ Constraint, mở ngón tay kẹp RC->>PB: Snap Z (và XY nếu IK lệch > 5cm) để vật tiếp đất chính xác RC->>RC: Rút cánh tay lên th��ng đứng RC->>PB: Khôi phục va chạm hoàn toàn giữa robot và vật thể Sim->>Sim: Xoá trạng thái vật thể đang cầm end end Sim->>Scene: describe() Scene-->>User: Trả về trạng thái cảnh cuối cùng & Điểm số đạt được```
---
## 4. Các Thuật Toán & Logic Cốt Lõi
### A. Phân Loại Vị Trí Logic (Symbolic Localisation)Nhằm giúp LLM hiểu trạng thái thế giới mà không cần đọc toạ độ float phức tạp, hệ thống chuyển đổi toạ độ 3D thực tế của vật thể về dạng logic:1. **Tray Check**: Tính khoảng cách Euclid trên mặt phẳng XY (Planar Distance) từ vật thể tới tâm Tray. Nếu khoảng cách $\le$ `TRAY_MATCH_RADIUS` (0.22 m) $\rightarrow$ vật thể nằm ở `tray`.2. **Slot Check**: Nếu không ở Tray, tính planar distance từ vật thể tới tâm của 6 Slots. Tìm slot gần nhất. Nếu khoảng cách gần nhất $\le$ `SLOT_MATCH_RADIUS` (0.09 m) $\rightarrow$ vật thể nằm ở Slot đó.3. **Elsewhere**: Nếu cả hai điều kiện trên không thoả mãn $\rightarrow$ vật thể nằm ở `elsewhere` (ví dụ bị rơi khỏi bàn hoặc bị lệch quá xa).
### B. Quản Lý Không Gian Trống Bằng Lưới Chiếm Dụng (Occupancy Grid)Hệ thống duy trì một lưới nhị phân (boolean grid) phủ lên mặt bàn:* **Vùng khảo sát**: Bàn được thu hẹp vào phía trong một khoảng `TABLE_EDGE_MARGIN` (3 cm) để đảm bảo vật đặt không bị chìa ra ngoài mép bàn.* **Rasterization**: Mỗi ô lưới có kích thước `OCCUPANCY_CELL_SIZE = 1` cm. Với mỗi vật thể trên bàn (trừ vật đang được robot cầm), hệ thống lấy hộp bao AABB của nó, tăng rộng ra một khoảng lề an toàn (`PLACEMENT_SAFETY_MARGIN = 3` cm), rồi chiếu xuống lưới XY và đánh dấu các ô tương ứng là `True` (bị chiếm). Các vật nằm ở khay hoặc ngoài bàn sẽ bị bỏ qua.
### C. Tìm Điểm Đặt Trống Bằng Summed-Area Table (SAT)Khi cần tìm vị trí đặt một vật thể có kích thước footprint $(w_x, w_y)$ lên bàn:1. Hệ thống tính toán **Summed-Area Table (SAT)** trên Occupancy Grid. SAT cho phép tính tổng số ô bị chiếm trong bất kỳ cửa sổ chữ nhật cỡ $w_x \times w_y$ nào chỉ trong độ phức tạp thời gian $O(1)$.2. Duyệt qua các cửa sổ khả dĩ trên bàn. Cửa sổ nào có tổng ô chiếm bằng 0 $\rightarrow$ là một điểm đặt hợp lệ.3. Sắp xếp các điểm đặt hợp lệ theo khoảng cách tới tâm bàn (ưu tiên vùng trung tâm dễ với tới hơn).4. Lọc các điểm đặt quá sát nhau (khoảng cách planar $\le \max(w_x, w_y)/2$) để phân tán các ứng viên đồng đều.
### D. Dọn Dẹp Chướng Ngại Vật (Obstacle Clearing)Trong `RuleBasedPlanner` và hướng dẫn prompt của `RemoteLLMPlanner`, khi gắp một vật thể mục tiêu $A$:1. Hệ thống quét các vật thể lân cận $B$ có khoảng cách planar tới $A < \text{NEIGHBOR\_RADIUS}$ (0.14 m trong planner, 0.18 m trong scene state) hoặc nằm trên **hành lang tiếp cận** (`_CORRIDOR_WIDTH = 0.09` m) nối từ gốc toạ độ robot tới vật thể mục tiêu.2. Nếu phát hiện có vật cản $B$ chặn đường gắp, planner tự động chèn thêm chuỗi hành động dọn dẹp trước: $$\text{pick\_up}(B) \rightarrow \text{move\_to}(\text{free\_slot}) \rightarrow \text{place\_down}()$$3. Sau khi dọn dẹp các vật cản, robot mới thực hiện chuỗi hành động gắp vật thể chính $A$.
### E. Tự Động Đổi Hướng Đích Đặt (Redirection)Trong `main.py`, khi robot thực thi lệnh đặt vật xuống một ô chứa (hoặc khay) mà ô đó đã bị chiếm dụng:1. Hệ thống tự động kích hoạt bộ lọc occupancy tại ô đích đó.2. Tìm kiếm các ô chứa trống trong danh sách `reachable_slots` (ưu tiên các ô gần đích đến ban đầu nhất).3. Nếu không có ô chứa trống nào có tên logic, hệ thống gọi `find_free_placements` để tìm một toạ độ trống liên tục trên bàn.4. Nếu tìm thấy điểm trống mới, hệ thống tự động đổi hướng di chuyển (Redirect) sang vị trí đó và ghi nhận cảnh báo lên log (ví dụ: `[REDIR] place_at(Slot_3): footprint blocked → Slot_5`).
### F. Quy Trình Di Chuyển Trực Giao An Toàn (Orthogonal Motion)Để tránh va chạm trong quá trình vận hành, robot không di chuyển theo đường chéo thẳng từ điểm này sang điểm khác mà di chuyển theo các trục trực giao:* **Khi Pick**: 1. Nâng thẳng tay kẹp từ vị trí hiện tại lên độ cao an toàn (`safe_z`). 2. Di chuyển ngang ở độ cao `safe_z` đến điểm phía trên vật thể mục tiêu (`pre-grasp`). 3. Hạ thẳng đứng xuống vị trí gắp (`grasp_pos`).* **Khi Place**: 1. Nâng thẳng tay kẹp đang giữ vật lên độ cao an toàn (`above_z`). 2. Di chuyển ngang đến điểm phía trên vị trí đặt mục tiêu ở độ cao `above_z`. 3. Hạ thẳng đứng xuống vị trí đặt (`place_pos`).
Độ cao an toàn `safe_z` và `above_z` được tính toán động bằng cách quét chiều cao Z lớn nhất của toàn bộ vật thể khác dọc theo hành lang di chuyển XY (`_get_corridor_max_z`), cộng thêm chiều cao vật thể đang giữ và biên độ an toàn 5cm. Giá trị này sau đó được giới hạn bởi chiều cao reachable tối đa của robot tại toạ độ đó để tránh lỗi IK vượt ngưỡng.
### G. Tính Toán Lực Kẹp Vật Lý & Ràng Buộc Cố Định (Grasp Force & Constraint)1. **Lực kẹp**: Hệ thống tính toán lực kẹp cần thiết để nâng vật không bị trượt dựa trên định luật ma sát: $$F_g = \frac{m \cdot (g + a) \cdot S_f}{2 \cdot \mu}$$ Lực này được ép vào khoảng $[40.0, 140.0]$ N.2. **Khớp cố định**: Do mô phỏng PyBullet có thể gặp lỗi trượt ngón tay vật lý khi cánh tay di chuyển nhanh, sau khi ngón tay gripper đóng lại chạm vật, hệ thống tạo ra một liên kết cứng cố định dạng khớp `pb.JOINT_FIXED` giữ chặt vật thể vào tay robot tại toạ độ tương đối lúc đó. Khi đặt vật xuống, liên kết này sẽ được giải phóng hoàn toàn.
---
## 5. Ràng Buộc Hệ Thống & Các Điểm Kiểm Tra An An Toàn (Constraints & Safety)
Hệ thống thiết lập nhiều lớp kiểm tra ràng buộc nghiêm ngặt nhằm tránh các hư hỏng hoặc hành động phi lý trong mô phỏng:
| Loại ràng buộc | Chi tiết ràng buộc | Cách hệ thống xử lý || :--- | :--- | :--- || **Ràng buộc kẹp** | Robot chỉ có 1 tay kẹp, giữ tối đa 1 vật thể tại một thời điểm. | `PlanVerifier` cảnh báo lỗi gắp liên tiếp. `RuleBasedPlanner` tự động chèn lệnh đặt vật hiện tại xuống slot trống trước khi đi gắp vật mới. || **Giới hạn Reachability** | Cánh tay có giới hạn tầm với vật lý và góc khớp. | `RobotController.is_reachable()` kiểm tra trước bằng cách giải IK thử và đo độ lệch TCP thực tế (phải < 2cm). `PlanVerifier` gắn cảnh báo `OUT OF REACH` nếu vật thể ở ngoài tầm với. || **Tránh va chạm bàn/khay** | Cánh tay (các link từ -1 đến 8) không được va quẹt vào bàn hoặc khay trong quá trình di chuyển. | Kiểm tra va chạm cơ học trong hàm `is_reachable` thông qua `pb.getContactPoints()`. Nếu phát hiện va chạm $\rightarrow$ báo vị trí không reachable. || **Cách ly va chạm tiếp cận** | Tránh gripper gạt lệch vật thể trước khi ngón tay kẹp kịp đóng lại. | `RobotController.isolate_object_collisions()` tạm thời tắt va chạm giữa tất cả các khớp robot với vật thể (chỉ mở va chạm ở 2 ngón tay kẹp) trong suốt pha tiếp cận. Va chạm được khôi phục sau khi đặt vật. || **Khắc phục sai lệch IK** | Khi giải IK đến vị trí đặt ở rìa bàn, khớp robot có thể bị lệch XY hoặc Z khiến vật đặt lơ lửng hoặc trôi lệch ô. | Sau khi nhả Constraint gắp, hệ thống thực hiện **Snapping**: thiết lập cứng toạ độ Z của vật thể về đúng mặt tiếp xúc (`target_z + half_height`). Nếu độ lệch XY thực tế so với mục tiêu $> 5$ cm, hệ thống cũng tự động snap toạ độ XY về đúng tâm ô chứa để tránh vật bị rơi ra ngoài bàn. |
---
## 6. Chiến Lược Kiểm Thử (Testing Strategy)
Hệ thống đi kèm một bộ kiểm thử tự động phong phú trong thư mục `tests/`:
1. **Unit Tests Hình Học & Vật Lý (`test_pipeline.py`, `test_occupancy.py`)**: * *Bất biến xoay*: Đảm bảo rằng việc xoay vật thể trên bàn ở góc 45 hay 90 độ không làm thay đổi độ lớn khoảng cách từ điểm gắp thế giới tới tâm vật thể (độ lệch kiểm tra đạt độ chính xác $10^{-6}$ m). * *Giới hạn lực*: Xác minh hàm tính lực kẹp tối ưu luôn nằm trong dải $[40, 140]$ N kể cả với khối lượng cực đoan ($10^{-9}$ kg đến $10^9$ kg) hoặc khi hệ số ma sát bằng 0. * *Mô phỏng chiếm dụng*: Kiểm tra logic tính diện tích bàn bị chiếm, loại trừ vật đang cầm, và thuật toán SAT tránh vùng bị chiếm khi tìm điểm đặt mới.2. **Integration Tests Quy Trình Thực Thi (`test_pipeline.py`, `test_llm_plan.py`)**: * *Độ ổn định khi di chuyển*: Gắp một vật thể thực tế trong PyBullet headless và thực hiện di chuyển cực nhanh (qua 3 waypoints lớn chỉ trong 50 bước mô phỏng). Xác minh vật thể không bị rơi và vẫn duy trì khoảng cách sát tay kẹp ($< 10$ cm). * *Kiểm tra Lập kế hoạch*: Chạy kiểm tra ngoại tuyến `RuleBasedPlanner` và `RemoteLLMPlanner` với các kịch bản thực tế trong `test_llm_expected.json` để đối chiếu kết quả đầu ra khớp 100% với kế hoạch mong đợi.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337# Thiết Kế Hệ Thống Điều Khiển Cánh Tay Robot Bằng Ngôn Ngữ Tự Nhiên (Text & Speech)## Mã dự án: AI20K-161 — AI Điều Khiển Robot Bằng Ngôn Ngữ Tự Nhiên
Tài liệu này trình bày thiết kế hệ thống chi tiết cho ứng dụng mô phỏng và điều khiển cánh tay robot **Franka Emika Panda** bằng ngôn ngữ tự nhiên (Văn bản và Giọng nói). Hệ thống tích hợp khả năng lập kế hoạch của Mô hình ngôn ngữ lớn (LLM), lớp kiểm tra an toàn vật lý, mô phỏng động lực học thời gian thực, và giao diện Web SPA hiện đại được triển khai trên môi trường trực tuyến hoàn chỉnh.
---
## 1. Tổng Quan Kiến Trúc Hệ Thống (System Architecture)
Hệ thống được thiết kế theo kiến trúc hướng dịch vụ (Service-Oriented Architecture), chia nhỏ thành các dịch vụ độc lập giao tiếp qua REST API, WebSockets và RPC để đảm bảo tính sẵn sàng cao, dễ mở rộng và tách biệt trách nhiệm:
```mermaidflowchart TB subgraph Client ["Thiết bị Người Dùng (Client App)"] UI["Web SPA (Three.js + HTML5 Speech)"] end
subgraph API_Gateway ["Cổng API & Quản Lý Người Dùng"] AuthService["Dịch vụ Xác thực & Phân quyền (JWT)"] UserDB[("Cơ sở dữ liệu (PostgreSQL)<br/>Users, Roles, Logs")] end
subgraph Execution_Engine ["Tầng Thực Thi Mô Phỏng & Vật Lý"] FastAPI_WS["FastAPI WebSockets Server"] PyBulletSim["Mô phỏng PyBullet (Headless Instance)"] SceneMgr["SceneManager (Module 1)"] GraspPlan["GraspPlanner (Module 2)"] RobotCtrl["RobotController (Module 3)"] GripperCtrl["GripperController (Module 4)"] end
subgraph Cognitive_Layer ["Tầng Nhận Thức & Lập Kế Hoạch"] STT_Service["Dịch vụ Nhận dạng Giọng nói (STT - Whisper/Web Speech API)"] LLM_Planner["LLMAgent (RuleBased / OpenAI/Claude API)"] Plan_Verifier["PlanVerifier (Static Validation)"] end
%% Giao tiếp UI <-->|WebSockets: Joints, Objects state| FastAPI_WS UI -->|REST API: Login, Manage Users| AuthService UI -->|Speech Input| STT_Service STT_Service -->|Text Command| UI AuthService <--> UserDB FastAPI_WS <--> PyBulletSim PyBulletSim --> SceneMgr PyBulletSim --> GraspPlan PyBulletSim --> RobotCtrl PyBulletSim --> GripperCtrl FastAPI_WS <-->|Prompt & State JSON| LLM_Planner LLM_Planner <-->|Verify Plan| Plan_Verifier```
### Các Dịch Vụ Cốt Lõi (Core Services):
1. **Dịch vụ Frontend Web SPA**: * Xây dựng giao diện web phản hồi nhanh (Responsive SPA). * Tích hợp thư viện **Three.js** để hiển thị mô phỏng 3D thời gian thực thông qua dữ liệu khớp (joint states) và vật thể (object poses) nhận được từ WebSocket. * Tích hợp API nhận diện giọng nói (Web Speech API hoặc Whisper API) để chuyển khẩu lệnh của người dùng thành văn bản ngay trên trình duyệt.2. **Dịch vụ Backend API (FastAPI)**: * Cung cấp các cổng REST API phục vụ đăng nhập, quản lý người dùng, cấp quyền hạn (Roles). * Cung cấp kết nối WebSocket song công (`/ws`) để truyền trạng thái mô phỏng liên tục ở tần số 30 FPS và nhận các câu lệnh thực thi. * Quản lý các tiểu trình mô phỏng (Simulation thread pool) để chạy PyBullet headless trên máy chủ.3. **Dịch vụ Mô phỏng Vật lý (PyBullet Service)**: * Chạy mô phỏng vật lý 3D Franka Panda và các vật thể YCB cục bộ trên máy chủ trong chế độ không giao diện (`pb.DIRECT` mode). * Gửi trạng thái góc khớp (11 khớp) và tư thế 3D của các vật thể qua WebSocket về Client.4. **Dịch vụ Lập kế hoạch LLM (LLMAgent Service)**: * **RuleBasedPlanner**: Lớp lập kế hoạch ngoại tuyến (Offline) dựa trên luật ánh xạ từ khóa song ngữ Anh/Việt. Dành cho chế độ chạy nhanh và không phụ thuộc mạng. * **RemoteLLMPlanner**: Lớp lập kế hoạch trực tuyến kết nối đến các API tương thích OpenAI (GPT-4o-mini, Gemini, DeepSeek). Nhận trạng thái cảnh dạng JSON và trả về chuỗi hành động JSON có cấu trúc.5. **Dịch vụ Kiểm tra Kế hoạch & An toàn (Verification & Safety Service)**: * **PlanVerifier**: Chạy phân tích tĩnh kế hoạch để phát hiện các hành động bất hợp lý trước khi nạp vào robot. * Bộ lọc va chạm vật lý và tính toán lực kẹp an toàn dựa trên khối lượng/ma sát thực của vật thể để ngăn ngừa hư hỏng và tuột vật trong PyBullet.
---
## 2. Thiết Kế Giao Diện & Trải Nghiệm Người Dùng (UI/UX Design)
Giao diện được thiết kế theo phong cách **Glassmorphism** hiện đại, bóng bẩy và mang lại cảm giác cao cấp với các hiệu ứng chuyển động vi mô (micro-animations) và cấu trúc phân vùng rõ ràng.
### A. Triết Lý Thiết Kế Trực Quan (Aesthetic & Style)* **Màu sắc**: Palette màu tối giản tối đậm (Deep Slate/Charcoal `#0f172a`, `#1e293b`) kết hợp với hiệu ứng làm mờ kính nền (backdrop blur) và các viền màu neon tinh tế (xanh dương `#3b82f6` cho hoạt động bình thường, xanh lá `#10b981` cho thành công, cam `#f59e0b` cho cảnh báo, đỏ `#ef4444` cho lỗi).* **Typography**: Sử dụng font chữ **Outfit** (cho tiêu đề, mang hơi hướng công nghệ hiện đại) và **Inter** (cho các thông số kỹ thuật và console log, dễ đọc).* **Chuyển động**: Các nút và thẻ có hiệu ứng hover mượt mà (transition 0.2s), các bước xử lý trong pipeline nhấp nháy đèn LED trạng thái khi đang chạy.
### B. Các Phân Vùng Giao Diện Trên Trang Workspace Chính
Giao diện trang làm việc chính được chia thành 4 khu vực chính:
```┌────────────────────────────────────────────────────────────────────────┐│ [🤖 LLM-Panda Workspace] [👤 Người vận hành: Operator] │├──────────────────────────────────────┬─────────────────────────────────┤│ │ 📊 Trạng Thái Hệ Thống ││ │ ┌───────────────────────────┐ ││ │ │ O LLM Plan -> O Verify │ ││ │ │ O PyBullet -> O Score │ ││ │ └───────────────────────────┘ ││ 3D VIEWPORT ├─────────────────────────────────┤│ (Three.js Visualizer) │ 📋 Kế Hoạch Thực Thi (Task) ││ │ ┌───────────────────────────┐ ││ Hiển thị cánh tay robot Panda │ │ 1. pick_up(banana) │ ││ và vật thể YCB trên bàn │ │ 2. place_at(tray) │ ││ ở chế độ tương tác kéo/xoay/zoom │ └───────────────────────────┘ ││ ├─────────────────────────────────┤│ │ 📺 Console Log Vận Hành ││ │ ┌───────────────────────────┐ ││ │ │ > Đang kết nối server... │ ││ │ │ > Nhận lệnh: gắp lon súp │ ││ │ └───────────────────────────┘ │├──────────────────────────────────────┴─────────────────────────────────┤│ [🎙️] [Nhập câu lệnh điều khiển của bạn...] [Mock Plan 🔘] [Reset 🔄] │└────────────────────────────────────────────────────────────────────────┘```
1. **Khung nhìn mô phỏng 3D (3D Viewport)**: * Chiếm diện tích lớn nhất (bên trái). Vẽ lại chính xác cấu trúc robot và bàn từ dữ liệu PyBullet. * Hỗ trợ tương tác bằng chuột: Kéo chuột trái để xoay camera, kéo chuột phải để di chuyển tiêu điểm camera, cuộn chuột để zoom gần/xa. * Vật thể YCB (như chuối, lon súp, hộp bánh) được nạp texture chân thực từ file `.obj` và `.mtl`. Có tùy chọn hiển thị khung va chạm (collision bounding box) màu xanh dương bán trong suốt để kỹ sư kiểm tra không gian làm việc.2. **Khung điều khiển & Nhận dạng giọng nói (Control Hub)**: * Nằm cố định ở góc dưới màn hình dưới dạng một thanh Glassmorphic nổi. * **Nút micro màu đỏ [🎙️]**: Nhấp để bắt đầu ghi âm giọng nói. Khi người dùng nói (ví dụ: *"gắp quả chuối đặt vào khay"*), sóng âm hiển thị dạng hoạt họa nhấp nháy. Khi dừng nói, hệ thống tự động chuyển đổi thành text và điền vào ô nhập liệu. * **Ô nhập liệu (Input Chatbox)**: Cho phép gõ văn bản trực tiếp. * **Các thẻ gợi ý nhanh (Preset Badges)**: Cung cấp các nút kịch bản dựng sẵn: * `🔌 Sửa đồ điện tử`: Dọn các vật chứa nước ra xa, cất đồ nguy hiểm vào khay. * `🧸 Trẻ em chơi`: Cất dao, pin, đồ thủy tinh dễ vỡ; giữ lại đồ chơi gỗ. * `📚 Bàn học tập`: Xếp sách vở vào trung tâm bàn, dọn rác. * **Nút Reset Scene**: Cho phép hoàn tác, đặt lại vị trí ngẫu nhiên của các vật thể trên bàn (reset seed) và đưa cánh tay về tư thế nghỉ (home pose).3. **Bảng giám sát luồng xử lý (Pipeline Status & Task Plan)**: * Nằm ở góc trên bên phải. Hiển thị 4 bước xử lý tuần tự bằng các biểu tượng bóng đèn LED đổi màu: 1. *LLM Planning* (Xanh dương khi đang lập kế hoạch, Xanh lá khi hoàn tất). 2. *Rule Validation* (Vàng nếu phát hiện cảnh báo tĩnh, Đỏ nếu kế hoạch bị từ chối). 3. *PyBullet Execution* (Nhấp nháy khi cánh tay đang di chuyển vật lý). 4. *Scoring & Feedback* (Hiện kết quả đánh giá rearrangement). * **Task Plan Viewer**: Hiển thị danh sách các kỹ năng thô sẽ được thực hiện (ví dụ: `Step 1: pick_up(banana)`, `Step 2: place_at(Slot_3)`). Bước nào đang chạy sẽ được tô sáng viền neon và có icon chỉ vị trí.4. **Bảng điều khiển Log Vận Hành & Dashboard Kỹ Thuật (Execution Log & Telemetry)**: * Hiển thị log chi tiết dạng dòng chảy console, cuộn tự động. Màu sắc phân biệt rõ ràng: cảnh báo có màu vàng cam, lỗi màu đỏ, các chuyển động kẹp/thả có màu xanh lục. * Telemetry Panel (có thể ẩn/hiện): Hiển thị tọa độ $x,y,z$ thực tế của TCP (Điểm cuối tay kẹp), góc xoay 7 khớp của robot dạng thanh đo (progress bar), lực kẹp hiện tại ($N$) và trạng thái ngón kẹp (đang giữ vật hay trống).
### C. Modal Báo Cáo Kết Quả Rearrangement (Evaluation Report)Khi hoàn thành toàn bộ chuỗi hành động, một modal lớn sẽ hiện lên giữa màn hình với hiệu ứng mờ hậu cảnh:* **Tổng điểm số**: Đánh giá từ `0` đến `100` điểm dựa trên công thức tính điểm rearrangement.* **Bảng chi tiết**: * Thành công trong việc đưa vật thể đích đến đúng slot chỉ định: `+50` điểm. * Thực thi trơn tru toàn bộ kế hoạch không bị lỗi gián đoạn: `+20` điểm. * Không làm xê dịch hay xô đổ các vật thể không liên quan khác: `+30` điểm. * *Trừ điểm*: `-15` điểm cho mỗi vật thể bị xô lệch khỏi slot quy định (knock detection), `-50` điểm nếu vật thể đích chưa đến đúng vị trí, `-30` điểm nếu robot bị kẹt hoặc va chạm thô bạo với bàn.
---
## 3. Luồng Hoạt Động Chi Tiết Của Hệ Thống (Data & Control Flow)
Quy trình khép kín từ khi nhận đầu vào giọng nói/văn bản cho đến khi robot thực thi chuyển động và cập nhật lên màn hình được thể hiện qua biểu đồ tuần tự sau:
```mermaidsequenceDiagram autonumber actor User as Người dùng participant UI as Web SPA (Three.js) participant STT as Dịch vụ STT (Whisper/Web API) participant API as FastAPI Backend participant Sim as PyBullet Engine participant LLM as LLMAgent (Planner) participant PV as PlanVerifier (Safety)
User->>UI: Bấm nút micro và nói câu lệnh UI->>STT: Gửi luồng âm thanh STT-->>UI: Trả về văn bản ("gắp chuối bỏ vào khay") UI->>API: Gửi lệnh văn bản qua WebSocket (type: "run") Note over API, Sim: Backend khóa tương tác người dùng (Lock Input) API->>Sim: Lấy trạng thái không gian (Scene State) hiện tại Sim-->>API: Trả về JSON (Objects, Slots, Occupancy Grid) API->>LLM: Gửi câu lệnh + Trạng thái cảnh dạng JSON LLM->>LLM: Phân rã câu lệnh thành chuỗi hành động JSON LLM->>PV: Chạy kiểm tra an toàn tĩnh (Reachability, Constraints) PV-->>LLM: Trả về kết quả xác minh (Warnings/Errors nếu có) LLM-->>API: Trả về Kế hoạch hành động cuối cùng API->>UI: Stream danh sách bước (Task Plan) để hiển thị lên giao diện loop Với mỗi hành động trong k�� hoạch API->>Sim: Yêu cầu thực thi bước (ví dụ: pick_up, place_at) loop Tần số 30 FPS trong lúc robot di chuyển Sim->>Sim: Giải IK, dịch chuyển các khớp, cập nhật vật lý Sim-->>API: Gửi trạng thái khớp & vị trí vật (Joints, Objects) API-->>UI: Stream gói dữ liệu "state" qua WebSocket UI->>UI: Cập nhật mô hình Three.js (render chuyển động robot mượt mà) end Sim-->>API: Báo cáo hoàn thành bước thực thi end API->>Sim: Tính toán Rearrangement Score cuối cùng Sim-->>API: Trả về điểm số & chi tiết đánh giá API-->>UI: Gửi gói tin "result" (Điểm số, báo cáo Markdown) Note over API, UI: Mở khóa tương tác người dùng (Unlock Input) UI->>User: Hiển thị Modal điểm số & Báo cáo chi tiết```
---
## 4. Các Thuật Toán An Toàn & Ràng Buộc Vật Lý (Safety & Controls)
Để hệ thống hoạt động ổn định, tránh các chuyển động hư hỏng trong mô phỏng vật lý, các thuật toán kiểm tra được phân lớp chặt chẽ:
### A. Kiểm Tra Khả Năng Chạm Tới (Reachability Verification)Trước khi gửi trạng thái cảnh cho LLM, `SceneManager` chạy hàm kiểm tra tính khả thi của điểm gắp:1. Truy vấn vị trí thế giới của vật thể.2. Tra cứu tư thế gắp cục bộ (local grasp pose) trong **Grasp Database** (`grasp_database.json`) để chuyển đổi sang tư thế gắp thế giới (world grasp pose) thông qua phép nhân ma trận biến đổi: $$T_{world\_grasp} = T_{world\_object} \times T_{local\_grasp}$$3. Gọi bộ giải động học nghịch (IK Solver) thử nghiệm trên cánh tay robot. Nếu sai số định vị điểm cuối TCP thực tế so với mục tiêu vượt quá $2$ cm hoặc có va chạm cơ học của robot với bàn $\rightarrow$ Đánh dấu vị trí đó là `Unreachable`.4. Thông tin này được nạp trực tiếp vào prompt JSON gửi LLM để LLM tránh ra lệnh gắp các vật nằm ngoài tầm với hoặc bị kẹt.
### B. Hành Lang Di Chuyển An Toàn & Tránh Va Chạm Động (Safety Corridor)Khi di chuyển giữa các vị trí, robot áp dụng **Quy trình di chuyển trực giao an toàn (Orthogonal Motion)** thay vì di chuyển đường chéo:* **Pha nhấc (Lift)**: Nhấc thẳng tay kẹp lên độ cao an toàn.* **Pha tịnh tiến (Pan)**: Di chuyển ngang ở độ cao an toàn đến điểm nằm ngay trên mục tiêu (`pre-grasp` hoặc `above_place`).* **Pha tiếp cận (Descend)**: Hạ thẳng đứng xuống điểm đích.* **Tính toán độ cao động**: Chiều cao di chuyển an toàn $Z_{safe}$ được tính toán động bằng cách quét tất cả vật thể nằm trong hành lang di chuyển (corridor) rộng $9$ cm kết nối điểm đầu và điểm cuối trên mặt phẳng XY: $$Z_{safe} = \max(Z_{corridor\_objects}) + H_{carried\_object} + \text{Margin (5cm)}$$ Thuật toán này đảm bảo tay kẹp đang giữ vật luôn đi cao hơn tất cả các vật thể cản trên bàn mà không vượt quá giới hạn với tới tối đa của robot.
### C. Quản Lý Không Gian Đặt Bằng Lưới Chiếm Dụng (Occupancy Grid & SAT)Để ngăn LLM đặt chồng vật thể lên nhau hoặc đặt sát mép bàn gây rơi vỡ:1. Mặt bàn được số hóa thành lưới ô vuông kích thước ô $1 \times 1$ cm.2. Các vật thể đang nằm trên bàn sẽ bị chiếu hộp bao AABB xuống lưới XY, cộng thêm biên an toàn $3$ cm xung quanh và đánh dấu các ô này là bị chiếm (`Occupied = True`).3. Khi cần đặt một vật thể mới, hệ thống sử dụng thuật toán **Bảng diện tích tích lũy (Summed-Area Table - SAT)** để tìm kiếm các cửa sổ chữ nhật trống trên bàn có kích thước phù hợp với footprint của vật thể.4. Nếu slot đích mà LLM chọn đã bị chiếm, hệ thống tự động kích hoạt logic **Redirection (Đổi hướng)**: tìm slot trống gần nhất có khả năng với tới, hoặc tìm tọa độ trống liên tục trên bàn bằng SAT, sau đó hướng robot đặt vào vị trí an toàn mới này và phát cảnh báo lên màn hình UI.
### D. Tối Ưu Lực Kẹp Vật Lý & Cách Ly Va Chạm (Grasp Force & Collision Isolation)* **Lực kẹp**: Đọc khối lượng $m$ và hệ số ma sát $\mu$ của vật từ PyBullet, tính toán lực kẹp ma sát tối thiểu để vật không bị trượt khi tay di chuyển với gia tốc $a$: $$F_g = \frac{m \cdot (g + a) \cdot S_f}{2 \cdot \mu}$$ *Trong đó $S_f = 1.5$ (hệ số an toàn), $g = 9.81 m/s^2$.* Lực kẹp được giới hạn cứng trong dải phần cứng cánh tay $[40.0, 140.0]$ N.* **Cách ly va chạm**: Trong suốt pha tiếp cận hạ thẳng đứng để kẹp vật, hệ thống tạm thời vô hiệu hóa va chạm giữa các khớp cánh tay (link 0 đến 8) với vật thể mục tiêu, chỉ cho phép hai ngón tay kẹp (finger pads) có va chạm vật lý với vật. Điều này ngăn robot vô tình huých lệch vật trước khi kẹp đóng lại.* **Khớp cố định (Rigid Constraint)**: Khi kẹp đã đóng sát vật và `is_holding()` xác nhận tiếp xúc, hệ thống tạo một khớp liên kết cứng cố định (`pb.JOINT_FIXED`) giữa tay kẹp và vật thể. Điều này giúp loại bỏ hoàn toàn lỗi rung lắc cơ học hoặc trượt vật do sai số mô phỏng của PyBullet khi robot di chuyển nhanh. Khớp liên kết này được giải phóng ngay khi bắt đầu pha thả vật.
---
## 5. Đăng Nhập, Phân Quyền & Quản Lý Người Dùng (Auth & Roles)
Để đáp ứng tiêu chuẩn phần mềm hoàn chỉnh, hệ thống tích hợp cơ chế quản lý tài khoản và phân quyền vận hành nghiêm ngặt:
### A. Cơ Chế Xác Thực (Authentication)* Sử dụng giao thức **OAuth2 với mã thông báo JWT (JSON Web Tokens)**.* Mã JWT được lưu trữ an toàn trong `HTTPOnly Cookies` ở phía client để chống tấn công XSS.* Mọi yêu cầu kết nối WebSocket `/ws` đều phải truyền kèm token xác thực hợp lệ trong tham số truy vấn hoặc header kết nối.
### B. Các Quyền Hạn Trong Hệ Thống (RBAC - Role-Based Access Control)
Hệ thống phân chia thành 3 vai trò người dùng rõ rệt:
| Vai trò | Quyền hạn trên UI/UX | Quyền hạn Backend & Dịch vụ || :--- | :--- | :--- || **Quản trị viên (Admin)** | Xem toàn bộ workspace, truy cập trang quản trị user, xem lịch sử log toàn hệ thống, thay đổi cấu hình robot. | Toàn quyền thêm/sửa/xóa tài khoản, cấu hình tham số vật lý trong `config.py` qua API, cấu hình LLM Model. || **Người vận hành (Operator)** | Gửi câu lệnh bằng text/speech, chạy và dừng mô phỏng, reset môi trường mô phỏng. | Gọi API lập kế hoạch LLM, điều khiển PyBullet Sim thông qua WebSocket. Không có quyền sửa đổi user khác. || **Người quan sát (Viewer)** | Chỉ xem luồng mô phỏng 3D thời gian thực, xem log console và bảng điểm. Khóa toàn bộ nút điều khiển, micro và chatbox. | Chỉ được phép lắng nghe (subscribe) luồng truyền tải dữ liệu trạng thái qua WebSocket. Bị chặn mọi API điều khiển. |
---
## 6. Kiến Trúc Triển Khai Trực Tuyến (Deployment & Cloud Hosting)
Hệ thống được đóng gói hoàn toàn bằng Docker và triển khai trên máy chủ Cloud/VPS công cộng để người dùng có thể truy cập qua URL Internet công cộng.
### A. Sơ Đồ Triển Khai Container (Docker Composition)
``` ┌────────────────────────┐ │ Nginx Reverse Proxy │ │ (SSL - Port 443) │ └───────────┬────────────┘ │ ┌─────────────────────┴─────────────────────┐ │ Port 80/443 (Web Traffic) │ Port 8000 (WebSocket) ▼ ▼┌─────────────────────────┐ ┌─────────────────────────┐│ Frontend Service │ │ FastAPI Backend ││ (Next.js / Nginx) │ │ (Uvicorn ASGI App) │└─────────────────────────┘ └────────────┬────────────┘ │ ┌────────────────────┴────────────────────┐ ▼ ▼ ┌─────────────────────────┐ ┌─────────────────────────┐ │ Headless PyBullet │ │ Database Instance │ │ (Xvfb Virtual Frame) │ │ (PostgreSQL - Auth) │ └─────────────────────────┘ └────────��────────────────┘```
### B. Giải Pháp Chạy PyBullet Headless Trên Cloud/VPSMột thách thức lớn khi triển khai PyBullet lên các máy chủ VPS đám mây thông thường là máy chủ không có màn hình vật lý (Headless) và không có card đồ họa GPU chuyên dụng:1. **Virtual Framebuffer (Xvfb)**: Backend chạy trong một container Docker chạy hệ điều hành Ubuntu được cài đặt `xvfb` (X virtual framebuffer) và `mesa-utils` (phần mềm kết xuất đồ họa OpenGL bằng CPU).2. **Khởi động Sim**: PyBullet được khởi tạo trong Python bằng cách kết nối ở chế độ `pb.DIRECT` (không dựng hình đồ họa) hoặc `pb.GUI` nhưng được trỏ ra màn hình ảo Xvfb: ```bash # Khởi chạy màn hình ảo ở chế độ background trong Docker entrypoint Xvfb :99 -screen 0 1024x768x24 & export DISPLAY=:99 ```3. **Dựng hình ở Backend**: Các tính toán vật lý, phát hiện va chạm và giải IK hoàn toàn sử dụng CPU của VPS thông qua thư viện PyBullet, sau đó xuất tọa độ góc khớp dạng mảng JSON thô. Việc dịch hình 3D (visual rendering) được đẩy toàn bộ về card đồ họa của máy người dùng cuối (Client-side GPU) thông qua thư viện **Three.js** trên trình duyệt, giúp giảm tải tối đa cho máy chủ VPS và mang lại chuyển động 60fps mượt mà cho người dùng.
---
## 7. Các Tính Năng Hệ Thống Nâng Cao Trải Nghiệm Người Dùng (User-Centric System & Platform Features)
Đối với một hệ thống quản lý và điều khiển robot thực tế chạy trên nền tảng Web/App, ngoài việc mô phỏng chuyển động cơ khí, người dùng cần các tính năng quản lý, phân tích và tương tác trực quan để tối ưu hóa hiệu suất làm việc. Dưới đây là các tính năng hệ thống hướng tới trải nghiệm người dùng (UX) và quản trị vận hành:
### A. Thiết Kế Không Gian & Kịch Bản Trực Quan (Visual Workspace & Scenario Builder)Giúp người dùng tự cấu hình môi trường thử nghiệm và làm việc mà không cần can thiệp vào mã nguồn:* **Kéo thả vật thể trong 3D Viewport**: Người dùng có thể click chọn một vật thể trong không gian Three.js và kéo thả (Drag & Drop) hoặc nhập tọa độ trực tiếp để thay đổi vị trí ban đầu của vật thể trên bàn, thiết lập trạng thái ban đầu của khay và các ô chứa.* **Lưu mẫu thiết lập bàn (Layout Templates)**: Hỗ trợ người dùng lưu các cấu hình không gian này thành các mẫu có sẵn (ví dụ: *"Bàn học tập bừa bộn"*, *"Chuẩn bị lắp ráp linh kiện"*). Người dùng có thể nhanh chóng nạp lại các mẫu này chỉ bằng 1-click để thử nghiệm lại hoặc chia sẻ cho các Operator khác.* **Quản lý Preset Badges**: Giao diện cho phép người quản trị tự tạo, chỉnh sửa hoặc xóa các nút kịch bản nhanh (Preset Badges) trực tiếp trên Web UI, tự định nghĩa Prompt tương ứng cho từng nút thay vì cấu hình tĩnh trong code.
### B. Nhật Ký Câu Lệnh & Tua Lại Chuyển Động (Command History & Replay Timeline)* **Lịch sử lệnh (Command Log Book)**: Bảng lịch sử lưu giữ danh sách tất cả các câu lệnh từng được gửi bởi các người dùng khác nhau trong hệ thống, bao gồm thời gian chạy, người thực hiện, nội dung câu lệnh, mô hình LLM đã dùng, và điểm rearrangement đánh giá.* **Trình phát lại trực quan (Execution Video/3D Playback)**: Người dùng có thể click vào bất kỳ bản ghi lịch sử nào để xem lại quá trình thực thi. Hệ thống cung cấp một thanh trượt thời gian (Timeline Slider) để tua nhanh, tua chậm, tạm dừng chuyển động của robot và vật thể trong Viewport 3D, giúp người dùng hiểu rõ tại sao robot thất bại ở một bước cụ thể.
### C. Quản Lý Thư Viện Vật Thể (Interactive Object Catalog & Asset Library)Trang quản trị dành cho người dùng cấu hình các thuộc tính phi hình học của vật thể:* **Quản lý thuộc tính vật thể**: Xem danh sách các vật thể có trong hệ thống, cấu hình các thuộc tính như: tên định danh (ID), tên ngôn ngữ tự nhiên thường gọi (ví dụ: *"tomato_can"* có các tên gọi phụ như *"lon cà chua"*, *"lon súp"*), khối lượng ($kg$), hệ số ma sát, và tính chất an toàn (ví dụ: *"dễ vỡ"*, *"nguy hiểm"*, *"chứa nước"*).* **Nạp Model 3D tự động**: Hỗ trợ tải lên file 3D Mesh mới (định dạng `.obj`, `.mtl`, hoặc `.gltf`) trực tiếp qua giao diện Web để mở rộng thư viện vật thể mà robot có thể tương tác.
### D. Gợi Ý Câu Lệnh Thông Minh & Hỗ Trợ Nhập Liệu (Smart Autocomplete & AI Recommendation)* **Gợi ý ngữ cảnh (Context-aware Autocomplete)**: Khi người dùng gõ câu lệnh vào khung chat, hệ thống dựa trên trạng thái cảnh hiện tại (Scene State) để gợi ý các từ khóa thích hợp (ví dụ: gõ *"gắp"* sẽ tự động gợi ý *"gắp quả chuối ở Slot_2 bỏ vào Tray"* vì hệ thống phát hiện quả chuối đang ở Slot 2).* **Đề xuất hành động tiếp theo (AI Next-Step Recommendation)**: Phân tích trạng thái cảnh hiện tại và đưa ra các đề xuất hành động cho người dùng. Ví dụ: *"Tôi phát hiện thấy có rác trên bàn học, bạn có muốn tôi 'Dọn dẹp rác bỏ vào thùng' không?"*.
### E. Thống Kê Hiệu Suất Hệ Thống (Performance Analytics Dashboard)Báo cáo trực quan bằng biểu đồ (Charts/Graphs):* **Chỉ số hiệu quả (KPIs)**: Thống kê tỷ lệ thực thi thành công của robot qua các ngày, điểm rearrangement trung bình, thời gian thực thi trung bình cho mỗi tác vụ, và độ trễ trung bình của các mô hình LLM.* **Phân tích lỗi (Error Distribution)**: Vẽ biểu đồ tròn phân tích các nguyên nhân gây lỗi vận hành (ví dụ: do lỗi lập kế hoạch LLM chiếm 20%, do vật thể ngoài tầm với IK chiếm 50%, do trượt ngón kẹp chiếm 30%), giúp người quản lý biết cần tối ưu hóa khâu nào.
### F. Trung Tâm Cảnh Báo & Hỗ Trợ Đa Phương Thức (System Alert Center & Audio Feedback)* **Phản hồi bằng giọng nói (TTS - Text-To-Speech)**: Robot không chỉ nhận giọng nói mà còn phát âm thanh phản hồi lại người dùng: *"Tôi đã hiểu yêu cầu. Tôi sẽ bắt đầu gắp lon snack"* hoặc phát giọng nói cảnh báo: *"Chú ý: Slot 3 đã bị chiếm dụng, tôi sẽ tự động đặt vật thể vào Slot 5"*.
### G. Quản Lý Dự Án & Không Gian Vận Hành (Multi-Workspace Hub)* **Phân vùng dự án (Workspaces)**: Người dùng có thể tạo nhiều không gian làm việc khác nhau (ví dụ: *"Dây chuyền lắp ráp A"*, *"Khu vực phân loại rác B"*), mỗi không gian có thiết lập mô hình robot, danh mục vật thể và các mẫu layout bàn riêng biệt.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181# TrajOpt Implementation Guide (Robot Franka Panda)
## 1. Mục tiêu
Tài liệu này chỉ đặc tả cách cài đặt **TrajOpt** cho bài toán của hệ thống:
- Đầu vào: - Trạng thái khớp hiện tại `q_start` - Grasp pose `T_grasp` (đã được module khác xác định) - Target placement pose `T_target` - Robot model (URDF) - Collision meshes - Môi trường- Đầu ra: - Quỹ đạo khớp liên tục từ `q_start -> grasp -> target`.
TrajOpt **không** sinh grasp pose.TrajOpt **không** giải IK.TrajOpt chỉ tối ưu quỹ đạo.
---
# 2. Biến tối ưu
Mỗi waypoint:
`q_t = [q1,...,q7]`
Toàn bộ trajectory:
`Q=[q1,q2,...,qT]`
Nếu T=30 thì số biến là 210.
TrajOpt tối ưu đồng thời toàn bộ waypoint.
---
# 3. Khởi tạo quỹ đạo
Không sử dụng random, RRT hay PRM.
Khởi tạo bằng nội suy tuyến tính:
- q_start -> q_grasp- q_grasp -> q_target
Quỹ đạo ban đầu được phép xuyên vật cản.
---
# 4. Hàm mục tiêu
Mục tiêu chính:
J = Σ ||q(t+1)-q(t)||²
Có thể bổ sung acceleration cost nếu cần quỹ đạo mượt hơn.
---
# 5. Hard Constraints
## Joint limits
Mọi waypoint đều phải thỏa:
q_min ≤ q_t ≤ q_max
Giới hạn lấy từ URDF.
## Grasp constraint
Waypoint grasp phải thỏa:
FK(q_k)=T_grasp
Đây là hard equality constraint.
## Placement constraint
Waypoint cuối:
FK(q_T)=T_target
Đây cũng là hard equality constraint.
---
# 6. Collision World
TrajOpt không đọc trực tiếp PyBullet.
Cần xây dựng Collision World gồm:
- Robot collision mesh- Object collision mesh- Table- Ground- Static obstacles
Mỗi object cần:
- Mesh- World pose- Collision margin- AABB
Trước mỗi lần planning phải đồng bộ pose từ PyBullet sang Collision World.
---
# 7. Continuous Collision Checking
Không chỉ kiểm tra tại waypoint.
TrajOpt kiểm tra chuyển động giữa hai waypoint liên tiếp.
Đối với mỗi robot link:
- xây dựng swept volume- tính signed distance- lấy contact normal- lấy closest points
Nếu signed distance < d_safe thì sinh gradient đẩy quỹ đạo ra xa vật cản.
---
# 8. Tuyến tính hóa
Khoảng cách va chạm được tuyến tính hóa quanh nghiệm hiện tại:
sd(q) ≈ sd(q0)+∇sd(q0)(q-q0)
Gradient được tính từ:
- contact normal- robot Jacobian
Sau đó chuyển thành ràng buộc tuyến tính trong bài toán QP.
---
# 9. SQP
Mỗi iteration:
1. Forward Kinematics2. Collision Query3. Jacobian4. Linearization5. Xây dựng Quadratic Program6. Giải QP7. Cập nhật trajectory8. Kiểm tra hội tụ
Thông thường 10–30 iteration.
---
# 10. Điều kiện hội tụ
Thuật toán dừng khi:
- Không còn vi phạm khoảng cách an toàn.- Các hard equality constraints được thỏa mãn trong giới hạn chính xác số học của solver.- Chi phí thay đổi giữa hai iteration nhỏ hơn ngưỡng.- Trust region không còn cải thiện nghiệm.
Nếu không hội tụ trước số iteration tối đa thì planner trả về thất bại.
---
# 11. Lưu ý
- TrajOpt không tìm grasp pose.- TrajOpt không giải IK.- IK phải được giải trước.- Collision World phải được cập nhật trước mỗi lần lập kế hoạch.- Khi attach object, collision model phải cập nhật để quỹ đạo sau grasp tính cả vật được gắp.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# Technical Worklog — LLM-Panda
Tài liệu này ghi lại các quyết định kỹ thuật, phân công công việc, và các lỗi quan trọng được phát hiện & sửa chữa trong quá trình phát triển dự án.
---
## [2026-06-18] Sửa Lỗi: Lệnh Gắp Đơn Thuần Tự Động Thả Vào Khay/Slot
### 1. Hiện tượng (Symptom)
* Khi người dùng nhập lệnh yêu cầu gắp vật thể lên đơn thuần mà không chỉ định điểm đến (ví dụ: `"nhấc lon súp"`, `"pick up the chips can"`), robot gắp vật thể lên thành công nhưng ngay lập tức di chuyển tay máy để đặt vật thể đó vào khay (`tray`) hoặc một slot trống ngẫu nhiên.
* Việc tự động thả này là sai yêu cầu nghiệp vụ (lẽ ra robot chỉ được gắp và nhấc giữ vật thể ở tư thế trên không).
### 2. Nguyên nhân gốc rễ (Root Cause)
* Trong System Prompt của `RemoteLLMPlanner` ([llm_agent.py](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/llm_agent.py)), điều kiện ràng buộc loại trừ chỉ cho phép tạo duy nhất hành động `pick_up` khi câu lệnh chứa các từ khóa cụ thể nằm trong tập **`('gắp lên', 'nhặt lên')`**.
* Khi người dùng sử dụng các động từ chỉ hành động gắp khác như `"nhấc"`, `"nhặt"`, `"cầm"`, `"nhấc lên"`, `"cầm lên"`, hoặc tiếng Anh `"pick up"`, `"grab"`, `"lift"`, `"take"`, LLM Planner không khớp được với tập từ khóa này.
* Do schema mặc định quy định đầu ra là một chuỗi tuần tự `[pick_up, place_at]`, LLM tự động suy luận ra một địa điểm trống thích hợp để tạo hành động `place_at` tương ứng dẫn đến hành vi tự động thả.
### 3. Giải pháp (Fix)
* Cập nhật System Prompt trong lớp `RemoteLLMPlanner` ([llm_agent.py](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/llm_agent.py#L274-L278)), mở rộng điều kiện loại trừ:
> *“If the user only asks to pick up / lift / grab / take an object (e.g., 'gắp', 'nhấc', 'nhặt', 'cầm', 'gắp lên', 'nhấc lên', 'nhặt lên', 'cầm lên', 'pick up', 'grab', 'take', 'lift') and does not specify any destination, output ONLY the pick_up action and do NOT append a place_at action.”*
* Điều này ép buộc LLM không được tự ý thêm hành động thả khi câu lệnh gắp không có đích đến cụ thể.
### 4. Kiểm chứng (Verification)
* Thêm các ca kiểm thử hành động đơn lẻ vào `tests/test_prompts.json` dưới dạng `level_1_basic` (như `"gắp lon snack lên"`, `"nhấc lon súp"`, `"pick up the banana"`).
* Chạy thử nghiệm qua `tests/test_auto.py`, các lệnh trên đều trả về JSON Plan chỉ có duy nhất 1 bước `pick_up`, robot gắp vật thể và giữ nguyên trên không đúng như thiết kế.
## [2026-06-18] Sửa Lỗi: Tay Robot Bị Kẹt Vật Lý (Physical Collision)
### 1. Hiện tượng (Symptom)
* Cánh tay robot bị kẹt vật lý khi hạ xuống (descend) gắp hoặc thả vật thể tại khay (tray) hoặc ô (slots) gần đế.
* Lỗi báo: `place: arm deviated X m from target XY` và ở bước tiếp theo báo `TCP is too far from grasp position! Grasp aborted` làm dừng toàn bộ chương trình gắp/thả kế tiếp.
### 2. Nguyên nhân gốc rễ (Root Cause)
* Bộ giải IK (`pb.calculateInverseKinematics`) không có ràng buộc về va chạm vật lý nên đã tính ra các nghiệm khớp có tư thế cùi chỏ hướng xuống (elbow-down) khi cánh tay duỗi xa/gần đế.
* Tư thế khuỷu tay/cánh tay này đè trực tiếp lên mặt bàn/khay (Z = 0.3m, trong khi đế robot ở Z = 0.0m) gây va chạm vật lý, kẹt khớp và lệch vị trí TCP.
### 3. Giải pháp (Fix)
* Cập nhật bộ giải IK trong `RobotController._ik` ([robot_controller.py](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/robot_controller.py)): Truy vấn các giới hạn khớp (`lowerLimits`, `upperLimits`), khoảng khớp (`jointRanges`) và tư thế nghỉ `ARM_REST_POSE` (tư thế cùi chỏ hướng lên - elbow-up) từ cấu hình để truyền làm tham số ràng buộc cho hàm giải IK của PyBullet.
* Cập nhật `RobotController.is_reachable` để kiểm tra thêm va chạm vật lý của cánh tay robot (links từ -1 đến 8) với bàn và khay sau khi giải IK bằng hàm `pb.performCollisionDetection`.
* Truyền thêm `table_id` và `tray_id` cho robot controller trong `main.py` ([main.py](file:///media/minhnht31/data/vinuni/C2-App-151/main.py)).
### 4. Kiểm chứng (Verification)
* Chạy kiểm thử tự động toàn bộ 29 unittests (`pytest`) đều đạt kết quả tốt.
* Xác minh thủ công luồng lệnh bị kẹt trước đó (gắp/thả chips_can vào khay và gắp soup_can từ Slot_5) đã chạy mượt mà, cùi chỏ hướng lên cao và không còn va chạm vật lý với bàn.
## [2026-06-18] Sửa Lỗi: Rung Lắc Cánh Tay, Lọc Vật Thể Rơi & Tránh Gắp Vào Không Khí
### 1. Hiện tượng (Symptom)
* Cánh tay robot bị rung lắc dữ dội khi gắp giữ vật thể lơ lửng trong thời gian chờ (idle), làm hất văng hộp snack (`chips_can`) rơi khỏi bàn xuống đất.
* Hộp snack sau khi rơi xuống đất vẫn báo trạng thái `reachable: true` trong scene state, dẫn đến LLM Planner cố gắp lại và bị trượt (`slipped during lift`).
* Robot gắp quả chuối (`banana`) vào khoảng không khí phía trên quả chuối, làm 2 ngón tay kẹp khép chặt về `0.0 mm` và không có điểm tiếp xúc vật lý (`contacts = [False, False]`), nhưng quả chuối vẫn tự bay lên theo tay robot.
### 2. Nguyên nhân gốc rễ (Root Cause)
* **Rung lắc vật lý**: Xảy ra xung đột lực (feedback loop) giữa mối liên kết kẹp cứng (`pb.createConstraint`) và lực đóng ngón kẹp liên tục (`self.close(force)`) trong lúc chạy mô phỏng thời gian thực (`setRealTimeSimulation(1)`).
* **Tiếp cận vật rơi**: Hàm `is_reachable` chỉ kiểm tra tầm vươn hình học của cánh tay robot chứ chưa lọc bỏ các vật thể đã rơi ra khỏi khu vực làm việc (ranh giới bàn và khay).
* **Gắp vào không khí**: Điểm gắp (TCP) của quả chuối mặc định được tính ở đỉnh cao nhất của hộp bao AABB (`aabb_max[2]`). Vì đầu kẹp của robot Panda (`panda_grasptarget`) nằm ở đầu mút của ngón tay, khi đặt TCP tại đỉnh cao nhất, 2 ngón tay kẹp cơ học sẽ nằm hoàn toàn trên không khí và trượt qua nhau khi đóng lại.
### 3. Giải pháp (Fix)
* **Triệt tiêu rung lắc**: Bổ sung hàm `isolate_gripper_collisions` trong `robot_controller.py` để tạm thời tắt va chạm giữa 2 ngón tay kẹp và vật thể đang giữ ngay sau khi hoàn tất ghi log kiểm chứng tiếp xúc. Va chạm sẽ tự động được khôi phục khi nhả kẹp trong hàm `place`.
* **Lọc vật thể rơi**: Cập nhật hàm `reachability_fn` trong `main.py` để lập tức trả về `False` nếu vật thể nằm ở vị trí ngoài bàn (`"elsewhere"`).
* **Tránh gắp vào không khí**: Cập nhật hằng số độ sâu gắp `_DEPTH_FROM_TOP` trong `grasp_planner.py` ([grasp_planner.py](file:///media/minhnht31/data/vinuni/C2-App-151/llm_panda/grasp_planner.py#L61-L67)) để hạ thấp điểm đặt đầu kẹp xuống dưới đỉnh AABB đối với tất cả các lớp vật thể (chips: 6cm, can: 5cm, banana: 3cm). Điều này giúp 2 ngón tay kẹp đi xuống ôm trọn thân vật thể và tiếp xúc trực tiếp.
* **Cấu hình OpenRouter**: Cập nhật `.env` để chuyển đổi API key, base URL sang OpenRouter nhằm sử dụng mô hình miễn phí `google/gemma-4-31b-it:free`.
### 4. Kiểm chứng (Verification)
* Quan sát cánh tay robot đứng im hoàn toàn ổn định sau khi gắp giữ vật thể lơ lửng, không còn rung lắc.
* Khi gạt thử vật thể rơi xuống đất, scene state lập tức báo `reachable: false`.
* Khi gắp quả chuối, 2 ngón tay kẹp kẹp trúng thân quả chuối, log kiểm chứng báo kích thước kẹp thực tế lớn hơn `0.0 mm` và các điểm tiếp xúc `contacts = [True, True]`..agents/AGENTS.mdAdded+2
.agents/rules/ai-log-hook.mdAdded+37
.agents/rules/caveman.mdAdded+13
.agents/workflows/log.mdAdded+36
.ai-log/.gitkeepAdded
.claude/settings.jsonAdded+38
.codex/hooks.jsonAdded+27
.cursor/hooks.jsonAdded+15
.envAdded+16
.env.exampleAdded+15
.gemini/settings.jsonAdded+42
.github/hooks/hooks.jsonAdded+21
.gitignoreAdded+41
.history/frontend/app_20260627225036.jsAdded+675
.history/frontend/app_20260627231401.jsAdded+511
.history/frontend/app_20260627231409.jsAdded+511
.history/frontend/app_20260627231430.jsAdded+511
.history/frontend/app_20260627231706.jsAdded+1177
.history/frontend/index_20260627225036.cssAdded+595
.history/frontend/index_20260627225036.htmlAdded+125
.history/frontend/index_20260627231836.htmlAdded+1177
.history/frontend/index_20260627231838.htmlAdded+125
.history/frontend/index_20260627231852.htmlAdded+388
.history/frontend/index_20260627232058.cssAdded+569
.history/frontend/index_20260627232102.cssAdded+569
.history/frontend/index_20260627232122.cssAdded+937
.history/frontend/interactive_server_20260627225036.pyAdded+524
.history/frontend/interactive_server_20260627232008.pyAdded+569
.pytest_cache/.gitignoreAdded+2
.pytest_cache/CACHEDIR.TAGAdded+4
.pytest_cache/README.mdAdded+8
.pytest_cache/v/cache/lastfailedAdded+3
.pytest_cache/v/cache/nodeidsAdded+53
.pytest_cache/v/cache/stepwiseAdded+1
DockerfileAdded+45
EVAL_EVIDENCES.mdAdded+163
GeoFIK/README.mdAdded+295
GeoFIK/example_geofik.cppAdded+273
GeoFIK/frames.pngAdded

GeoFIK/geofik.cppAdded+2108
GeoFIK/geofik.hAdded+201
JOURNAL.mdAdded
README.md+117-10
README_LLM_PANDA.mdAdded+265
SYSTEM_ANALYSIS.mdAdded+230
SYSTEM_DESIGN.mdAdded+337
TrajOpt_Implementation_Guide.mdAdded+181
WORKLOG.mdAdded+67
__pycache__/main.cpython-310.pycAdded
debug_log.txtAdded