Done
Browse files
development_logs/2026-07-04_19-13-30_fix-cors-textures-huggingface.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Nhật ký phát triển (Development Log) - 2026-07-04 19:13:30
|
| 2 |
+
|
| 3 |
+
## Yêu cầu của người dùng
|
| 4 |
+
Khắc phục lỗi robot loang lổ màu (phần đen phần trắng) và các đồ vật YCB bị hiển thị đen kịt (pitch black) khi triển khai trên Hugging Face Spaces.
|
| 5 |
+
|
| 6 |
+
## Phạm vi và giả định
|
| 7 |
+
- Chỉ thay đổi cấu hình nạp tài nguyên ở frontend (`app.js`) và cấu hình phản hồi CORS ở backend (`interactive_server.py`).
|
| 8 |
+
- Bảo toàn toàn bộ logic và vật lý của mô phỏng.
|
| 9 |
+
|
| 10 |
+
## File đã thêm/sửa/xóa
|
| 11 |
+
- **Sửa:**
|
| 12 |
+
- [frontend/interactive_server.py](file:///c:/users/admin/Robot/frontend/interactive_server.py)
|
| 13 |
+
- [frontend/app.js](file:///c:/users/admin/Robot/frontend/app.js)
|
| 14 |
+
- **Thêm:**
|
| 15 |
+
- [development_logs/2026-07-04_19-13-30_fix-cors-textures-huggingface.md](file:///c:/users/admin/Robot/development_logs/2026-07-04_19-13-30_fix-cors-textures-huggingface.md)
|
| 16 |
+
|
| 17 |
+
## Hành vi trước và sau
|
| 18 |
+
- **Trước khi sửa:**
|
| 19 |
+
- Trang web chạy trong `iframe` của Hugging Face Spaces chịu chính sách sandbox bảo mật của trình duyệt.
|
| 20 |
+
- Khi Three.js tải các file ảnh texture (`colors.png` cho robot, `texture_map.png` cho đồ vật), trình duyệt chặn không cho nạp WebGL texture do thiếu CORS headers từ máy chủ FastAPI.
|
| 21 |
+
- Kết quả: Các khớp của robot và các đồ vật YCB đều bị tô đen kịt, làm chìm/khó nhìn thấy các đồ vật nhỏ như bóng tennis, quả lê.
|
| 22 |
+
- **Sau khi sửa:**
|
| 23 |
+
- Thêm `CORSMiddleware` cho FastAPI backend ở `interactive_server.py` để gửi đầy đủ các header `Access-Control-Allow-Origin: *`.
|
| 24 |
+
- Cấu hình `MTL_LOADER.setCrossOrigin('anonymous')` ở `app.js` để gửi yêu cầu xác thực CORS khi tải ảnh texture.
|
| 25 |
+
- Kết quả: Toàn bộ robot và các đồ vật YCB được dựng hình đầy đủ màu sắc và họa tiết vân bề mặt chính xác trên Hugging Face Spaces.
|
| 26 |
+
|
| 27 |
+
## Lệnh kiểm tra và kết quả
|
| 28 |
+
- Kiểm tra cú pháp Python: `python -m py_compile frontend/interactive_server.py` thành công.
|
| 29 |
+
- Chạy `git diff -w` để xác định chính xác số dòng thay đổi thực tế chỉ là 9 dòng logic (không tính các dòng chuyển đổi CRLF sang LF tự động của git).
|
| 30 |
+
- `git diff --check` cho thấy không có lỗi khoảng trắng thừa nào.
|
| 31 |
+
|
| 32 |
+
## Tính năng hiện có đã được bảo toàn
|
| 33 |
+
- Khả năng nạp môi trường, kéo thả vật thể, kết nối WebSocket và cập nhật trạng thái khớp robot được giữ nguyên vẹn.
|
| 34 |
+
|
| 35 |
+
## Vấn đề còn lại hoặc việc cần người dùng quyết định
|
| 36 |
+
- Người dùng cần thực hiện push code lên Hugging Face để hoàn tất việc cập nhật và tận hưởng thành quả hiển thị đầy đủ màu sắc.
|
frontend/__pycache__/interactive_server.cpython-310.pyc
CHANGED
|
Binary files a/frontend/__pycache__/interactive_server.cpython-310.pyc and b/frontend/__pycache__/interactive_server.cpython-310.pyc differ
|
|
|
frontend/app.js
CHANGED
|
@@ -6,19 +6,20 @@ let robotGroup, tableMesh, trayMesh;
|
|
| 6 |
const slotHelpers = [];
|
| 7 |
const joints = {};
|
| 8 |
const ycbMeshes = {};
|
| 9 |
-
let isDragging = false;
|
| 10 |
-
let dragPlane = new THREE.Plane();
|
| 11 |
-
let eeDummy = null;
|
| 12 |
-
let placementSurfaceZ = 0.3;
|
| 13 |
const OBJ_LOADER = new THREE.OBJLoader();
|
| 14 |
const MTL_LOADER = new THREE.MTLLoader();
|
| 15 |
-
|
| 16 |
-
let
|
| 17 |
-
|
| 18 |
-
localStorage.
|
| 19 |
-
|
| 20 |
-
let
|
| 21 |
-
let
|
|
|
|
| 22 |
function initVisualizer() {
|
| 23 |
// Set default coordinate system to Z-up
|
| 24 |
THREE.Object3D.DefaultUp.set(0, 0, 1);
|
|
@@ -174,14 +175,14 @@ function animate() {
|
|
| 174 |
}
|
| 175 |
|
| 176 |
// Align eeDummy position to handJoint if not being dragged
|
| 177 |
-
if (eeDummy && joints.handJoint) {
|
| 178 |
const handWorldPos = new THREE.Vector3();
|
| 179 |
joints.handJoint.getWorldPosition(handWorldPos);
|
| 180 |
-
eeDummy.position.copy(handWorldPos);
|
| 181 |
-
}
|
| 182 |
-
updateObjectSelectionOverlay();
|
| 183 |
-
|
| 184 |
-
renderer.render(scene, camera);
|
| 185 |
}
|
| 186 |
// Window resizing
|
| 187 |
window.addEventListener('resize', () => {
|
|
@@ -194,15 +195,15 @@ window.addEventListener('resize', () => {
|
|
| 194 |
}
|
| 195 |
});
|
| 196 |
// ─── Three.js Scene Construction ────────────────────────────────────────────
|
| 197 |
-
function createTable(tableConfig) {
|
| 198 |
if (tableMesh) scene.remove(tableMesh);
|
| 199 |
const ext = tableConfig.half_extents;
|
| 200 |
const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2);
|
| 201 |
const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3));
|
| 202 |
const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 });
|
| 203 |
tableMesh = new THREE.Mesh(geo, mat);
|
| 204 |
-
tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]);
|
| 205 |
-
placementSurfaceZ = Number(tableConfig.top_z || 0.3);
|
| 206 |
tableMesh.castShadow = true;
|
| 207 |
tableMesh.receiveShadow = true;
|
| 208 |
scene.add(tableMesh);
|
|
@@ -384,78 +385,78 @@ function initRobotStructure() {
|
|
| 384 |
eeDummy.visible = false;
|
| 385 |
scene.add(eeDummy);
|
| 386 |
}
|
| 387 |
-
function loadYcbObjects(objectsConfig) {
|
| 388 |
-
// Clear old meshes/groups from scene
|
| 389 |
-
Object.values(ycbMeshes).forEach(group => scene.remove(group));
|
| 390 |
-
for (const key in ycbMeshes) delete ycbMeshes[key];
|
| 391 |
-
clearObjectSelection();
|
| 392 |
-
Object.entries(objectsConfig).forEach(([name, config]) => {
|
| 393 |
-
addYcbObject(name, config);
|
| 394 |
-
});
|
| 395 |
-
}
|
| 396 |
-
|
| 397 |
-
function addYcbObject(name, config) {
|
| 398 |
-
if (!config || !config.folder || !config.web_obj) return null;
|
| 399 |
-
if (ycbMeshes[name]) {
|
| 400 |
-
scene.remove(ycbMeshes[name]);
|
| 401 |
-
delete ycbMeshes[name];
|
| 402 |
-
}
|
| 403 |
-
const objFile = `/assets/ycb/${config.folder}/${config.web_obj}`;
|
| 404 |
-
const mtlFile = config.web_mtl
|
| 405 |
-
? `/assets/ycb/${config.folder}/${config.web_mtl}`
|
| 406 |
-
: "";
|
| 407 |
-
const objectGroup = new THREE.Group();
|
| 408 |
-
objectGroup.name = name;
|
| 409 |
-
objectGroup.position.fromArray(config.initial_pos);
|
| 410 |
-
objectGroup.quaternion.fromArray(config.initial_ori);
|
| 411 |
-
scene.add(objectGroup);
|
| 412 |
-
ycbMeshes[name] = objectGroup;
|
| 413 |
-
|
| 414 |
-
const attachVisual = (objLoader) => {
|
| 415 |
-
objLoader.load(objFile, (visObj) => {
|
| 416 |
-
if (ycbMeshes[name] !== objectGroup) return;
|
| 417 |
-
visObj.traverse(child => {
|
| 418 |
-
if (!child.isMesh) return;
|
| 419 |
-
child.castShadow = true;
|
| 420 |
-
child.receiveShadow = true;
|
| 421 |
-
const materials = Array.isArray(child.material)
|
| 422 |
-
? child.material
|
| 423 |
-
: [child.material];
|
| 424 |
-
materials.filter(Boolean).forEach(material => {
|
| 425 |
-
if (material.map) {
|
| 426 |
-
material.color.setHex(0xffffff);
|
| 427 |
-
material.map.encoding = THREE.sRGBEncoding;
|
| 428 |
-
material.map.needsUpdate = true;
|
| 429 |
-
}
|
| 430 |
-
});
|
| 431 |
-
});
|
| 432 |
-
if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos);
|
| 433 |
-
if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori);
|
| 434 |
-
if (config.vis_scale) visObj.scale.fromArray(config.vis_scale);
|
| 435 |
-
objectGroup.add(visObj);
|
| 436 |
-
});
|
| 437 |
-
};
|
| 438 |
-
if (mtlFile) {
|
| 439 |
-
MTL_LOADER.load(mtlFile, materials => {
|
| 440 |
-
materials.preload();
|
| 441 |
-
const objLoader = new THREE.OBJLoader();
|
| 442 |
-
objLoader.setMaterials(materials);
|
| 443 |
-
attachVisual(objLoader);
|
| 444 |
-
});
|
| 445 |
-
} else {
|
| 446 |
-
attachVisual(new THREE.OBJLoader());
|
| 447 |
-
}
|
| 448 |
-
return objectGroup;
|
| 449 |
-
}
|
| 450 |
-
|
| 451 |
-
function removeYcbObject(name) {
|
| 452 |
-
const group = ycbMeshes[name];
|
| 453 |
-
if (!group) return;
|
| 454 |
-
if (selectedObjectName === name) clearObjectSelection();
|
| 455 |
-
scene.remove(group);
|
| 456 |
-
delete ycbMeshes[name];
|
| 457 |
-
delete targetObjects[name];
|
| 458 |
-
}
|
| 459 |
function updateSimulationState(jointsData, objectsData) {
|
| 460 |
if (jointsData && jointsData.length >= 11) {
|
| 461 |
targetJoints = jointsData;
|
|
@@ -477,7 +478,7 @@ function connectWebSocket() {
|
|
| 477 |
reconnectTimeout = null;
|
| 478 |
}
|
| 479 |
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
| 480 |
-
const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=false&client_id=${runtimeClientId}&last_event_seq=${lastEventSeq}`;
|
| 481 |
|
| 482 |
updateBadgeStatus('disconnected');
|
| 483 |
|
|
@@ -486,15 +487,15 @@ function connectWebSocket() {
|
|
| 486 |
console.log("WebSocket connected.");
|
| 487 |
updateBadgeStatus('connected');
|
| 488 |
};
|
| 489 |
-
socket.onmessage = (event) => {
|
| 490 |
-
const msg = JSON.parse(event.data);
|
| 491 |
-
if (msg.seq) {
|
| 492 |
-
lastEventSeq = Math.max(lastEventSeq, Number(msg.seq));
|
| 493 |
-
localStorage.setItem('llm-panda-last-event-seq', String(lastEventSeq));
|
| 494 |
-
}
|
| 495 |
-
if (msg.generation && ['log', 'plan', 'result', 'execution_status', 'current_step'].includes(msg.type)
|
| 496 |
-
&& Number(msg.generation) < activeGeneration) return;
|
| 497 |
-
handleSocketMessage(msg);
|
| 498 |
};
|
| 499 |
socket.onclose = () => {
|
| 500 |
console.log("WebSocket disconnected.");
|
|
@@ -506,85 +507,85 @@ function connectWebSocket() {
|
|
| 506 |
console.error("WebSocket Error: ", err);
|
| 507 |
};
|
| 508 |
}
|
| 509 |
-
function handleSocketMessage(msg) {
|
| 510 |
-
switch(msg.type) {
|
| 511 |
-
case 'runtime_snapshot': {
|
| 512 |
-
activeGeneration = Number(msg.generation || 0);
|
| 513 |
-
executionState = msg.execution_state || 'idle';
|
| 514 |
-
if (msg.active_prompt) currentPrompt = msg.active_prompt;
|
| 515 |
-
if (msg.state) updateSimulationState(msg.state.joints, msg.state.objects);
|
| 516 |
-
if (msg.events) {
|
| 517 |
-
logConsole.innerHTML = '';
|
| 518 |
-
msg.events.filter(item => item.type === 'log').forEach(item => {
|
| 519 |
-
writeLog(item.message, getLogClass(item.message));
|
| 520 |
-
updatePipelineUI(item.message);
|
| 521 |
-
});
|
| 522 |
-
}
|
| 523 |
-
if (msg.plan && msg.plan.plan) displayPlan(msg.plan.plan);
|
| 524 |
-
if (['idle', 'completed', 'interrupted', 'failed'].includes(executionState)) {
|
| 525 |
-
unlockInput();
|
| 526 |
-
} else {
|
| 527 |
-
lockInput();
|
| 528 |
-
}
|
| 529 |
-
break;
|
| 530 |
-
}
|
| 531 |
-
|
| 532 |
-
case 'command_accepted':
|
| 533 |
-
activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0));
|
| 534 |
-
currentPrompt = msg.prompt || currentPrompt;
|
| 535 |
-
executionState = 'planning';
|
| 536 |
-
lockInput();
|
| 537 |
-
break;
|
| 538 |
-
|
| 539 |
-
case 'execution_status':
|
| 540 |
-
activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0));
|
| 541 |
-
executionState = msg.state || executionState;
|
| 542 |
-
lockInput();
|
| 543 |
-
break;
|
| 544 |
-
|
| 545 |
-
case 'interrupt_requested':
|
| 546 |
-
activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0));
|
| 547 |
-
executionState = 'interrupt_requested';
|
| 548 |
-
lockInput();
|
| 549 |
-
break;
|
| 550 |
-
|
| 551 |
-
case 'interrupted':
|
| 552 |
-
writeLog('Đã dừng lệnh đang thực thi.', 'warn');
|
| 553 |
-
if (msg.generation && Number(msg.generation) < activeGeneration) {
|
| 554 |
-
lockInput();
|
| 555 |
-
} else {
|
| 556 |
-
executionState = 'interrupted';
|
| 557 |
-
unlockInput();
|
| 558 |
-
}
|
| 559 |
-
break;
|
| 560 |
-
|
| 561 |
-
case 'drag_started':
|
| 562 |
-
if (activeDrag) {
|
| 563 |
-
activeDrag.dragId = msg.drag_id;
|
| 564 |
-
activeDrag.type = msg.target_type;
|
| 565 |
-
}
|
| 566 |
-
break;
|
| 567 |
-
|
| 568 |
-
case 'drag_rejected':
|
| 569 |
-
case 'spawn_rejected':
|
| 570 |
-
case 'delete_rejected':
|
| 571 |
-
case 'environment_rejected':
|
| 572 |
-
endActiveDrag(false);
|
| 573 |
-
writeLog(msg.reason || 'Không thể thực hiện thao tác kéo thả.', 'warn');
|
| 574 |
-
break;
|
| 575 |
-
|
| 576 |
-
case 'object_added':
|
| 577 |
-
addYcbObject(msg.name, msg.config);
|
| 578 |
-
if (msg.state) {
|
| 579 |
-
updateSimulationState(null, { [msg.name]: msg.state });
|
| 580 |
-
}
|
| 581 |
-
break;
|
| 582 |
-
|
| 583 |
-
case 'object_removed':
|
| 584 |
-
removeYcbObject(msg.name);
|
| 585 |
-
break;
|
| 586 |
-
|
| 587 |
-
case 'env_list':
|
| 588 |
const envSelect = document.getElementById('env-select');
|
| 589 |
if (envSelect && msg.envs) {
|
| 590 |
envSelect.innerHTML = msg.envs.map(env => `<option value="${env}">${env}</option>`).join('');
|
|
@@ -622,16 +623,16 @@ function handleSocketMessage(msg) {
|
|
| 622 |
speakFeedback(window.currentPlanSummary);
|
| 623 |
break;
|
| 624 |
|
| 625 |
-
case 'result':
|
| 626 |
-
if (['clarify', 'reject'].includes(msg.response_type)) {
|
| 627 |
-
executionState = 'idle';
|
| 628 |
-
unlockInput();
|
| 629 |
-
window.currentPlan = null;
|
| 630 |
-
window.currentLlmTime = 0;
|
| 631 |
-
break;
|
| 632 |
-
}
|
| 633 |
-
executionState = msg.success === false ? 'failed' : 'completed';
|
| 634 |
-
unlockInput();
|
| 635 |
|
| 636 |
// Add new run record to history log dynamically
|
| 637 |
const now = new Date();
|
|
@@ -744,10 +745,10 @@ function renderObjectsTable(catalogMap) {
|
|
| 744 |
const rows = Object.entries(catalogMap).map(([name, config]) => {
|
| 745 |
const displayName = objDict[name] || name;
|
| 746 |
const imageUrl = `/static/thumbnails/${config.folder}.png?v=${new Date().getTime()}`;
|
| 747 |
-
return `
|
| 748 |
-
<tr class="catalog-object-row" draggable="true"
|
| 749 |
-
data-catalog-folder="${config.folder}" data-catalog-name="${name}">
|
| 750 |
-
<td>
|
| 751 |
<div style="width: 50px; height: 50px; overflow: hidden; border-radius: 8px; border: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: center; background: #fff;">
|
| 752 |
<img src="${imageUrl}" alt="${displayName}" style="max-width: 100%; max-height: 100%; object-fit: contain;">
|
| 753 |
</div>
|
|
@@ -757,25 +758,25 @@ function renderObjectsTable(catalogMap) {
|
|
| 757 |
`;
|
| 758 |
});
|
| 759 |
|
| 760 |
-
objectsTableBody.innerHTML = rows.join('');
|
| 761 |
-
objectsTableBody.querySelectorAll('.catalog-object-row').forEach(row => {
|
| 762 |
-
row.addEventListener('dragstart', event => {
|
| 763 |
-
event.dataTransfer.effectAllowed = 'copy';
|
| 764 |
-
event.dataTransfer.setData(
|
| 765 |
-
'application/x-llm-panda-ycb',
|
| 766 |
-
JSON.stringify({
|
| 767 |
-
folder: row.dataset.catalogFolder,
|
| 768 |
-
name: row.dataset.catalogName
|
| 769 |
-
})
|
| 770 |
-
);
|
| 771 |
-
row.classList.add('is-dragging');
|
| 772 |
-
});
|
| 773 |
-
row.addEventListener('dragend', () => {
|
| 774 |
-
row.classList.remove('is-dragging');
|
| 775 |
-
canvas.classList.remove('catalog-drop-target');
|
| 776 |
-
});
|
| 777 |
-
});
|
| 778 |
-
}
|
| 779 |
// 4. History Logs Data & Render
|
| 780 |
const historyData = [];
|
| 781 |
|
|
@@ -1184,31 +1185,31 @@ function displayPlan(plan) {
|
|
| 1184 |
});
|
| 1185 |
}
|
| 1186 |
|
| 1187 |
-
function lockInput() {
|
| 1188 |
-
chatInput.disabled = false;
|
| 1189 |
-
submitBtn.disabled = false;
|
| 1190 |
-
resetBtn.disabled = true;
|
| 1191 |
-
setSubmitButtonMode(true);
|
| 1192 |
-
chatInput.placeholder = 'Nhập lệnh mới rồi Enter để thay thế lệnh hiện tại';
|
| 1193 |
-
}
|
| 1194 |
-
let enterSubmittedFromChatInput = false;
|
| 1195 |
-
chatInput.addEventListener('keydown', (e) => {
|
| 1196 |
-
if (e.key === 'Enter' && !e.shiftKey) {
|
| 1197 |
-
enterSubmittedFromChatInput = true;
|
| 1198 |
-
}
|
| 1199 |
-
});
|
| 1200 |
-
document.getElementById('chat-form').addEventListener('submit', (e) => {
|
| 1201 |
-
e.preventDefault();
|
| 1202 |
-
const submittedWithEnter = enterSubmittedFromChatInput;
|
| 1203 |
-
enterSubmittedFromChatInput = false;
|
| 1204 |
-
const busy = !['idle', 'completed', 'interrupted', 'failed'].includes(executionState);
|
| 1205 |
-
if (busy && e.submitter === submitBtn && !submittedWithEnter) {
|
| 1206 |
-
if (socket && socket.readyState === WebSocket.OPEN) {
|
| 1207 |
-
socket.send(JSON.stringify({ type: 'cancel' }));
|
| 1208 |
-
}
|
| 1209 |
-
return;
|
| 1210 |
-
}
|
| 1211 |
-
const prompt = chatInput.value.trim();
|
| 1212 |
if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return;
|
| 1213 |
currentPrompt = prompt;
|
| 1214 |
chatInput.value = '';
|
|
@@ -1221,31 +1222,31 @@ document.getElementById('chat-form').addEventListener('submit', (e) => {
|
|
| 1221 |
});
|
| 1222 |
window.currentRunStartTime = Date.now();
|
| 1223 |
writeLog(`Gửi yêu cầu: "${prompt}"`, "info");
|
| 1224 |
-
executionState = 'planning';
|
| 1225 |
-
lockInput();
|
| 1226 |
|
| 1227 |
speakFeedback("Start processing your command.");
|
| 1228 |
-
socket.send(JSON.stringify({
|
| 1229 |
-
type: 'run',
|
| 1230 |
prompt: prompt,
|
| 1231 |
mock: false
|
| 1232 |
}));
|
| 1233 |
});
|
| 1234 |
-
function unlockInput() {
|
| 1235 |
-
chatInput.disabled = false;
|
| 1236 |
-
submitBtn.disabled = false;
|
| 1237 |
-
resetBtn.disabled = false;
|
| 1238 |
-
chatInput.placeholder = 'Nhập câu lệnh của bạn cho robot';
|
| 1239 |
-
setSubmitButtonMode(false);
|
| 1240 |
-
}
|
| 1241 |
-
function setSubmitButtonMode(executing) {
|
| 1242 |
-
submitBtn.classList.toggle('is-executing', executing);
|
| 1243 |
-
submitBtn.title = executing ? 'Dừng lệnh đang thực thi' : 'Gửi lệnh';
|
| 1244 |
-
submitBtn.setAttribute('aria-label', submitBtn.title);
|
| 1245 |
-
submitBtn.innerHTML = executing
|
| 1246 |
-
? '<span class="stop-square" aria-hidden="true"></span>'
|
| 1247 |
-
: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>';
|
| 1248 |
-
}
|
| 1249 |
resetBtn.addEventListener('click', () => {
|
| 1250 |
if (!socket || socket.readyState !== WebSocket.OPEN) return;
|
| 1251 |
|
|
@@ -1290,107 +1291,107 @@ slidersList.forEach(id => {
|
|
| 1290 |
});
|
| 1291 |
}
|
| 1292 |
});
|
| 1293 |
-
// 11. Authoritative pointer dragging for YCB objects and robot end-effector
|
| 1294 |
-
const raycaster = new THREE.Raycaster();
|
| 1295 |
-
const mouse = new THREE.Vector2();
|
| 1296 |
-
let hoveredGroup = null;
|
| 1297 |
-
let activeDrag = null;
|
| 1298 |
-
let lastDragUpdateAt = 0;
|
| 1299 |
-
let selectedObjectName = null;
|
| 1300 |
-
let selectionHelper = null;
|
| 1301 |
-
const objectDeleteButton = document.createElement('button');
|
| 1302 |
-
objectDeleteButton.type = 'button';
|
| 1303 |
-
objectDeleteButton.className = 'object-delete-button hidden';
|
| 1304 |
-
objectDeleteButton.textContent = '×';
|
| 1305 |
-
objectDeleteButton.title = 'Xóa vật thể';
|
| 1306 |
-
objectDeleteButton.setAttribute('aria-label', 'Xóa vật thể đã chọn');
|
| 1307 |
-
document.body.appendChild(objectDeleteButton);
|
| 1308 |
-
objectDeleteButton.addEventListener('click', event => {
|
| 1309 |
-
event.stopPropagation();
|
| 1310 |
-
if (
|
| 1311 |
-
selectedObjectName
|
| 1312 |
-
&& socket
|
| 1313 |
-
&& socket.readyState === WebSocket.OPEN
|
| 1314 |
-
) {
|
| 1315 |
-
socket.send(JSON.stringify({
|
| 1316 |
-
type: 'delete_object',
|
| 1317 |
-
name: selectedObjectName
|
| 1318 |
-
}));
|
| 1319 |
-
}
|
| 1320 |
-
});
|
| 1321 |
-
|
| 1322 |
-
function clearObjectSelection() {
|
| 1323 |
-
selectedObjectName = null;
|
| 1324 |
-
if (selectionHelper) {
|
| 1325 |
-
scene.remove(selectionHelper);
|
| 1326 |
-
selectionHelper.geometry.dispose();
|
| 1327 |
-
selectionHelper.material.dispose();
|
| 1328 |
-
selectionHelper = null;
|
| 1329 |
-
}
|
| 1330 |
-
objectDeleteButton.classList.add('hidden');
|
| 1331 |
-
}
|
| 1332 |
-
|
| 1333 |
-
function selectSceneObject(name) {
|
| 1334 |
-
clearObjectSelection();
|
| 1335 |
-
const group = ycbMeshes[name];
|
| 1336 |
-
if (!group) return;
|
| 1337 |
-
selectedObjectName = name;
|
| 1338 |
-
selectionHelper = new THREE.BoxHelper(group, 0xef4444);
|
| 1339 |
-
selectionHelper.material.depthTest = false;
|
| 1340 |
-
selectionHelper.material.transparent = true;
|
| 1341 |
-
selectionHelper.material.opacity = 0.95;
|
| 1342 |
-
selectionHelper.renderOrder = 999;
|
| 1343 |
-
scene.add(selectionHelper);
|
| 1344 |
-
objectDeleteButton.classList.remove('hidden');
|
| 1345 |
-
}
|
| 1346 |
-
|
| 1347 |
-
function updateObjectSelectionOverlay() {
|
| 1348 |
-
if (!selectedObjectName || !selectionHelper) return;
|
| 1349 |
-
const group = ycbMeshes[selectedObjectName];
|
| 1350 |
-
if (!group) {
|
| 1351 |
-
clearObjectSelection();
|
| 1352 |
-
return;
|
| 1353 |
-
}
|
| 1354 |
-
selectionHelper.setFromObject(group);
|
| 1355 |
-
const box = new THREE.Box3().setFromObject(group);
|
| 1356 |
-
const anchor = new THREE.Vector3(
|
| 1357 |
-
(box.min.x + box.max.x) / 2,
|
| 1358 |
-
(box.min.y + box.max.y) / 2,
|
| 1359 |
-
box.max.z + 0.04
|
| 1360 |
-
);
|
| 1361 |
-
anchor.project(camera);
|
| 1362 |
-
const rect = canvas.getBoundingClientRect();
|
| 1363 |
-
objectDeleteButton.style.left =
|
| 1364 |
-
`${rect.left + (anchor.x + 1) * rect.width / 2}px`;
|
| 1365 |
-
objectDeleteButton.style.top =
|
| 1366 |
-
`${rect.top + (-anchor.y + 1) * rect.height / 2}px`;
|
| 1367 |
-
}
|
| 1368 |
-
|
| 1369 |
-
// Helper to determine if an intersected object belongs to a draggable group (YCB or Robot)
|
| 1370 |
-
function findDraggableTarget(hitObject) {
|
| 1371 |
-
let curr = hitObject;
|
| 1372 |
-
while (curr && curr !== scene) {
|
| 1373 |
-
if (curr === robotGroup) {
|
| 1374 |
-
return { type: 'robot_ee', group: robotGroup, name: 'robot' };
|
| 1375 |
-
}
|
| 1376 |
-
const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr);
|
| 1377 |
-
if (ycbEntry) {
|
| 1378 |
-
return { type: 'object', group: ycbEntry[1], name: ycbEntry[0] };
|
| 1379 |
-
}
|
| 1380 |
-
curr = curr.parent;
|
| 1381 |
-
}
|
| 1382 |
-
return null;
|
| 1383 |
-
}
|
| 1384 |
-
|
| 1385 |
-
function updatePointerRay(event) {
|
| 1386 |
-
const rect = canvas.getBoundingClientRect();
|
| 1387 |
-
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
|
| 1388 |
-
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
|
| 1389 |
-
raycaster.setFromCamera(mouse, camera);
|
| 1390 |
-
}
|
| 1391 |
-
|
| 1392 |
-
// Helper to set/restore emissive highlight glow on all child meshes of a group
|
| 1393 |
-
function highlightGroup(group, highlightColor = null) {
|
| 1394 |
if (!group) return;
|
| 1395 |
group.traverse(child => {
|
| 1396 |
if (child.isMesh) {
|
|
@@ -1414,165 +1415,165 @@ function highlightGroup(group, highlightColor = null) {
|
|
| 1414 |
}
|
| 1415 |
}
|
| 1416 |
});
|
| 1417 |
-
}
|
| 1418 |
-
|
| 1419 |
-
function onPointerDown(event) {
|
| 1420 |
-
if (event.button !== 0 || !socket || socket.readyState !== WebSocket.OPEN) return;
|
| 1421 |
-
updatePointerRay(event);
|
| 1422 |
-
const hits = raycaster.intersectObjects(scene.children, true);
|
| 1423 |
-
const hit = hits.find(item => findDraggableTarget(item.object));
|
| 1424 |
-
if (!hit) {
|
| 1425 |
-
clearObjectSelection();
|
| 1426 |
-
return;
|
| 1427 |
-
}
|
| 1428 |
-
const target = findDraggableTarget(hit.object);
|
| 1429 |
-
if (target.type === 'object') {
|
| 1430 |
-
selectSceneObject(target.name);
|
| 1431 |
-
event.preventDefault();
|
| 1432 |
-
return;
|
| 1433 |
-
}
|
| 1434 |
-
|
| 1435 |
-
const planePoint = hit.point.clone();
|
| 1436 |
-
if (target.type === 'robot_ee' && joints.handJoint) {
|
| 1437 |
-
joints.handJoint.getWorldPosition(planePoint);
|
| 1438 |
-
}
|
| 1439 |
-
dragPlane.setFromNormalAndCoplanarPoint(
|
| 1440 |
-
camera.getWorldDirection(new THREE.Vector3()),
|
| 1441 |
-
planePoint
|
| 1442 |
-
);
|
| 1443 |
-
const initialPlaneHit = new THREE.Vector3();
|
| 1444 |
-
raycaster.ray.intersectPlane(dragPlane, initialPlaneHit);
|
| 1445 |
-
activeDrag = {
|
| 1446 |
-
dragId: null,
|
| 1447 |
-
type: target.type,
|
| 1448 |
-
name: target.name,
|
| 1449 |
-
pointerId: event.pointerId,
|
| 1450 |
-
group: target.group,
|
| 1451 |
-
offset: planePoint.clone().sub(initialPlaneHit)
|
| 1452 |
-
};
|
| 1453 |
-
isDragging = true;
|
| 1454 |
-
controls.enabled = false;
|
| 1455 |
-
canvas.setPointerCapture(event.pointerId);
|
| 1456 |
-
const rayTo = raycaster.ray.origin.clone().add(
|
| 1457 |
-
raycaster.ray.direction.clone().multiplyScalar(100)
|
| 1458 |
-
);
|
| 1459 |
-
socket.send(JSON.stringify({
|
| 1460 |
-
type: 'mouse_pick_start',
|
| 1461 |
-
target_type: target.type,
|
| 1462 |
-
object_id: target.name,
|
| 1463 |
-
rayFrom: raycaster.ray.origin.toArray(),
|
| 1464 |
-
rayTo: rayTo.toArray()
|
| 1465 |
-
}));
|
| 1466 |
-
event.preventDefault();
|
| 1467 |
-
}
|
| 1468 |
-
|
| 1469 |
-
function onPointerMove(event) {
|
| 1470 |
-
updatePointerRay(event);
|
| 1471 |
-
if (activeDrag && event.pointerId === activeDrag.pointerId) {
|
| 1472 |
-
const now = performance.now();
|
| 1473 |
-
if (!activeDrag.dragId || now - lastDragUpdateAt < 25) return;
|
| 1474 |
-
lastDragUpdateAt = now;
|
| 1475 |
-
const targetPos = new THREE.Vector3();
|
| 1476 |
-
if (raycaster.ray.intersectPlane(dragPlane, targetPos)) {
|
| 1477 |
-
targetPos.add(activeDrag.offset);
|
| 1478 |
-
socket.send(JSON.stringify({
|
| 1479 |
-
type: 'mouse_pick_update',
|
| 1480 |
-
drag_id: activeDrag.dragId,
|
| 1481 |
-
targetPos: [targetPos.x, targetPos.y, targetPos.z]
|
| 1482 |
-
}));
|
| 1483 |
-
}
|
| 1484 |
-
return;
|
| 1485 |
-
}
|
| 1486 |
-
|
| 1487 |
-
const hits = raycaster.intersectObjects(scene.children, true);
|
| 1488 |
-
const hoverHit = hits.find(item => findDraggableTarget(item.object));
|
| 1489 |
-
const hoverTarget = hoverHit ? findDraggableTarget(hoverHit.object) : null;
|
| 1490 |
-
if (hoverTarget) {
|
| 1491 |
-
if (hoveredGroup !== hoverTarget.group) {
|
| 1492 |
-
if (hoveredGroup) highlightGroup(hoveredGroup, null);
|
| 1493 |
-
hoveredGroup = hoverTarget.group;
|
| 1494 |
-
highlightGroup(hoveredGroup, 0x555555);
|
| 1495 |
-
canvas.style.cursor = 'pointer';
|
| 1496 |
-
}
|
| 1497 |
-
} else {
|
| 1498 |
-
if (hoveredGroup) {
|
| 1499 |
-
highlightGroup(hoveredGroup, null);
|
| 1500 |
-
hoveredGroup = null;
|
| 1501 |
-
}
|
| 1502 |
-
canvas.style.cursor = 'default';
|
| 1503 |
-
}
|
| 1504 |
-
}
|
| 1505 |
-
|
| 1506 |
-
function endActiveDrag(notifyServer = true) {
|
| 1507 |
-
if (!activeDrag) return;
|
| 1508 |
-
if (
|
| 1509 |
-
notifyServer
|
| 1510 |
-
&& activeDrag.dragId
|
| 1511 |
-
&& socket
|
| 1512 |
-
&& socket.readyState === WebSocket.OPEN
|
| 1513 |
-
) {
|
| 1514 |
-
socket.send(JSON.stringify({
|
| 1515 |
-
type: 'mouse_pick_end',
|
| 1516 |
-
drag_id: activeDrag.dragId
|
| 1517 |
-
}));
|
| 1518 |
-
}
|
| 1519 |
-
const pointerId = activeDrag.pointerId;
|
| 1520 |
-
activeDrag = null;
|
| 1521 |
-
isDragging = false;
|
| 1522 |
-
controls.enabled = true;
|
| 1523 |
-
if (canvas.hasPointerCapture(pointerId)) {
|
| 1524 |
-
canvas.releasePointerCapture(pointerId);
|
| 1525 |
-
}
|
| 1526 |
-
}
|
| 1527 |
-
|
| 1528 |
-
function onPointerEnd(event) {
|
| 1529 |
-
if (activeDrag && event.pointerId === activeDrag.pointerId) {
|
| 1530 |
-
endActiveDrag(true);
|
| 1531 |
-
}
|
| 1532 |
-
}
|
| 1533 |
-
|
| 1534 |
-
canvas.addEventListener('pointerdown', onPointerDown);
|
| 1535 |
-
canvas.addEventListener('pointermove', onPointerMove);
|
| 1536 |
-
canvas.addEventListener('pointerup', onPointerEnd);
|
| 1537 |
-
canvas.addEventListener('pointercancel', onPointerEnd);
|
| 1538 |
-
canvas.addEventListener('lostpointercapture', () => endActiveDrag(true));
|
| 1539 |
-
|
| 1540 |
-
canvas.addEventListener('dragover', event => {
|
| 1541 |
-
if (!event.dataTransfer.types.includes('application/x-llm-panda-ycb')) return;
|
| 1542 |
-
event.preventDefault();
|
| 1543 |
-
event.dataTransfer.dropEffect = 'copy';
|
| 1544 |
-
canvas.classList.add('catalog-drop-target');
|
| 1545 |
-
});
|
| 1546 |
-
|
| 1547 |
-
canvas.addEventListener('dragleave', () => {
|
| 1548 |
-
canvas.classList.remove('catalog-drop-target');
|
| 1549 |
-
});
|
| 1550 |
-
|
| 1551 |
-
canvas.addEventListener('drop', event => {
|
| 1552 |
-
event.preventDefault();
|
| 1553 |
-
canvas.classList.remove('catalog-drop-target');
|
| 1554 |
-
if (!socket || socket.readyState !== WebSocket.OPEN) return;
|
| 1555 |
-
let item;
|
| 1556 |
-
try {
|
| 1557 |
-
item = JSON.parse(
|
| 1558 |
-
event.dataTransfer.getData('application/x-llm-panda-ycb')
|
| 1559 |
-
);
|
| 1560 |
-
} catch (_) {
|
| 1561 |
-
return;
|
| 1562 |
-
}
|
| 1563 |
-
updatePointerRay(event);
|
| 1564 |
-
const surfacePlane = new THREE.Plane(
|
| 1565 |
-
new THREE.Vector3(0, 0, 1),
|
| 1566 |
-
-placementSurfaceZ
|
| 1567 |
-
);
|
| 1568 |
-
const position = new THREE.Vector3();
|
| 1569 |
-
if (!raycaster.ray.intersectPlane(surfacePlane, position)) return;
|
| 1570 |
-
socket.send(JSON.stringify({
|
| 1571 |
-
type: 'spawn_catalog_object',
|
| 1572 |
-
folder: item.folder,
|
| 1573 |
-
position: [position.x, position.y, placementSurfaceZ + 0.08]
|
| 1574 |
-
}));
|
| 1575 |
-
});
|
| 1576 |
|
| 1577 |
|
| 1578 |
// Initialize
|
|
|
|
| 6 |
const slotHelpers = [];
|
| 7 |
const joints = {};
|
| 8 |
const ycbMeshes = {};
|
| 9 |
+
let isDragging = false;
|
| 10 |
+
let dragPlane = new THREE.Plane();
|
| 11 |
+
let eeDummy = null;
|
| 12 |
+
let placementSurfaceZ = 0.3;
|
| 13 |
const OBJ_LOADER = new THREE.OBJLoader();
|
| 14 |
const MTL_LOADER = new THREE.MTLLoader();
|
| 15 |
+
MTL_LOADER.setCrossOrigin('anonymous');
|
| 16 |
+
let socket = null;
|
| 17 |
+
let currentPrompt = '';
|
| 18 |
+
const runtimeClientId = localStorage.getItem('llm-panda-client-id') || crypto.randomUUID();
|
| 19 |
+
localStorage.setItem('llm-panda-client-id', runtimeClientId);
|
| 20 |
+
let lastEventSeq = Number(localStorage.getItem('llm-panda-last-event-seq') || 0);
|
| 21 |
+
let activeGeneration = 0;
|
| 22 |
+
let executionState = 'idle';
|
| 23 |
function initVisualizer() {
|
| 24 |
// Set default coordinate system to Z-up
|
| 25 |
THREE.Object3D.DefaultUp.set(0, 0, 1);
|
|
|
|
| 175 |
}
|
| 176 |
|
| 177 |
// Align eeDummy position to handJoint if not being dragged
|
| 178 |
+
if (eeDummy && joints.handJoint) {
|
| 179 |
const handWorldPos = new THREE.Vector3();
|
| 180 |
joints.handJoint.getWorldPosition(handWorldPos);
|
| 181 |
+
eeDummy.position.copy(handWorldPos);
|
| 182 |
+
}
|
| 183 |
+
updateObjectSelectionOverlay();
|
| 184 |
+
|
| 185 |
+
renderer.render(scene, camera);
|
| 186 |
}
|
| 187 |
// Window resizing
|
| 188 |
window.addEventListener('resize', () => {
|
|
|
|
| 195 |
}
|
| 196 |
});
|
| 197 |
// ─── Three.js Scene Construction ────────────────────────────────────────────
|
| 198 |
+
function createTable(tableConfig) {
|
| 199 |
if (tableMesh) scene.remove(tableMesh);
|
| 200 |
const ext = tableConfig.half_extents;
|
| 201 |
const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2);
|
| 202 |
const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3));
|
| 203 |
const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 });
|
| 204 |
tableMesh = new THREE.Mesh(geo, mat);
|
| 205 |
+
tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]);
|
| 206 |
+
placementSurfaceZ = Number(tableConfig.top_z || 0.3);
|
| 207 |
tableMesh.castShadow = true;
|
| 208 |
tableMesh.receiveShadow = true;
|
| 209 |
scene.add(tableMesh);
|
|
|
|
| 385 |
eeDummy.visible = false;
|
| 386 |
scene.add(eeDummy);
|
| 387 |
}
|
| 388 |
+
function loadYcbObjects(objectsConfig) {
|
| 389 |
+
// Clear old meshes/groups from scene
|
| 390 |
+
Object.values(ycbMeshes).forEach(group => scene.remove(group));
|
| 391 |
+
for (const key in ycbMeshes) delete ycbMeshes[key];
|
| 392 |
+
clearObjectSelection();
|
| 393 |
+
Object.entries(objectsConfig).forEach(([name, config]) => {
|
| 394 |
+
addYcbObject(name, config);
|
| 395 |
+
});
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
function addYcbObject(name, config) {
|
| 399 |
+
if (!config || !config.folder || !config.web_obj) return null;
|
| 400 |
+
if (ycbMeshes[name]) {
|
| 401 |
+
scene.remove(ycbMeshes[name]);
|
| 402 |
+
delete ycbMeshes[name];
|
| 403 |
+
}
|
| 404 |
+
const objFile = `/assets/ycb/${config.folder}/${config.web_obj}`;
|
| 405 |
+
const mtlFile = config.web_mtl
|
| 406 |
+
? `/assets/ycb/${config.folder}/${config.web_mtl}`
|
| 407 |
+
: "";
|
| 408 |
+
const objectGroup = new THREE.Group();
|
| 409 |
+
objectGroup.name = name;
|
| 410 |
+
objectGroup.position.fromArray(config.initial_pos);
|
| 411 |
+
objectGroup.quaternion.fromArray(config.initial_ori);
|
| 412 |
+
scene.add(objectGroup);
|
| 413 |
+
ycbMeshes[name] = objectGroup;
|
| 414 |
+
|
| 415 |
+
const attachVisual = (objLoader) => {
|
| 416 |
+
objLoader.load(objFile, (visObj) => {
|
| 417 |
+
if (ycbMeshes[name] !== objectGroup) return;
|
| 418 |
+
visObj.traverse(child => {
|
| 419 |
+
if (!child.isMesh) return;
|
| 420 |
+
child.castShadow = true;
|
| 421 |
+
child.receiveShadow = true;
|
| 422 |
+
const materials = Array.isArray(child.material)
|
| 423 |
+
? child.material
|
| 424 |
+
: [child.material];
|
| 425 |
+
materials.filter(Boolean).forEach(material => {
|
| 426 |
+
if (material.map) {
|
| 427 |
+
material.color.setHex(0xffffff);
|
| 428 |
+
material.map.encoding = THREE.sRGBEncoding;
|
| 429 |
+
material.map.needsUpdate = true;
|
| 430 |
+
}
|
| 431 |
+
});
|
| 432 |
+
});
|
| 433 |
+
if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos);
|
| 434 |
+
if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori);
|
| 435 |
+
if (config.vis_scale) visObj.scale.fromArray(config.vis_scale);
|
| 436 |
+
objectGroup.add(visObj);
|
| 437 |
+
});
|
| 438 |
+
};
|
| 439 |
+
if (mtlFile) {
|
| 440 |
+
MTL_LOADER.load(mtlFile, materials => {
|
| 441 |
+
materials.preload();
|
| 442 |
+
const objLoader = new THREE.OBJLoader();
|
| 443 |
+
objLoader.setMaterials(materials);
|
| 444 |
+
attachVisual(objLoader);
|
| 445 |
+
});
|
| 446 |
+
} else {
|
| 447 |
+
attachVisual(new THREE.OBJLoader());
|
| 448 |
+
}
|
| 449 |
+
return objectGroup;
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
function removeYcbObject(name) {
|
| 453 |
+
const group = ycbMeshes[name];
|
| 454 |
+
if (!group) return;
|
| 455 |
+
if (selectedObjectName === name) clearObjectSelection();
|
| 456 |
+
scene.remove(group);
|
| 457 |
+
delete ycbMeshes[name];
|
| 458 |
+
delete targetObjects[name];
|
| 459 |
+
}
|
| 460 |
function updateSimulationState(jointsData, objectsData) {
|
| 461 |
if (jointsData && jointsData.length >= 11) {
|
| 462 |
targetJoints = jointsData;
|
|
|
|
| 478 |
reconnectTimeout = null;
|
| 479 |
}
|
| 480 |
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
| 481 |
+
const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=false&client_id=${runtimeClientId}&last_event_seq=${lastEventSeq}`;
|
| 482 |
|
| 483 |
updateBadgeStatus('disconnected');
|
| 484 |
|
|
|
|
| 487 |
console.log("WebSocket connected.");
|
| 488 |
updateBadgeStatus('connected');
|
| 489 |
};
|
| 490 |
+
socket.onmessage = (event) => {
|
| 491 |
+
const msg = JSON.parse(event.data);
|
| 492 |
+
if (msg.seq) {
|
| 493 |
+
lastEventSeq = Math.max(lastEventSeq, Number(msg.seq));
|
| 494 |
+
localStorage.setItem('llm-panda-last-event-seq', String(lastEventSeq));
|
| 495 |
+
}
|
| 496 |
+
if (msg.generation && ['log', 'plan', 'result', 'execution_status', 'current_step'].includes(msg.type)
|
| 497 |
+
&& Number(msg.generation) < activeGeneration) return;
|
| 498 |
+
handleSocketMessage(msg);
|
| 499 |
};
|
| 500 |
socket.onclose = () => {
|
| 501 |
console.log("WebSocket disconnected.");
|
|
|
|
| 507 |
console.error("WebSocket Error: ", err);
|
| 508 |
};
|
| 509 |
}
|
| 510 |
+
function handleSocketMessage(msg) {
|
| 511 |
+
switch(msg.type) {
|
| 512 |
+
case 'runtime_snapshot': {
|
| 513 |
+
activeGeneration = Number(msg.generation || 0);
|
| 514 |
+
executionState = msg.execution_state || 'idle';
|
| 515 |
+
if (msg.active_prompt) currentPrompt = msg.active_prompt;
|
| 516 |
+
if (msg.state) updateSimulationState(msg.state.joints, msg.state.objects);
|
| 517 |
+
if (msg.events) {
|
| 518 |
+
logConsole.innerHTML = '';
|
| 519 |
+
msg.events.filter(item => item.type === 'log').forEach(item => {
|
| 520 |
+
writeLog(item.message, getLogClass(item.message));
|
| 521 |
+
updatePipelineUI(item.message);
|
| 522 |
+
});
|
| 523 |
+
}
|
| 524 |
+
if (msg.plan && msg.plan.plan) displayPlan(msg.plan.plan);
|
| 525 |
+
if (['idle', 'completed', 'interrupted', 'failed'].includes(executionState)) {
|
| 526 |
+
unlockInput();
|
| 527 |
+
} else {
|
| 528 |
+
lockInput();
|
| 529 |
+
}
|
| 530 |
+
break;
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
case 'command_accepted':
|
| 534 |
+
activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0));
|
| 535 |
+
currentPrompt = msg.prompt || currentPrompt;
|
| 536 |
+
executionState = 'planning';
|
| 537 |
+
lockInput();
|
| 538 |
+
break;
|
| 539 |
+
|
| 540 |
+
case 'execution_status':
|
| 541 |
+
activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0));
|
| 542 |
+
executionState = msg.state || executionState;
|
| 543 |
+
lockInput();
|
| 544 |
+
break;
|
| 545 |
+
|
| 546 |
+
case 'interrupt_requested':
|
| 547 |
+
activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0));
|
| 548 |
+
executionState = 'interrupt_requested';
|
| 549 |
+
lockInput();
|
| 550 |
+
break;
|
| 551 |
+
|
| 552 |
+
case 'interrupted':
|
| 553 |
+
writeLog('Đã dừng lệnh đang thực thi.', 'warn');
|
| 554 |
+
if (msg.generation && Number(msg.generation) < activeGeneration) {
|
| 555 |
+
lockInput();
|
| 556 |
+
} else {
|
| 557 |
+
executionState = 'interrupted';
|
| 558 |
+
unlockInput();
|
| 559 |
+
}
|
| 560 |
+
break;
|
| 561 |
+
|
| 562 |
+
case 'drag_started':
|
| 563 |
+
if (activeDrag) {
|
| 564 |
+
activeDrag.dragId = msg.drag_id;
|
| 565 |
+
activeDrag.type = msg.target_type;
|
| 566 |
+
}
|
| 567 |
+
break;
|
| 568 |
+
|
| 569 |
+
case 'drag_rejected':
|
| 570 |
+
case 'spawn_rejected':
|
| 571 |
+
case 'delete_rejected':
|
| 572 |
+
case 'environment_rejected':
|
| 573 |
+
endActiveDrag(false);
|
| 574 |
+
writeLog(msg.reason || 'Không thể thực hiện thao tác kéo thả.', 'warn');
|
| 575 |
+
break;
|
| 576 |
+
|
| 577 |
+
case 'object_added':
|
| 578 |
+
addYcbObject(msg.name, msg.config);
|
| 579 |
+
if (msg.state) {
|
| 580 |
+
updateSimulationState(null, { [msg.name]: msg.state });
|
| 581 |
+
}
|
| 582 |
+
break;
|
| 583 |
+
|
| 584 |
+
case 'object_removed':
|
| 585 |
+
removeYcbObject(msg.name);
|
| 586 |
+
break;
|
| 587 |
+
|
| 588 |
+
case 'env_list':
|
| 589 |
const envSelect = document.getElementById('env-select');
|
| 590 |
if (envSelect && msg.envs) {
|
| 591 |
envSelect.innerHTML = msg.envs.map(env => `<option value="${env}">${env}</option>`).join('');
|
|
|
|
| 623 |
speakFeedback(window.currentPlanSummary);
|
| 624 |
break;
|
| 625 |
|
| 626 |
+
case 'result':
|
| 627 |
+
if (['clarify', 'reject'].includes(msg.response_type)) {
|
| 628 |
+
executionState = 'idle';
|
| 629 |
+
unlockInput();
|
| 630 |
+
window.currentPlan = null;
|
| 631 |
+
window.currentLlmTime = 0;
|
| 632 |
+
break;
|
| 633 |
+
}
|
| 634 |
+
executionState = msg.success === false ? 'failed' : 'completed';
|
| 635 |
+
unlockInput();
|
| 636 |
|
| 637 |
// Add new run record to history log dynamically
|
| 638 |
const now = new Date();
|
|
|
|
| 745 |
const rows = Object.entries(catalogMap).map(([name, config]) => {
|
| 746 |
const displayName = objDict[name] || name;
|
| 747 |
const imageUrl = `/static/thumbnails/${config.folder}.png?v=${new Date().getTime()}`;
|
| 748 |
+
return `
|
| 749 |
+
<tr class="catalog-object-row" draggable="true"
|
| 750 |
+
data-catalog-folder="${config.folder}" data-catalog-name="${name}">
|
| 751 |
+
<td>
|
| 752 |
<div style="width: 50px; height: 50px; overflow: hidden; border-radius: 8px; border: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: center; background: #fff;">
|
| 753 |
<img src="${imageUrl}" alt="${displayName}" style="max-width: 100%; max-height: 100%; object-fit: contain;">
|
| 754 |
</div>
|
|
|
|
| 758 |
`;
|
| 759 |
});
|
| 760 |
|
| 761 |
+
objectsTableBody.innerHTML = rows.join('');
|
| 762 |
+
objectsTableBody.querySelectorAll('.catalog-object-row').forEach(row => {
|
| 763 |
+
row.addEventListener('dragstart', event => {
|
| 764 |
+
event.dataTransfer.effectAllowed = 'copy';
|
| 765 |
+
event.dataTransfer.setData(
|
| 766 |
+
'application/x-llm-panda-ycb',
|
| 767 |
+
JSON.stringify({
|
| 768 |
+
folder: row.dataset.catalogFolder,
|
| 769 |
+
name: row.dataset.catalogName
|
| 770 |
+
})
|
| 771 |
+
);
|
| 772 |
+
row.classList.add('is-dragging');
|
| 773 |
+
});
|
| 774 |
+
row.addEventListener('dragend', () => {
|
| 775 |
+
row.classList.remove('is-dragging');
|
| 776 |
+
canvas.classList.remove('catalog-drop-target');
|
| 777 |
+
});
|
| 778 |
+
});
|
| 779 |
+
}
|
| 780 |
// 4. History Logs Data & Render
|
| 781 |
const historyData = [];
|
| 782 |
|
|
|
|
| 1185 |
});
|
| 1186 |
}
|
| 1187 |
|
| 1188 |
+
function lockInput() {
|
| 1189 |
+
chatInput.disabled = false;
|
| 1190 |
+
submitBtn.disabled = false;
|
| 1191 |
+
resetBtn.disabled = true;
|
| 1192 |
+
setSubmitButtonMode(true);
|
| 1193 |
+
chatInput.placeholder = 'Nhập lệnh mới rồi Enter để thay thế lệnh hiện tại';
|
| 1194 |
+
}
|
| 1195 |
+
let enterSubmittedFromChatInput = false;
|
| 1196 |
+
chatInput.addEventListener('keydown', (e) => {
|
| 1197 |
+
if (e.key === 'Enter' && !e.shiftKey) {
|
| 1198 |
+
enterSubmittedFromChatInput = true;
|
| 1199 |
+
}
|
| 1200 |
+
});
|
| 1201 |
+
document.getElementById('chat-form').addEventListener('submit', (e) => {
|
| 1202 |
+
e.preventDefault();
|
| 1203 |
+
const submittedWithEnter = enterSubmittedFromChatInput;
|
| 1204 |
+
enterSubmittedFromChatInput = false;
|
| 1205 |
+
const busy = !['idle', 'completed', 'interrupted', 'failed'].includes(executionState);
|
| 1206 |
+
if (busy && e.submitter === submitBtn && !submittedWithEnter) {
|
| 1207 |
+
if (socket && socket.readyState === WebSocket.OPEN) {
|
| 1208 |
+
socket.send(JSON.stringify({ type: 'cancel' }));
|
| 1209 |
+
}
|
| 1210 |
+
return;
|
| 1211 |
+
}
|
| 1212 |
+
const prompt = chatInput.value.trim();
|
| 1213 |
if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return;
|
| 1214 |
currentPrompt = prompt;
|
| 1215 |
chatInput.value = '';
|
|
|
|
| 1222 |
});
|
| 1223 |
window.currentRunStartTime = Date.now();
|
| 1224 |
writeLog(`Gửi yêu cầu: "${prompt}"`, "info");
|
| 1225 |
+
executionState = 'planning';
|
| 1226 |
+
lockInput();
|
| 1227 |
|
| 1228 |
speakFeedback("Start processing your command.");
|
| 1229 |
+
socket.send(JSON.stringify({
|
| 1230 |
+
type: 'run',
|
| 1231 |
prompt: prompt,
|
| 1232 |
mock: false
|
| 1233 |
}));
|
| 1234 |
});
|
| 1235 |
+
function unlockInput() {
|
| 1236 |
+
chatInput.disabled = false;
|
| 1237 |
+
submitBtn.disabled = false;
|
| 1238 |
+
resetBtn.disabled = false;
|
| 1239 |
+
chatInput.placeholder = 'Nhập câu lệnh của bạn cho robot';
|
| 1240 |
+
setSubmitButtonMode(false);
|
| 1241 |
+
}
|
| 1242 |
+
function setSubmitButtonMode(executing) {
|
| 1243 |
+
submitBtn.classList.toggle('is-executing', executing);
|
| 1244 |
+
submitBtn.title = executing ? 'Dừng lệnh đang thực thi' : 'Gửi lệnh';
|
| 1245 |
+
submitBtn.setAttribute('aria-label', submitBtn.title);
|
| 1246 |
+
submitBtn.innerHTML = executing
|
| 1247 |
+
? '<span class="stop-square" aria-hidden="true"></span>'
|
| 1248 |
+
: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>';
|
| 1249 |
+
}
|
| 1250 |
resetBtn.addEventListener('click', () => {
|
| 1251 |
if (!socket || socket.readyState !== WebSocket.OPEN) return;
|
| 1252 |
|
|
|
|
| 1291 |
});
|
| 1292 |
}
|
| 1293 |
});
|
| 1294 |
+
// 11. Authoritative pointer dragging for YCB objects and robot end-effector
|
| 1295 |
+
const raycaster = new THREE.Raycaster();
|
| 1296 |
+
const mouse = new THREE.Vector2();
|
| 1297 |
+
let hoveredGroup = null;
|
| 1298 |
+
let activeDrag = null;
|
| 1299 |
+
let lastDragUpdateAt = 0;
|
| 1300 |
+
let selectedObjectName = null;
|
| 1301 |
+
let selectionHelper = null;
|
| 1302 |
+
const objectDeleteButton = document.createElement('button');
|
| 1303 |
+
objectDeleteButton.type = 'button';
|
| 1304 |
+
objectDeleteButton.className = 'object-delete-button hidden';
|
| 1305 |
+
objectDeleteButton.textContent = '×';
|
| 1306 |
+
objectDeleteButton.title = 'Xóa vật thể';
|
| 1307 |
+
objectDeleteButton.setAttribute('aria-label', 'Xóa vật thể đã chọn');
|
| 1308 |
+
document.body.appendChild(objectDeleteButton);
|
| 1309 |
+
objectDeleteButton.addEventListener('click', event => {
|
| 1310 |
+
event.stopPropagation();
|
| 1311 |
+
if (
|
| 1312 |
+
selectedObjectName
|
| 1313 |
+
&& socket
|
| 1314 |
+
&& socket.readyState === WebSocket.OPEN
|
| 1315 |
+
) {
|
| 1316 |
+
socket.send(JSON.stringify({
|
| 1317 |
+
type: 'delete_object',
|
| 1318 |
+
name: selectedObjectName
|
| 1319 |
+
}));
|
| 1320 |
+
}
|
| 1321 |
+
});
|
| 1322 |
+
|
| 1323 |
+
function clearObjectSelection() {
|
| 1324 |
+
selectedObjectName = null;
|
| 1325 |
+
if (selectionHelper) {
|
| 1326 |
+
scene.remove(selectionHelper);
|
| 1327 |
+
selectionHelper.geometry.dispose();
|
| 1328 |
+
selectionHelper.material.dispose();
|
| 1329 |
+
selectionHelper = null;
|
| 1330 |
+
}
|
| 1331 |
+
objectDeleteButton.classList.add('hidden');
|
| 1332 |
+
}
|
| 1333 |
+
|
| 1334 |
+
function selectSceneObject(name) {
|
| 1335 |
+
clearObjectSelection();
|
| 1336 |
+
const group = ycbMeshes[name];
|
| 1337 |
+
if (!group) return;
|
| 1338 |
+
selectedObjectName = name;
|
| 1339 |
+
selectionHelper = new THREE.BoxHelper(group, 0xef4444);
|
| 1340 |
+
selectionHelper.material.depthTest = false;
|
| 1341 |
+
selectionHelper.material.transparent = true;
|
| 1342 |
+
selectionHelper.material.opacity = 0.95;
|
| 1343 |
+
selectionHelper.renderOrder = 999;
|
| 1344 |
+
scene.add(selectionHelper);
|
| 1345 |
+
objectDeleteButton.classList.remove('hidden');
|
| 1346 |
+
}
|
| 1347 |
+
|
| 1348 |
+
function updateObjectSelectionOverlay() {
|
| 1349 |
+
if (!selectedObjectName || !selectionHelper) return;
|
| 1350 |
+
const group = ycbMeshes[selectedObjectName];
|
| 1351 |
+
if (!group) {
|
| 1352 |
+
clearObjectSelection();
|
| 1353 |
+
return;
|
| 1354 |
+
}
|
| 1355 |
+
selectionHelper.setFromObject(group);
|
| 1356 |
+
const box = new THREE.Box3().setFromObject(group);
|
| 1357 |
+
const anchor = new THREE.Vector3(
|
| 1358 |
+
(box.min.x + box.max.x) / 2,
|
| 1359 |
+
(box.min.y + box.max.y) / 2,
|
| 1360 |
+
box.max.z + 0.04
|
| 1361 |
+
);
|
| 1362 |
+
anchor.project(camera);
|
| 1363 |
+
const rect = canvas.getBoundingClientRect();
|
| 1364 |
+
objectDeleteButton.style.left =
|
| 1365 |
+
`${rect.left + (anchor.x + 1) * rect.width / 2}px`;
|
| 1366 |
+
objectDeleteButton.style.top =
|
| 1367 |
+
`${rect.top + (-anchor.y + 1) * rect.height / 2}px`;
|
| 1368 |
+
}
|
| 1369 |
+
|
| 1370 |
+
// Helper to determine if an intersected object belongs to a draggable group (YCB or Robot)
|
| 1371 |
+
function findDraggableTarget(hitObject) {
|
| 1372 |
+
let curr = hitObject;
|
| 1373 |
+
while (curr && curr !== scene) {
|
| 1374 |
+
if (curr === robotGroup) {
|
| 1375 |
+
return { type: 'robot_ee', group: robotGroup, name: 'robot' };
|
| 1376 |
+
}
|
| 1377 |
+
const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr);
|
| 1378 |
+
if (ycbEntry) {
|
| 1379 |
+
return { type: 'object', group: ycbEntry[1], name: ycbEntry[0] };
|
| 1380 |
+
}
|
| 1381 |
+
curr = curr.parent;
|
| 1382 |
+
}
|
| 1383 |
+
return null;
|
| 1384 |
+
}
|
| 1385 |
+
|
| 1386 |
+
function updatePointerRay(event) {
|
| 1387 |
+
const rect = canvas.getBoundingClientRect();
|
| 1388 |
+
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
|
| 1389 |
+
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
|
| 1390 |
+
raycaster.setFromCamera(mouse, camera);
|
| 1391 |
+
}
|
| 1392 |
+
|
| 1393 |
+
// Helper to set/restore emissive highlight glow on all child meshes of a group
|
| 1394 |
+
function highlightGroup(group, highlightColor = null) {
|
| 1395 |
if (!group) return;
|
| 1396 |
group.traverse(child => {
|
| 1397 |
if (child.isMesh) {
|
|
|
|
| 1415 |
}
|
| 1416 |
}
|
| 1417 |
});
|
| 1418 |
+
}
|
| 1419 |
+
|
| 1420 |
+
function onPointerDown(event) {
|
| 1421 |
+
if (event.button !== 0 || !socket || socket.readyState !== WebSocket.OPEN) return;
|
| 1422 |
+
updatePointerRay(event);
|
| 1423 |
+
const hits = raycaster.intersectObjects(scene.children, true);
|
| 1424 |
+
const hit = hits.find(item => findDraggableTarget(item.object));
|
| 1425 |
+
if (!hit) {
|
| 1426 |
+
clearObjectSelection();
|
| 1427 |
+
return;
|
| 1428 |
+
}
|
| 1429 |
+
const target = findDraggableTarget(hit.object);
|
| 1430 |
+
if (target.type === 'object') {
|
| 1431 |
+
selectSceneObject(target.name);
|
| 1432 |
+
event.preventDefault();
|
| 1433 |
+
return;
|
| 1434 |
+
}
|
| 1435 |
+
|
| 1436 |
+
const planePoint = hit.point.clone();
|
| 1437 |
+
if (target.type === 'robot_ee' && joints.handJoint) {
|
| 1438 |
+
joints.handJoint.getWorldPosition(planePoint);
|
| 1439 |
+
}
|
| 1440 |
+
dragPlane.setFromNormalAndCoplanarPoint(
|
| 1441 |
+
camera.getWorldDirection(new THREE.Vector3()),
|
| 1442 |
+
planePoint
|
| 1443 |
+
);
|
| 1444 |
+
const initialPlaneHit = new THREE.Vector3();
|
| 1445 |
+
raycaster.ray.intersectPlane(dragPlane, initialPlaneHit);
|
| 1446 |
+
activeDrag = {
|
| 1447 |
+
dragId: null,
|
| 1448 |
+
type: target.type,
|
| 1449 |
+
name: target.name,
|
| 1450 |
+
pointerId: event.pointerId,
|
| 1451 |
+
group: target.group,
|
| 1452 |
+
offset: planePoint.clone().sub(initialPlaneHit)
|
| 1453 |
+
};
|
| 1454 |
+
isDragging = true;
|
| 1455 |
+
controls.enabled = false;
|
| 1456 |
+
canvas.setPointerCapture(event.pointerId);
|
| 1457 |
+
const rayTo = raycaster.ray.origin.clone().add(
|
| 1458 |
+
raycaster.ray.direction.clone().multiplyScalar(100)
|
| 1459 |
+
);
|
| 1460 |
+
socket.send(JSON.stringify({
|
| 1461 |
+
type: 'mouse_pick_start',
|
| 1462 |
+
target_type: target.type,
|
| 1463 |
+
object_id: target.name,
|
| 1464 |
+
rayFrom: raycaster.ray.origin.toArray(),
|
| 1465 |
+
rayTo: rayTo.toArray()
|
| 1466 |
+
}));
|
| 1467 |
+
event.preventDefault();
|
| 1468 |
+
}
|
| 1469 |
+
|
| 1470 |
+
function onPointerMove(event) {
|
| 1471 |
+
updatePointerRay(event);
|
| 1472 |
+
if (activeDrag && event.pointerId === activeDrag.pointerId) {
|
| 1473 |
+
const now = performance.now();
|
| 1474 |
+
if (!activeDrag.dragId || now - lastDragUpdateAt < 25) return;
|
| 1475 |
+
lastDragUpdateAt = now;
|
| 1476 |
+
const targetPos = new THREE.Vector3();
|
| 1477 |
+
if (raycaster.ray.intersectPlane(dragPlane, targetPos)) {
|
| 1478 |
+
targetPos.add(activeDrag.offset);
|
| 1479 |
+
socket.send(JSON.stringify({
|
| 1480 |
+
type: 'mouse_pick_update',
|
| 1481 |
+
drag_id: activeDrag.dragId,
|
| 1482 |
+
targetPos: [targetPos.x, targetPos.y, targetPos.z]
|
| 1483 |
+
}));
|
| 1484 |
+
}
|
| 1485 |
+
return;
|
| 1486 |
+
}
|
| 1487 |
+
|
| 1488 |
+
const hits = raycaster.intersectObjects(scene.children, true);
|
| 1489 |
+
const hoverHit = hits.find(item => findDraggableTarget(item.object));
|
| 1490 |
+
const hoverTarget = hoverHit ? findDraggableTarget(hoverHit.object) : null;
|
| 1491 |
+
if (hoverTarget) {
|
| 1492 |
+
if (hoveredGroup !== hoverTarget.group) {
|
| 1493 |
+
if (hoveredGroup) highlightGroup(hoveredGroup, null);
|
| 1494 |
+
hoveredGroup = hoverTarget.group;
|
| 1495 |
+
highlightGroup(hoveredGroup, 0x555555);
|
| 1496 |
+
canvas.style.cursor = 'pointer';
|
| 1497 |
+
}
|
| 1498 |
+
} else {
|
| 1499 |
+
if (hoveredGroup) {
|
| 1500 |
+
highlightGroup(hoveredGroup, null);
|
| 1501 |
+
hoveredGroup = null;
|
| 1502 |
+
}
|
| 1503 |
+
canvas.style.cursor = 'default';
|
| 1504 |
+
}
|
| 1505 |
+
}
|
| 1506 |
+
|
| 1507 |
+
function endActiveDrag(notifyServer = true) {
|
| 1508 |
+
if (!activeDrag) return;
|
| 1509 |
+
if (
|
| 1510 |
+
notifyServer
|
| 1511 |
+
&& activeDrag.dragId
|
| 1512 |
+
&& socket
|
| 1513 |
+
&& socket.readyState === WebSocket.OPEN
|
| 1514 |
+
) {
|
| 1515 |
+
socket.send(JSON.stringify({
|
| 1516 |
+
type: 'mouse_pick_end',
|
| 1517 |
+
drag_id: activeDrag.dragId
|
| 1518 |
+
}));
|
| 1519 |
+
}
|
| 1520 |
+
const pointerId = activeDrag.pointerId;
|
| 1521 |
+
activeDrag = null;
|
| 1522 |
+
isDragging = false;
|
| 1523 |
+
controls.enabled = true;
|
| 1524 |
+
if (canvas.hasPointerCapture(pointerId)) {
|
| 1525 |
+
canvas.releasePointerCapture(pointerId);
|
| 1526 |
+
}
|
| 1527 |
+
}
|
| 1528 |
+
|
| 1529 |
+
function onPointerEnd(event) {
|
| 1530 |
+
if (activeDrag && event.pointerId === activeDrag.pointerId) {
|
| 1531 |
+
endActiveDrag(true);
|
| 1532 |
+
}
|
| 1533 |
+
}
|
| 1534 |
+
|
| 1535 |
+
canvas.addEventListener('pointerdown', onPointerDown);
|
| 1536 |
+
canvas.addEventListener('pointermove', onPointerMove);
|
| 1537 |
+
canvas.addEventListener('pointerup', onPointerEnd);
|
| 1538 |
+
canvas.addEventListener('pointercancel', onPointerEnd);
|
| 1539 |
+
canvas.addEventListener('lostpointercapture', () => endActiveDrag(true));
|
| 1540 |
+
|
| 1541 |
+
canvas.addEventListener('dragover', event => {
|
| 1542 |
+
if (!event.dataTransfer.types.includes('application/x-llm-panda-ycb')) return;
|
| 1543 |
+
event.preventDefault();
|
| 1544 |
+
event.dataTransfer.dropEffect = 'copy';
|
| 1545 |
+
canvas.classList.add('catalog-drop-target');
|
| 1546 |
+
});
|
| 1547 |
+
|
| 1548 |
+
canvas.addEventListener('dragleave', () => {
|
| 1549 |
+
canvas.classList.remove('catalog-drop-target');
|
| 1550 |
+
});
|
| 1551 |
+
|
| 1552 |
+
canvas.addEventListener('drop', event => {
|
| 1553 |
+
event.preventDefault();
|
| 1554 |
+
canvas.classList.remove('catalog-drop-target');
|
| 1555 |
+
if (!socket || socket.readyState !== WebSocket.OPEN) return;
|
| 1556 |
+
let item;
|
| 1557 |
+
try {
|
| 1558 |
+
item = JSON.parse(
|
| 1559 |
+
event.dataTransfer.getData('application/x-llm-panda-ycb')
|
| 1560 |
+
);
|
| 1561 |
+
} catch (_) {
|
| 1562 |
+
return;
|
| 1563 |
+
}
|
| 1564 |
+
updatePointerRay(event);
|
| 1565 |
+
const surfacePlane = new THREE.Plane(
|
| 1566 |
+
new THREE.Vector3(0, 0, 1),
|
| 1567 |
+
-placementSurfaceZ
|
| 1568 |
+
);
|
| 1569 |
+
const position = new THREE.Vector3();
|
| 1570 |
+
if (!raycaster.ray.intersectPlane(surfacePlane, position)) return;
|
| 1571 |
+
socket.send(JSON.stringify({
|
| 1572 |
+
type: 'spawn_catalog_object',
|
| 1573 |
+
folder: item.folder,
|
| 1574 |
+
position: [position.x, position.y, placementSurfaceZ + 0.08]
|
| 1575 |
+
}));
|
| 1576 |
+
});
|
| 1577 |
|
| 1578 |
|
| 1579 |
// Initialize
|
frontend/interactive_server.py
CHANGED
|
@@ -2,10 +2,10 @@ import sys
|
|
| 2 |
import os
|
| 3 |
import json
|
| 4 |
import asyncio
|
| 5 |
-
import math
|
| 6 |
-
import time
|
| 7 |
-
import threading
|
| 8 |
-
import uuid
|
| 9 |
from typing import Optional
|
| 10 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 11 |
from fastapi.staticfiles import StaticFiles
|
|
@@ -23,12 +23,20 @@ load_dotenv()
|
|
| 23 |
from main import PandaApp
|
| 24 |
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
|
| 25 |
from llm_panda.plan_verifier import PlanVerifier
|
| 26 |
-
from llm_panda import config
|
| 27 |
-
from llm_panda.execution.cancellation import ExecutionInterrupted
|
| 28 |
-
from frontend.web_runtime import WebRuntime
|
| 29 |
import pybullet_data
|
| 30 |
from pybullet_object_models import ycb_objects
|
|
|
|
| 31 |
app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
# Serve static files from the frontend directory itself
|
| 33 |
static_dir = os.path.dirname(__file__)
|
| 34 |
app.mount("/static", StaticFiles(directory=static_dir), name="static")
|
|
@@ -41,82 +49,82 @@ app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb")
|
|
| 41 |
async def get():
|
| 42 |
html_file = os.path.join(static_dir, "index.html")
|
| 43 |
if os.path.exists(html_file):
|
| 44 |
-
with open(html_file, "r", encoding="utf-8") as f:
|
| 45 |
-
return HTMLResponse(
|
| 46 |
-
content=f.read(),
|
| 47 |
-
status_code=200,
|
| 48 |
-
headers={
|
| 49 |
-
"Cache-Control": "no-store, no-cache, must-revalidate",
|
| 50 |
-
"Pragma": "no-cache",
|
| 51 |
-
"Expires": "0",
|
| 52 |
-
},
|
| 53 |
-
)
|
| 54 |
return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
|
| 55 |
# Global variables to track the current active simulation, lock, and thread lock
|
| 56 |
current_sim: Optional[PandaApp] = None
|
| 57 |
executor_lock = asyncio.Lock()
|
| 58 |
pybullet_lock = threading.RLock()
|
| 59 |
-
pipeline_executing = False
|
| 60 |
-
web_runtime = WebRuntime()
|
| 61 |
-
command_worker_task = None
|
| 62 |
-
physics_settle_task = None
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def _finite_vec3(value):
|
| 66 |
-
return (
|
| 67 |
-
isinstance(value, (list, tuple))
|
| 68 |
-
and len(value) >= 3
|
| 69 |
-
and all(
|
| 70 |
-
isinstance(component, (int, float))
|
| 71 |
-
and math.isfinite(component)
|
| 72 |
-
for component in value[:3]
|
| 73 |
-
)
|
| 74 |
-
)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def _clamp_manual_target(position, target_type="object"):
|
| 78 |
-
"""Keep browser-controlled targets inside the supported workspace."""
|
| 79 |
-
if not _finite_vec3(position):
|
| 80 |
-
raise ValueError("Manual target must contain three finite coordinates")
|
| 81 |
-
x, y, z = (float(value) for value in position[:3])
|
| 82 |
-
x = min(max(x, -0.10), 0.90)
|
| 83 |
-
y = min(max(y, -0.65), 0.65)
|
| 84 |
-
z = min(max(z, 0.08 if target_type == "robot_ee" else 0.03), 0.90)
|
| 85 |
-
|
| 86 |
-
cx, cy = config.TABLE_CENTER
|
| 87 |
-
hx, hy = config.TABLE_HALF_EXTENTS[:2]
|
| 88 |
-
if cx - hx <= x <= cx + hx and cy - hy <= y <= cy + hy:
|
| 89 |
-
z = max(z, config.TABLE_TOP_Z + 0.01)
|
| 90 |
-
tx, ty, tz = config.TRAY_POSITION
|
| 91 |
-
thx, thy = config.TRAY_HALF_EXTENTS[:2]
|
| 92 |
-
if tx - thx <= x <= tx + thx and ty - thy <= y <= ty + thy:
|
| 93 |
-
z = max(z, tz + 0.01)
|
| 94 |
-
return [x, y, z]
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def _load_environment_config(path):
|
| 98 |
-
with open(path, "r", encoding="utf-8") as handle:
|
| 99 |
-
data = json.load(handle)
|
| 100 |
-
required = {"table", "tray", "robot"}
|
| 101 |
-
if not isinstance(data, dict) or not required.issubset(data):
|
| 102 |
-
raise ValueError("File được chọn không phải environment JSON hợp lệ.")
|
| 103 |
-
if "objects" in data and not isinstance(data["objects"], list):
|
| 104 |
-
raise ValueError("Trường objects của environment phải là một danh sách.")
|
| 105 |
-
return data
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
def _list_environment_files(directory):
|
| 109 |
-
files = []
|
| 110 |
-
for filename in sorted(os.listdir(directory)):
|
| 111 |
-
if not filename.endswith(".json") or filename.endswith(".semantics.json"):
|
| 112 |
-
continue
|
| 113 |
-
path = os.path.join(directory, filename)
|
| 114 |
-
try:
|
| 115 |
-
_load_environment_config(path)
|
| 116 |
-
except (OSError, ValueError, json.JSONDecodeError):
|
| 117 |
-
continue
|
| 118 |
-
files.append(filename)
|
| 119 |
-
return files
|
| 120 |
def get_init_payload(sim: PandaApp) -> dict:
|
| 121 |
"""Gathers the initial static geometry and YCB object definitions."""
|
| 122 |
with pybullet_lock:
|
|
@@ -162,26 +170,26 @@ def get_init_payload(sim: PandaApp) -> dict:
|
|
| 162 |
vis_local_pos = list(vis_pos_com)
|
| 163 |
vis_local_ori = list(vis_ori_com)
|
| 164 |
|
| 165 |
-
import os
|
| 166 |
-
if not web_obj and vd[4]:
|
| 167 |
-
mesh_path = vd[4].decode('utf-8')
|
| 168 |
-
web_obj = os.path.basename(mesh_path)
|
| 169 |
-
if not folder:
|
| 170 |
-
folder = os.path.basename(os.path.dirname(mesh_path))
|
| 171 |
-
candidate_mtls = [
|
| 172 |
-
mesh_path + ".mtl",
|
| 173 |
-
os.path.splitext(mesh_path)[0] + ".mtl",
|
| 174 |
-
]
|
| 175 |
-
matching_mtl = next(
|
| 176 |
-
(
|
| 177 |
-
candidate
|
| 178 |
-
for candidate in candidate_mtls
|
| 179 |
-
if os.path.isfile(candidate)
|
| 180 |
-
),
|
| 181 |
-
None,
|
| 182 |
-
)
|
| 183 |
-
if not web_mtl and matching_mtl:
|
| 184 |
-
web_mtl = os.path.basename(matching_mtl)
|
| 185 |
|
| 186 |
objects_info[name] = {
|
| 187 |
"class": cls,
|
|
@@ -358,31 +366,31 @@ def compute_and_format_score(sim: PandaApp, plan: list, executed_successfully: b
|
|
| 358 |
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])
|
| 359 |
return score, md
|
| 360 |
|
| 361 |
-
def run_pipeline_threadsafe(
|
| 362 |
-
user_prompt: str,
|
| 363 |
-
loop,
|
| 364 |
-
use_mock: bool,
|
| 365 |
-
runtime: WebRuntime,
|
| 366 |
-
cancellation_token,
|
| 367 |
-
generation: int,
|
| 368 |
-
task_id: str,
|
| 369 |
-
camera_state: Optional[dict] = None,
|
| 370 |
-
):
|
| 371 |
"""Runs the planning, validation, execution with image streaming, and scoring using closed-loop execution monitor."""
|
| 372 |
global current_sim, pipeline_executing
|
| 373 |
-
pipeline_executing = True
|
| 374 |
-
current_sim.pipeline.set_cancellation_token(cancellation_token)
|
| 375 |
-
|
| 376 |
-
def publish(payload: dict, journal: bool = True):
|
| 377 |
-
payload = {**payload, "task_id": task_id, "generation": generation}
|
| 378 |
-
runtime.publish_threadsafe(payload, loop, journal=journal)
|
| 379 |
|
| 380 |
def log(message: str, step: Optional[int] = None):
|
| 381 |
try:
|
| 382 |
print(f"[WS Log] {message}", flush=True)
|
| 383 |
except Exception:
|
| 384 |
pass
|
| 385 |
-
publish({"type": "log", "message": message, "step": step})
|
| 386 |
|
| 387 |
# Step 1: Planning
|
| 388 |
log("⏳ [1/5] Tôi đang suy nghĩ cách thực hiện...")
|
|
@@ -400,27 +408,27 @@ def run_pipeline_threadsafe(
|
|
| 400 |
log(f"✅ [1] Tôi đang phân tích yêu cầu...")
|
| 401 |
|
| 402 |
with pybullet_lock:
|
| 403 |
-
current_sim.pipeline.agent = LLMAgent(
|
| 404 |
-
planner=planner,
|
| 405 |
-
conversation_manager=runtime.conversation_manager,
|
| 406 |
-
)
|
| 407 |
|
| 408 |
-
try:
|
| 409 |
-
MAX_REPLANS = max(0, int(os.environ.get("MAX_REPLANS", "3")))
|
| 410 |
-
except ValueError:
|
| 411 |
-
MAX_REPLANS = 3
|
| 412 |
-
last_failed_sig = None
|
| 413 |
-
last_failed_state_sig = None
|
| 414 |
-
resolved_goal = None
|
| 415 |
|
| 416 |
# Hook pb.stepSimulation to capture states during movements
|
| 417 |
original_step = pb.stepSimulation
|
| 418 |
last_stream_time = [0.0]
|
| 419 |
throttle_interval = 0.033
|
| 420 |
|
| 421 |
-
def wrapped_step():
|
| 422 |
-
cancellation_token.checkpoint()
|
| 423 |
-
original_step()
|
| 424 |
if not current_sim.gui:
|
| 425 |
time.sleep(0.001)
|
| 426 |
curr_time = time.time()
|
|
@@ -428,13 +436,13 @@ def run_pipeline_threadsafe(
|
|
| 428 |
last_stream_time[0] = curr_time
|
| 429 |
state_payload = get_simulation_state_payload(current_sim)
|
| 430 |
if state_payload:
|
| 431 |
-
publish(state_payload, journal=False)
|
| 432 |
|
| 433 |
-
for attempt in range(MAX_REPLANS + 1):
|
| 434 |
-
cancellation_token.checkpoint()
|
| 435 |
-
if attempt > 0:
|
| 436 |
-
runtime.set_status("replanning", generation=generation)
|
| 437 |
-
publish({"type": "execution_status", "state": "replanning"})
|
| 438 |
log(f"[MONITOR] Re-plan attempt {attempt}/{MAX_REPLANS} due to: {last_failed_sig}")
|
| 439 |
log("⏳ [1/5] Tôi đang suy nghĩ cách thực hiện...")
|
| 440 |
|
|
@@ -462,30 +470,30 @@ def run_pipeline_threadsafe(
|
|
| 462 |
}
|
| 463 |
state_sig = json.dumps(state_sig_dict, sort_keys=True)
|
| 464 |
|
| 465 |
-
try:
|
| 466 |
-
with pybullet_lock:
|
| 467 |
-
llm_start_time = time.time()
|
| 468 |
-
planning_instruction = (
|
| 469 |
-
resolved_goal.canonical_instruction
|
| 470 |
-
if attempt > 0 and resolved_goal is not None
|
| 471 |
-
else user_prompt
|
| 472 |
-
)
|
| 473 |
-
current_sim.pipeline.agent.last_outcome = None
|
| 474 |
-
plan_kwargs = {
|
| 475 |
-
"previous_failed_reasons": last_failed_sig,
|
| 476 |
-
}
|
| 477 |
-
if attempt > 0:
|
| 478 |
-
plan_kwargs["resolve_goal"] = False
|
| 479 |
-
plan = current_sim.pipeline.agent.plan(
|
| 480 |
-
planning_instruction,
|
| 481 |
-
state_text,
|
| 482 |
-
**plan_kwargs,
|
| 483 |
-
)
|
| 484 |
-
outcome = current_sim.pipeline.agent.last_outcome
|
| 485 |
-
if attempt == 0 and outcome is not None:
|
| 486 |
-
resolved_goal = outcome.resolved_goal
|
| 487 |
-
llm_time = time.time() - llm_start_time
|
| 488 |
-
cancellation_token.checkpoint()
|
| 489 |
|
| 490 |
# Summarize plan
|
| 491 |
targets = []
|
|
@@ -533,22 +541,22 @@ def run_pipeline_threadsafe(
|
|
| 533 |
"args": args
|
| 534 |
})
|
| 535 |
|
| 536 |
-
publish({"type": "plan", "plan": plan_steps, "summary": summary_msg, "llm_time": llm_time})
|
| 537 |
|
| 538 |
if plan and plan[0].get("function") in ("clarify", "reject"):
|
| 539 |
log(f"Robot phản hồi: {summary_msg}")
|
| 540 |
header_title = "Phản hồi từ Robot" if plan[0].get("function") == "clarify" else "Yêu cầu bị từ chối"
|
| 541 |
score_md = f"### {header_title}\n\n**Robot phản hồi:** {summary_msg}\n"
|
| 542 |
-
publish({
|
| 543 |
-
"type": "result",
|
| 544 |
-
"response_type": plan[0].get("function"),
|
| 545 |
-
"score_display": score_md,
|
| 546 |
-
"score_value": 0,
|
| 547 |
-
"success": False,
|
| 548 |
-
})
|
| 549 |
state_payload = get_simulation_state_payload(current_sim)
|
| 550 |
if state_payload:
|
| 551 |
-
publish(state_payload, journal=False)
|
| 552 |
pipeline_executing = False
|
| 553 |
return
|
| 554 |
|
|
@@ -556,14 +564,14 @@ def run_pipeline_threadsafe(
|
|
| 556 |
log("⚠️ [1] Kế hoạch rỗng.")
|
| 557 |
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
|
| 558 |
score_val, score_md = compute_and_format_score(current_sim, [], True)
|
| 559 |
-
publish({
|
| 560 |
-
"type": "result",
|
| 561 |
-
"score_display": score_md,
|
| 562 |
-
"score_value": score_val,
|
| 563 |
-
})
|
| 564 |
state_payload = get_simulation_state_payload(current_sim)
|
| 565 |
if state_payload:
|
| 566 |
-
publish(state_payload, journal=False)
|
| 567 |
pipeline_executing = False
|
| 568 |
return
|
| 569 |
|
|
@@ -583,10 +591,10 @@ def run_pipeline_threadsafe(
|
|
| 583 |
pipeline_executing = False
|
| 584 |
return
|
| 585 |
|
| 586 |
-
# Step 3: PyBullet Execution (Live!)
|
| 587 |
-
log("⏳ [3/5] Tôi bắt đầu thực hiện các bước...")
|
| 588 |
-
runtime.set_status("executing", generation=generation)
|
| 589 |
-
publish({"type": "execution_status", "state": "executing"})
|
| 590 |
|
| 591 |
with pybullet_lock:
|
| 592 |
pb.stepSimulation = wrapped_step
|
|
@@ -600,7 +608,7 @@ def run_pipeline_threadsafe(
|
|
| 600 |
# Trigger an initial simulation state transmission
|
| 601 |
state_payload = get_simulation_state_payload(current_sim)
|
| 602 |
if state_payload:
|
| 603 |
-
publish(state_payload, journal=False)
|
| 604 |
|
| 605 |
def format_skill_vn(step_data):
|
| 606 |
fn = step_data.get("function", "")
|
|
@@ -626,12 +634,12 @@ def run_pipeline_threadsafe(
|
|
| 626 |
if fn == "close_gripper": return "Đóng tay kẹp"
|
| 627 |
return f"{fn}"
|
| 628 |
|
| 629 |
-
expected_location = None
|
| 630 |
-
for i, step in enumerate(plan, 1):
|
| 631 |
-
cancellation_token.checkpoint()
|
| 632 |
-
runtime.set_status("executing", generation=generation, current_step=i)
|
| 633 |
-
publish({"type": "current_step", "step": i})
|
| 634 |
-
friendly_text = format_skill_vn(step)
|
| 635 |
# Make the first letter lowercase for natural sentence integration
|
| 636 |
if friendly_text:
|
| 637 |
friendly_text = friendly_text[0].lower() + friendly_text[1:]
|
|
@@ -666,11 +674,11 @@ def run_pipeline_threadsafe(
|
|
| 666 |
log("✅ [3] Tôi đã hoàn tất các bước.")
|
| 667 |
else:
|
| 668 |
log(f"❌ [3] Thực thi lỗi tại bước {failed_step_index} '{failed_step_data.get('function')}': {step_failure_reason}")
|
| 669 |
-
except ExecutionInterrupted:
|
| 670 |
-
with pybullet_lock:
|
| 671 |
-
current_sim.pipeline.interrupt_hold()
|
| 672 |
-
raise
|
| 673 |
-
except Exception as e:
|
| 674 |
log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
|
| 675 |
executed_successfully = False
|
| 676 |
step_failure_reason = str(e)
|
|
@@ -681,7 +689,7 @@ def run_pipeline_threadsafe(
|
|
| 681 |
# Send a final state to ensure visual sync
|
| 682 |
state_payload = get_simulation_state_payload(current_sim)
|
| 683 |
if state_payload:
|
| 684 |
-
publish(state_payload, journal=False)
|
| 685 |
|
| 686 |
# Now check overall goal using execution monitor
|
| 687 |
goal_completed = False
|
|
@@ -690,13 +698,13 @@ def run_pipeline_threadsafe(
|
|
| 690 |
with pybullet_lock:
|
| 691 |
final_scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=current_sim.scene.get_name(current_sim.pipeline._carried) if current_sim.pipeline._carried else None)
|
| 692 |
final_state_text = json.dumps(final_scene_state, indent=2)
|
| 693 |
-
goal_completed, goal_reason = (
|
| 694 |
-
current_sim.pipeline.execution_monitor.verify_goal(
|
| 695 |
-
user_prompt,
|
| 696 |
-
final_state_text,
|
| 697 |
-
resolved_goal=resolved_goal,
|
| 698 |
-
)
|
| 699 |
-
)
|
| 700 |
if goal_completed:
|
| 701 |
log(f"✅ [GOAL CHECK] OK: {goal_reason}")
|
| 702 |
else:
|
|
@@ -734,106 +742,106 @@ def run_pipeline_threadsafe(
|
|
| 734 |
|
| 735 |
is_success = executed_successfully and goal_completed and score_val >= 50
|
| 736 |
|
| 737 |
-
publish({
|
| 738 |
-
"type": "result",
|
| 739 |
-
"score_display": score_md,
|
| 740 |
-
"score_value": score_val,
|
| 741 |
-
"error_cause": error_cause,
|
| 742 |
-
"success": is_success,
|
| 743 |
-
})
|
| 744 |
-
current_sim.pipeline.set_cancellation_token(None)
|
| 745 |
-
pipeline_executing = False
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
async def command_worker_loop(loop):
|
| 749 |
-
"""Serialize robot commands while allowing the newest prompt to interrupt."""
|
| 750 |
-
global command_worker_task, pipeline_executing
|
| 751 |
-
try:
|
| 752 |
-
while True:
|
| 753 |
-
command = web_runtime.take_pending()
|
| 754 |
-
if command is None:
|
| 755 |
-
return
|
| 756 |
-
generation = command["generation"]
|
| 757 |
-
task_id = command["task_id"]
|
| 758 |
-
interrupted = False
|
| 759 |
-
await web_runtime.publish({
|
| 760 |
-
"type": "command_accepted",
|
| 761 |
-
"prompt": command["prompt"],
|
| 762 |
-
"task_id": task_id,
|
| 763 |
-
"generation": generation,
|
| 764 |
-
})
|
| 765 |
-
await web_runtime.publish({
|
| 766 |
-
"type": "execution_status",
|
| 767 |
-
"state": "planning",
|
| 768 |
-
"task_id": task_id,
|
| 769 |
-
"generation": generation,
|
| 770 |
-
})
|
| 771 |
-
try:
|
| 772 |
-
await asyncio.to_thread(
|
| 773 |
-
run_pipeline_threadsafe,
|
| 774 |
-
command["prompt"],
|
| 775 |
-
loop,
|
| 776 |
-
command["use_mock"],
|
| 777 |
-
web_runtime,
|
| 778 |
-
command["token"],
|
| 779 |
-
generation,
|
| 780 |
-
task_id,
|
| 781 |
-
)
|
| 782 |
-
except ExecutionInterrupted as exc:
|
| 783 |
-
interrupted = True
|
| 784 |
-
pipeline_executing = False
|
| 785 |
-
with pybullet_lock:
|
| 786 |
-
if current_sim is not None and current_sim.pipeline is not None:
|
| 787 |
-
current_sim.pipeline.interrupt_hold()
|
| 788 |
-
web_runtime.set_status("interrupted", generation=generation)
|
| 789 |
-
await web_runtime.publish({
|
| 790 |
-
"type": "interrupted",
|
| 791 |
-
"reason": str(exc),
|
| 792 |
-
"task_id": task_id,
|
| 793 |
-
"generation": generation,
|
| 794 |
-
})
|
| 795 |
-
state_payload = await asyncio.to_thread(
|
| 796 |
-
get_simulation_state_payload,
|
| 797 |
-
current_sim,
|
| 798 |
-
)
|
| 799 |
-
if state_payload:
|
| 800 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 801 |
-
except Exception as exc:
|
| 802 |
-
pipeline_executing = False
|
| 803 |
-
await web_runtime.publish({
|
| 804 |
-
"type": "result",
|
| 805 |
-
"success": False,
|
| 806 |
-
"error_cause": "runtime",
|
| 807 |
-
"score_display": f"### Lỗi thực thi\n\n{exc}",
|
| 808 |
-
"task_id": task_id,
|
| 809 |
-
"generation": generation,
|
| 810 |
-
})
|
| 811 |
-
finally:
|
| 812 |
-
if current_sim is not None and current_sim.pipeline is not None:
|
| 813 |
-
current_sim.pipeline.set_cancellation_token(None)
|
| 814 |
-
web_runtime.complete(
|
| 815 |
-
generation,
|
| 816 |
-
state="interrupted" if interrupted else "completed",
|
| 817 |
-
)
|
| 818 |
-
finally:
|
| 819 |
-
command_worker_task = None
|
| 820 |
-
if web_runtime.has_pending:
|
| 821 |
-
command_worker_task = asyncio.create_task(command_worker_loop(loop))
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
async def wait_for_active_task_stop(timeout=5.0):
|
| 825 |
-
web_runtime.cancel_all("runtime_mutation")
|
| 826 |
-
deadline = time.monotonic() + timeout
|
| 827 |
-
while web_runtime.active_token is not None and time.monotonic() < deadline:
|
| 828 |
-
await asyncio.sleep(0.02)
|
| 829 |
-
return web_runtime.active_token is None
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
@app.websocket("/ws")
|
| 833 |
-
async def websocket_endpoint(websocket: WebSocket):
|
| 834 |
-
global current_sim, command_worker_task, physics_settle_task
|
| 835 |
-
await websocket.accept()
|
| 836 |
-
await web_runtime.subscribe(websocket)
|
| 837 |
loop = asyncio.get_running_loop()
|
| 838 |
|
| 839 |
# Retrieve user's desktop display preference from client query params
|
|
@@ -842,15 +850,15 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 842 |
# Force gui = False to run PyBullet completely headless (DIRECT mode)
|
| 843 |
gui = False
|
| 844 |
|
| 845 |
-
camera_state = {
|
| 846 |
"target": [0.5, 0.0, 0.3],
|
| 847 |
"dist": 1.3,
|
| 848 |
"yaw": 45.0,
|
| 849 |
-
"pitch": -35.0
|
| 850 |
-
}
|
| 851 |
-
drag_state = {"constraint_id": None, "active": False}
|
| 852 |
|
| 853 |
-
async def physics_settle_loop():
|
| 854 |
try:
|
| 855 |
while True:
|
| 856 |
global pipeline_executing
|
|
@@ -874,9 +882,9 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 874 |
pb.stepSimulation(physicsClientId=current_sim.client)
|
| 875 |
await asyncio.to_thread(step)
|
| 876 |
|
| 877 |
-
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 878 |
-
if state_payload:
|
| 879 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 880 |
await asyncio.sleep(1/30.0)
|
| 881 |
except asyncio.CancelledError:
|
| 882 |
pass
|
|
@@ -909,165 +917,165 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 909 |
except Exception:
|
| 910 |
is_connected = False
|
| 911 |
|
| 912 |
-
# Reconnect/reload deliberately keeps the live PyBullet state.
|
| 913 |
await asyncio.to_thread(init_sim)
|
| 914 |
# Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
|
| 915 |
await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
|
| 916 |
|
| 917 |
# Send environment list
|
| 918 |
try:
|
| 919 |
-
env_files = _list_environment_files(
|
| 920 |
-
os.path.join(PROJECT_SRC, "envs")
|
| 921 |
-
)
|
| 922 |
-
await websocket.send_json({"type": "env_list", "envs": env_files})
|
| 923 |
|
| 924 |
# Send initial static scene data (only needs to be sent once)
|
| 925 |
-
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
|
| 926 |
-
web_runtime.latest_init = init_payload
|
| 927 |
-
await websocket.send_json(init_payload)
|
| 928 |
# Send the first simulation state to sync objects and joints
|
| 929 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 930 |
-
if state_payload:
|
| 931 |
-
web_runtime.latest_state = state_payload
|
| 932 |
-
await websocket.send_json(state_payload)
|
| 933 |
-
await websocket.send_json(web_runtime.snapshot())
|
| 934 |
-
|
| 935 |
-
if physics_settle_task is None or physics_settle_task.done():
|
| 936 |
-
physics_settle_task = asyncio.create_task(physics_settle_loop())
|
| 937 |
|
| 938 |
-
while True:
|
| 939 |
data = await websocket.receive_text()
|
| 940 |
payload = json.loads(data)
|
| 941 |
|
| 942 |
p_type = payload.get("type")
|
| 943 |
-
if p_type == "run":
|
| 944 |
-
prompt = payload.get("prompt", "")
|
| 945 |
-
use_mock = payload.get("mock", False)
|
| 946 |
-
if prompt.strip():
|
| 947 |
-
command = web_runtime.submit(prompt.strip(), use_mock)
|
| 948 |
-
await web_runtime.publish({
|
| 949 |
-
"type": "interrupt_requested",
|
| 950 |
-
"generation": command["generation"],
|
| 951 |
-
"task_id": command["task_id"],
|
| 952 |
-
})
|
| 953 |
-
if command_worker_task is None or command_worker_task.done():
|
| 954 |
-
command_worker_task = asyncio.create_task(
|
| 955 |
-
command_worker_loop(loop)
|
| 956 |
-
)
|
| 957 |
-
|
| 958 |
-
elif p_type == "cancel":
|
| 959 |
-
if web_runtime.cancel_all("user_cancelled"):
|
| 960 |
-
await web_runtime.publish({
|
| 961 |
-
"type": "interrupt_requested",
|
| 962 |
-
"generation": web_runtime.active_generation,
|
| 963 |
-
})
|
| 964 |
|
| 965 |
|
| 966 |
-
elif p_type == "mouse_pick_start":
|
| 967 |
-
if web_runtime.active_token is not None:
|
| 968 |
-
if not await wait_for_active_task_stop():
|
| 969 |
-
await websocket.send_json({
|
| 970 |
-
"type": "drag_rejected",
|
| 971 |
-
"reason": "Robot chưa dừng an toàn.",
|
| 972 |
-
})
|
| 973 |
-
continue
|
| 974 |
-
rayFrom = payload.get("rayFrom")
|
| 975 |
-
rayTo = payload.get("rayTo")
|
| 976 |
-
requested_type = payload.get("target_type")
|
| 977 |
-
requested_name = payload.get("object_id")
|
| 978 |
-
if _finite_vec3(rayFrom) and _finite_vec3(rayTo):
|
| 979 |
-
async with executor_lock:
|
| 980 |
-
def do_pick():
|
| 981 |
-
with pybullet_lock:
|
| 982 |
-
if drag_state.get("constraint_id") is not None:
|
| 983 |
-
pb.removeConstraint(
|
| 984 |
-
drag_state["constraint_id"],
|
| 985 |
-
physicsClientId=current_sim.client,
|
| 986 |
-
)
|
| 987 |
-
hit = pb.rayTest(
|
| 988 |
-
rayFrom,
|
| 989 |
-
rayTo,
|
| 990 |
-
physicsClientId=current_sim.client,
|
| 991 |
-
)[0]
|
| 992 |
-
hit_uid, link_index, hit_pos = hit[0], hit[1], hit[3]
|
| 993 |
-
drag_id = uuid.uuid4().hex
|
| 994 |
-
|
| 995 |
-
if requested_type == "robot_ee":
|
| 996 |
-
if hit_uid != current_sim.controller.robot_id:
|
| 997 |
-
return None
|
| 998 |
-
drag_state.update({
|
| 999 |
-
"drag_id": drag_id,
|
| 1000 |
-
"target_type": "robot_ee",
|
| 1001 |
-
"object_name": None,
|
| 1002 |
-
"constraint_id": None,
|
| 1003 |
-
"active": True,
|
| 1004 |
-
})
|
| 1005 |
-
return dict(drag_state)
|
| 1006 |
-
|
| 1007 |
-
object_id = current_sim.scene.name_to_id(
|
| 1008 |
-
requested_name
|
| 1009 |
-
)
|
| 1010 |
-
if object_id is None:
|
| 1011 |
-
return None
|
| 1012 |
-
mass = pb.getDynamicsInfo(
|
| 1013 |
-
object_id,
|
| 1014 |
-
-1,
|
| 1015 |
-
physicsClientId=current_sim.client,
|
| 1016 |
-
)[0]
|
| 1017 |
-
if mass <= 0:
|
| 1018 |
-
return None
|
| 1019 |
-
pos, _ = pb.getBasePositionAndOrientation(
|
| 1020 |
-
object_id,
|
| 1021 |
-
physicsClientId=current_sim.client,
|
| 1022 |
-
)
|
| 1023 |
-
constraint_id = pb.createConstraint(
|
| 1024 |
-
parentBodyUniqueId=object_id,
|
| 1025 |
-
parentLinkIndex=-1,
|
| 1026 |
-
childBodyUniqueId=-1,
|
| 1027 |
-
childLinkIndex=-1,
|
| 1028 |
-
jointType=pb.JOINT_POINT2POINT,
|
| 1029 |
-
jointAxis=[0, 0, 0],
|
| 1030 |
-
parentFramePosition=[0, 0, 0],
|
| 1031 |
-
childFramePosition=pos,
|
| 1032 |
-
physicsClientId=current_sim.client,
|
| 1033 |
-
)
|
| 1034 |
-
pb.changeConstraint(
|
| 1035 |
-
constraint_id,
|
| 1036 |
-
maxForce=500,
|
| 1037 |
-
physicsClientId=current_sim.client,
|
| 1038 |
-
)
|
| 1039 |
-
drag_state.update({
|
| 1040 |
-
"drag_id": drag_id,
|
| 1041 |
-
"target_type": "object",
|
| 1042 |
-
"object_name": requested_name,
|
| 1043 |
-
"constraint_id": constraint_id,
|
| 1044 |
-
"active": True,
|
| 1045 |
-
})
|
| 1046 |
-
return dict(drag_state)
|
| 1047 |
-
started = await asyncio.to_thread(do_pick)
|
| 1048 |
-
|
| 1049 |
-
if not started:
|
| 1050 |
-
await websocket.send_json({
|
| 1051 |
-
"type": "drag_rejected",
|
| 1052 |
-
"reason": "Vật được chọn trên web không khớp scene vật lý.",
|
| 1053 |
-
})
|
| 1054 |
-
continue
|
| 1055 |
-
await websocket.send_json({
|
| 1056 |
-
"type": "drag_started",
|
| 1057 |
-
"drag_id": started["drag_id"],
|
| 1058 |
-
"target_type": started["target_type"],
|
| 1059 |
-
"object_id": started.get("object_name"),
|
| 1060 |
-
})
|
| 1061 |
-
|
| 1062 |
-
if (
|
| 1063 |
-
started["target_type"] == "object"
|
| 1064 |
-
and (
|
| 1065 |
-
drag_state.get("task") is None
|
| 1066 |
-
or drag_state["task"].done()
|
| 1067 |
-
)
|
| 1068 |
-
):
|
| 1069 |
-
async def drag_loop():
|
| 1070 |
-
while drag_state.get("active") and drag_state.get("constraint_id") is not None:
|
| 1071 |
async with executor_lock:
|
| 1072 |
def step():
|
| 1073 |
with pybullet_lock:
|
|
@@ -1077,263 +1085,263 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 1077 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1078 |
if state_payload:
|
| 1079 |
try:
|
| 1080 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 1081 |
except Exception:
|
| 1082 |
break
|
| 1083 |
await asyncio.sleep(1/60.0)
|
| 1084 |
drag_state["task"] = asyncio.create_task(drag_loop())
|
| 1085 |
|
| 1086 |
-
elif p_type == "mouse_pick_update":
|
| 1087 |
-
targetPos = payload.get("targetPos")
|
| 1088 |
-
drag_id = payload.get("drag_id")
|
| 1089 |
-
if (
|
| 1090 |
-
drag_id
|
| 1091 |
-
and drag_id == drag_state.get("drag_id")
|
| 1092 |
-
and _finite_vec3(targetPos)
|
| 1093 |
-
):
|
| 1094 |
-
target_pos = _clamp_manual_target(
|
| 1095 |
-
targetPos,
|
| 1096 |
-
drag_state.get("target_type", "object"),
|
| 1097 |
-
)
|
| 1098 |
-
async with executor_lock:
|
| 1099 |
-
def do_update():
|
| 1100 |
-
with pybullet_lock:
|
| 1101 |
-
if drag_state.get("target_type") == "robot_ee":
|
| 1102 |
-
link_state = pb.getLinkState(
|
| 1103 |
-
current_sim.controller.robot_id,
|
| 1104 |
-
current_sim.controller.ee_index,
|
| 1105 |
-
physicsClientId=current_sim.client,
|
| 1106 |
-
)
|
| 1107 |
-
solution = pb.calculateInverseKinematics(
|
| 1108 |
-
current_sim.controller.robot_id,
|
| 1109 |
-
current_sim.controller.ee_index,
|
| 1110 |
-
target_pos,
|
| 1111 |
-
link_state[1],
|
| 1112 |
-
lowerLimits=current_sim.controller._lower_limits,
|
| 1113 |
-
upperLimits=current_sim.controller._upper_limits,
|
| 1114 |
-
jointRanges=current_sim.controller._joint_ranges,
|
| 1115 |
-
restPoses=current_sim.controller._rest_poses,
|
| 1116 |
-
maxNumIterations=200,
|
| 1117 |
-
residualThreshold=1e-5,
|
| 1118 |
-
physicsClientId=current_sim.client,
|
| 1119 |
-
)
|
| 1120 |
-
for idx, q in enumerate(solution[:7]):
|
| 1121 |
-
pb.resetJointState(
|
| 1122 |
-
current_sim.controller.robot_id,
|
| 1123 |
-
idx,
|
| 1124 |
-
q,
|
| 1125 |
-
physicsClientId=current_sim.client,
|
| 1126 |
-
)
|
| 1127 |
-
elif drag_state.get("constraint_id") is not None:
|
| 1128 |
-
pb.changeConstraint(
|
| 1129 |
-
drag_state["constraint_id"],
|
| 1130 |
-
target_pos,
|
| 1131 |
-
maxForce=500,
|
| 1132 |
-
physicsClientId=current_sim.client,
|
| 1133 |
-
)
|
| 1134 |
-
await asyncio.to_thread(do_update)
|
| 1135 |
-
state_payload = await asyncio.to_thread(
|
| 1136 |
-
get_simulation_state_payload,
|
| 1137 |
-
current_sim,
|
| 1138 |
-
)
|
| 1139 |
-
if state_payload:
|
| 1140 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 1141 |
-
|
| 1142 |
-
elif p_type == "mouse_pick_end":
|
| 1143 |
-
drag_id = payload.get("drag_id")
|
| 1144 |
-
if drag_id != drag_state.get("drag_id"):
|
| 1145 |
-
continue
|
| 1146 |
-
drag_state["active"] = False
|
| 1147 |
-
async with executor_lock:
|
| 1148 |
-
def do_end():
|
| 1149 |
-
with pybullet_lock:
|
| 1150 |
if drag_state.get("constraint_id") is not None:
|
| 1151 |
-
pb.removeConstraint(drag_state["constraint_id"], physicsClientId=current_sim.client)
|
| 1152 |
-
drag_state["constraint_id"] = None
|
| 1153 |
-
if drag_state.get("target_type") == "robot_ee":
|
| 1154 |
-
current_sim.controller.hold_current_pose()
|
| 1155 |
-
await asyncio.to_thread(do_end)
|
| 1156 |
-
drag_state["drag_id"] = None
|
| 1157 |
-
drag_state["target_type"] = None
|
| 1158 |
-
for _ in range(20):
|
| 1159 |
-
with pybullet_lock:
|
| 1160 |
-
pb.stepSimulation(physicsClientId=current_sim.client)
|
| 1161 |
-
state_payload = await asyncio.to_thread(
|
| 1162 |
-
get_simulation_state_payload,
|
| 1163 |
-
current_sim,
|
| 1164 |
-
)
|
| 1165 |
-
if state_payload:
|
| 1166 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 1167 |
-
|
| 1168 |
-
elif p_type == "spawn_catalog_object":
|
| 1169 |
-
if web_runtime.active_token is not None:
|
| 1170 |
-
if not await wait_for_active_task_stop():
|
| 1171 |
-
continue
|
| 1172 |
-
folder = payload.get("folder")
|
| 1173 |
-
position = payload.get("position")
|
| 1174 |
-
if not _finite_vec3(position):
|
| 1175 |
-
continue
|
| 1176 |
-
spawn_position = _clamp_manual_target(position, "object")
|
| 1177 |
-
async with executor_lock:
|
| 1178 |
-
def spawn_object():
|
| 1179 |
-
with pybullet_lock:
|
| 1180 |
-
return current_sim.env_builder.spawn_catalog_object(
|
| 1181 |
-
folder,
|
| 1182 |
-
spawn_position,
|
| 1183 |
-
)
|
| 1184 |
-
try:
|
| 1185 |
-
_, object_name = await asyncio.to_thread(spawn_object)
|
| 1186 |
-
except (ValueError, OSError) as exc:
|
| 1187 |
-
await websocket.send_json({
|
| 1188 |
-
"type": "spawn_rejected",
|
| 1189 |
-
"reason": str(exc),
|
| 1190 |
-
})
|
| 1191 |
-
continue
|
| 1192 |
-
for _ in range(30):
|
| 1193 |
-
with pybullet_lock:
|
| 1194 |
-
pb.stepSimulation(physicsClientId=current_sim.client)
|
| 1195 |
-
init_payload = await asyncio.to_thread(
|
| 1196 |
-
get_init_payload,
|
| 1197 |
-
current_sim,
|
| 1198 |
-
)
|
| 1199 |
-
web_runtime.latest_init = init_payload
|
| 1200 |
-
state_payload = await asyncio.to_thread(
|
| 1201 |
-
get_simulation_state_payload,
|
| 1202 |
-
current_sim,
|
| 1203 |
-
)
|
| 1204 |
-
await web_runtime.publish({
|
| 1205 |
-
"type": "object_added",
|
| 1206 |
-
"name": object_name,
|
| 1207 |
-
"config": init_payload["objects"][object_name],
|
| 1208 |
-
"state": (
|
| 1209 |
-
state_payload.get("objects", {}).get(object_name)
|
| 1210 |
-
if state_payload
|
| 1211 |
-
else None
|
| 1212 |
-
),
|
| 1213 |
-
}, journal=False)
|
| 1214 |
-
if state_payload:
|
| 1215 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 1216 |
-
await web_runtime.publish({
|
| 1217 |
-
"type": "log",
|
| 1218 |
-
"message": f"Đã thêm '{object_name}' vào môi trường.",
|
| 1219 |
-
})
|
| 1220 |
-
|
| 1221 |
-
elif p_type == "delete_object":
|
| 1222 |
-
if web_runtime.active_token is not None:
|
| 1223 |
-
if not await wait_for_active_task_stop():
|
| 1224 |
-
continue
|
| 1225 |
-
object_name = payload.get("name")
|
| 1226 |
-
async with executor_lock:
|
| 1227 |
-
def delete_object():
|
| 1228 |
-
with pybullet_lock:
|
| 1229 |
-
object_id = current_sim.scene.name_to_id(
|
| 1230 |
-
object_name
|
| 1231 |
-
)
|
| 1232 |
-
if object_id is None:
|
| 1233 |
-
return False
|
| 1234 |
-
if current_sim.pipeline._carried == object_id:
|
| 1235 |
-
return False
|
| 1236 |
-
pb.removeBody(
|
| 1237 |
-
object_id,
|
| 1238 |
-
physicsClientId=current_sim.client,
|
| 1239 |
-
)
|
| 1240 |
-
current_sim.scene.unregister_object(object_id)
|
| 1241 |
-
return True
|
| 1242 |
-
deleted = await asyncio.to_thread(delete_object)
|
| 1243 |
-
if not deleted:
|
| 1244 |
-
await websocket.send_json({
|
| 1245 |
-
"type": "delete_rejected",
|
| 1246 |
-
"reason": "Không thể xóa vật đang được giữ hoặc không tồn tại.",
|
| 1247 |
-
})
|
| 1248 |
-
continue
|
| 1249 |
-
await web_runtime.publish({
|
| 1250 |
-
"type": "object_removed",
|
| 1251 |
-
"name": object_name,
|
| 1252 |
-
}, journal=False)
|
| 1253 |
-
state_payload = await asyncio.to_thread(
|
| 1254 |
-
get_simulation_state_payload,
|
| 1255 |
-
current_sim,
|
| 1256 |
-
)
|
| 1257 |
-
if state_payload:
|
| 1258 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 1259 |
-
await web_runtime.publish({
|
| 1260 |
-
"type": "log",
|
| 1261 |
-
"message": f"Đã xóa '{object_name}' khỏi môi trường.",
|
| 1262 |
-
})
|
| 1263 |
|
| 1264 |
-
elif p_type == "
|
| 1265 |
-
if
|
| 1266 |
-
await
|
| 1267 |
-
|
| 1268 |
-
|
| 1269 |
-
|
| 1270 |
-
|
| 1271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1272 |
def reset_sim():
|
| 1273 |
with pybullet_lock:
|
| 1274 |
current_sim.reset_objects(seed=0)
|
| 1275 |
current_sim.controller.reset_to_home()
|
| 1276 |
-
await asyncio.to_thread(reset_sim)
|
| 1277 |
-
web_runtime.conversation_manager.clear()
|
| 1278 |
-
web_runtime.clear_task_history()
|
| 1279 |
|
| 1280 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1281 |
if state_payload:
|
| 1282 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 1283 |
-
await web_runtime.publish({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
|
| 1284 |
|
| 1285 |
-
elif p_type == "change_env":
|
| 1286 |
-
if not await wait_for_active_task_stop():
|
| 1287 |
-
await web_runtime.publish({
|
| 1288 |
-
"type": "log",
|
| 1289 |
-
"message": "Không thể đổi môi trường khi robot chưa dừng an toàn.",
|
| 1290 |
-
})
|
| 1291 |
-
continue
|
| 1292 |
-
env_file = payload.get("env")
|
| 1293 |
-
if (
|
| 1294 |
-
not isinstance(env_file, str)
|
| 1295 |
-
or os.path.basename(env_file) != env_file
|
| 1296 |
-
):
|
| 1297 |
-
await websocket.send_json({
|
| 1298 |
-
"type": "environment_rejected",
|
| 1299 |
-
"reason": "Tên environment không hợp lệ.",
|
| 1300 |
-
})
|
| 1301 |
-
continue
|
| 1302 |
-
env_path = os.path.join(PROJECT_SRC, "envs", env_file)
|
| 1303 |
-
try:
|
| 1304 |
-
_load_environment_config(env_path)
|
| 1305 |
-
except (
|
| 1306 |
-
OSError,
|
| 1307 |
-
ValueError,
|
| 1308 |
-
json.JSONDecodeError,
|
| 1309 |
-
) as exc:
|
| 1310 |
-
await websocket.send_json({
|
| 1311 |
-
"type": "environment_rejected",
|
| 1312 |
-
"reason": str(exc),
|
| 1313 |
-
})
|
| 1314 |
-
continue
|
| 1315 |
-
async with executor_lock:
|
| 1316 |
def change_sim_env():
|
| 1317 |
with pybullet_lock:
|
| 1318 |
current_sim.change_environment(env_path)
|
| 1319 |
-
await asyncio.to_thread(change_sim_env)
|
| 1320 |
-
web_runtime.conversation_manager.clear()
|
| 1321 |
-
web_runtime.clear_task_history()
|
| 1322 |
|
| 1323 |
# Send the new static data
|
| 1324 |
-
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
|
| 1325 |
-
web_runtime.latest_init = init_payload
|
| 1326 |
-
await web_runtime.publish(init_payload, journal=False)
|
| 1327 |
|
| 1328 |
# Send the new dynamic state
|
| 1329 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1330 |
if state_payload:
|
| 1331 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 1332 |
-
await web_runtime.publish({"type": "log", "message": f"🌍 Đã chuyển sang môi trường {env_file}."})
|
| 1333 |
|
| 1334 |
-
elif p_type == "update_object_pose":
|
| 1335 |
-
if web_runtime.active_token is not None:
|
| 1336 |
-
continue
|
| 1337 |
name = payload.get("name")
|
| 1338 |
pos = payload.get("pos")
|
| 1339 |
ori = payload.get("ori")
|
|
@@ -1347,11 +1355,11 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 1347 |
|
| 1348 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1349 |
if state_payload:
|
| 1350 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 1351 |
|
| 1352 |
-
elif p_type == "update_joints":
|
| 1353 |
-
if web_runtime.active_token is not None:
|
| 1354 |
-
continue
|
| 1355 |
joints_data = payload.get("joints")
|
| 1356 |
async with executor_lock:
|
| 1357 |
def move_joints():
|
|
@@ -1365,10 +1373,10 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 1365 |
|
| 1366 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1367 |
if state_payload:
|
| 1368 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 1369 |
-
elif p_type == "update_robot_ee":
|
| 1370 |
-
if web_runtime.active_token is not None:
|
| 1371 |
-
continue
|
| 1372 |
pos = payload.get("pos")
|
| 1373 |
async with executor_lock:
|
| 1374 |
def move_robot_ee():
|
|
@@ -1405,27 +1413,27 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 1405 |
|
| 1406 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1407 |
if state_payload:
|
| 1408 |
-
await web_runtime.publish(state_payload, journal=False)
|
| 1409 |
elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
|
| 1410 |
pass
|
| 1411 |
|
| 1412 |
except WebSocketDisconnect:
|
| 1413 |
print("Client disconnected")
|
| 1414 |
-
except Exception as e:
|
| 1415 |
-
print(f"WS Exception: {e}")
|
| 1416 |
-
finally:
|
| 1417 |
-
drag_state["active"] = False
|
| 1418 |
-
if drag_state.get("constraint_id") is not None:
|
| 1419 |
-
try:
|
| 1420 |
-
with pybullet_lock:
|
| 1421 |
-
pb.removeConstraint(
|
| 1422 |
-
drag_state["constraint_id"],
|
| 1423 |
-
physicsClientId=current_sim.client,
|
| 1424 |
-
)
|
| 1425 |
-
except Exception:
|
| 1426 |
-
pass
|
| 1427 |
-
drag_state["constraint_id"] = None
|
| 1428 |
-
await web_runtime.unsubscribe(websocket)
|
| 1429 |
if __name__ == "__main__":
|
| 1430 |
port = int(os.environ.get("PORT", 8000))
|
| 1431 |
-
uvicorn.run("interactive_server:app", host="0.0.0.0", port=port, reload=False)
|
|
|
|
| 2 |
import os
|
| 3 |
import json
|
| 4 |
import asyncio
|
| 5 |
+
import math
|
| 6 |
+
import time
|
| 7 |
+
import threading
|
| 8 |
+
import uuid
|
| 9 |
from typing import Optional
|
| 10 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 11 |
from fastapi.staticfiles import StaticFiles
|
|
|
|
| 23 |
from main import PandaApp
|
| 24 |
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
|
| 25 |
from llm_panda.plan_verifier import PlanVerifier
|
| 26 |
+
from llm_panda import config
|
| 27 |
+
from llm_panda.execution.cancellation import ExecutionInterrupted
|
| 28 |
+
from frontend.web_runtime import WebRuntime
|
| 29 |
import pybullet_data
|
| 30 |
from pybullet_object_models import ycb_objects
|
| 31 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 32 |
app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
|
| 33 |
+
app.add_middleware(
|
| 34 |
+
CORSMiddleware,
|
| 35 |
+
allow_origins=["*"],
|
| 36 |
+
allow_credentials=True,
|
| 37 |
+
allow_methods=["*"],
|
| 38 |
+
allow_headers=["*"],
|
| 39 |
+
)
|
| 40 |
# Serve static files from the frontend directory itself
|
| 41 |
static_dir = os.path.dirname(__file__)
|
| 42 |
app.mount("/static", StaticFiles(directory=static_dir), name="static")
|
|
|
|
| 49 |
async def get():
|
| 50 |
html_file = os.path.join(static_dir, "index.html")
|
| 51 |
if os.path.exists(html_file):
|
| 52 |
+
with open(html_file, "r", encoding="utf-8") as f:
|
| 53 |
+
return HTMLResponse(
|
| 54 |
+
content=f.read(),
|
| 55 |
+
status_code=200,
|
| 56 |
+
headers={
|
| 57 |
+
"Cache-Control": "no-store, no-cache, must-revalidate",
|
| 58 |
+
"Pragma": "no-cache",
|
| 59 |
+
"Expires": "0",
|
| 60 |
+
},
|
| 61 |
+
)
|
| 62 |
return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
|
| 63 |
# Global variables to track the current active simulation, lock, and thread lock
|
| 64 |
current_sim: Optional[PandaApp] = None
|
| 65 |
executor_lock = asyncio.Lock()
|
| 66 |
pybullet_lock = threading.RLock()
|
| 67 |
+
pipeline_executing = False
|
| 68 |
+
web_runtime = WebRuntime()
|
| 69 |
+
command_worker_task = None
|
| 70 |
+
physics_settle_task = None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _finite_vec3(value):
|
| 74 |
+
return (
|
| 75 |
+
isinstance(value, (list, tuple))
|
| 76 |
+
and len(value) >= 3
|
| 77 |
+
and all(
|
| 78 |
+
isinstance(component, (int, float))
|
| 79 |
+
and math.isfinite(component)
|
| 80 |
+
for component in value[:3]
|
| 81 |
+
)
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _clamp_manual_target(position, target_type="object"):
|
| 86 |
+
"""Keep browser-controlled targets inside the supported workspace."""
|
| 87 |
+
if not _finite_vec3(position):
|
| 88 |
+
raise ValueError("Manual target must contain three finite coordinates")
|
| 89 |
+
x, y, z = (float(value) for value in position[:3])
|
| 90 |
+
x = min(max(x, -0.10), 0.90)
|
| 91 |
+
y = min(max(y, -0.65), 0.65)
|
| 92 |
+
z = min(max(z, 0.08 if target_type == "robot_ee" else 0.03), 0.90)
|
| 93 |
+
|
| 94 |
+
cx, cy = config.TABLE_CENTER
|
| 95 |
+
hx, hy = config.TABLE_HALF_EXTENTS[:2]
|
| 96 |
+
if cx - hx <= x <= cx + hx and cy - hy <= y <= cy + hy:
|
| 97 |
+
z = max(z, config.TABLE_TOP_Z + 0.01)
|
| 98 |
+
tx, ty, tz = config.TRAY_POSITION
|
| 99 |
+
thx, thy = config.TRAY_HALF_EXTENTS[:2]
|
| 100 |
+
if tx - thx <= x <= tx + thx and ty - thy <= y <= ty + thy:
|
| 101 |
+
z = max(z, tz + 0.01)
|
| 102 |
+
return [x, y, z]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _load_environment_config(path):
|
| 106 |
+
with open(path, "r", encoding="utf-8") as handle:
|
| 107 |
+
data = json.load(handle)
|
| 108 |
+
required = {"table", "tray", "robot"}
|
| 109 |
+
if not isinstance(data, dict) or not required.issubset(data):
|
| 110 |
+
raise ValueError("File được chọn không phải environment JSON hợp lệ.")
|
| 111 |
+
if "objects" in data and not isinstance(data["objects"], list):
|
| 112 |
+
raise ValueError("Trường objects của environment phải là một danh sách.")
|
| 113 |
+
return data
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _list_environment_files(directory):
|
| 117 |
+
files = []
|
| 118 |
+
for filename in sorted(os.listdir(directory)):
|
| 119 |
+
if not filename.endswith(".json") or filename.endswith(".semantics.json"):
|
| 120 |
+
continue
|
| 121 |
+
path = os.path.join(directory, filename)
|
| 122 |
+
try:
|
| 123 |
+
_load_environment_config(path)
|
| 124 |
+
except (OSError, ValueError, json.JSONDecodeError):
|
| 125 |
+
continue
|
| 126 |
+
files.append(filename)
|
| 127 |
+
return files
|
| 128 |
def get_init_payload(sim: PandaApp) -> dict:
|
| 129 |
"""Gathers the initial static geometry and YCB object definitions."""
|
| 130 |
with pybullet_lock:
|
|
|
|
| 170 |
vis_local_pos = list(vis_pos_com)
|
| 171 |
vis_local_ori = list(vis_ori_com)
|
| 172 |
|
| 173 |
+
import os
|
| 174 |
+
if not web_obj and vd[4]:
|
| 175 |
+
mesh_path = vd[4].decode('utf-8')
|
| 176 |
+
web_obj = os.path.basename(mesh_path)
|
| 177 |
+
if not folder:
|
| 178 |
+
folder = os.path.basename(os.path.dirname(mesh_path))
|
| 179 |
+
candidate_mtls = [
|
| 180 |
+
mesh_path + ".mtl",
|
| 181 |
+
os.path.splitext(mesh_path)[0] + ".mtl",
|
| 182 |
+
]
|
| 183 |
+
matching_mtl = next(
|
| 184 |
+
(
|
| 185 |
+
candidate
|
| 186 |
+
for candidate in candidate_mtls
|
| 187 |
+
if os.path.isfile(candidate)
|
| 188 |
+
),
|
| 189 |
+
None,
|
| 190 |
+
)
|
| 191 |
+
if not web_mtl and matching_mtl:
|
| 192 |
+
web_mtl = os.path.basename(matching_mtl)
|
| 193 |
|
| 194 |
objects_info[name] = {
|
| 195 |
"class": cls,
|
|
|
|
| 366 |
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])
|
| 367 |
return score, md
|
| 368 |
|
| 369 |
+
def run_pipeline_threadsafe(
|
| 370 |
+
user_prompt: str,
|
| 371 |
+
loop,
|
| 372 |
+
use_mock: bool,
|
| 373 |
+
runtime: WebRuntime,
|
| 374 |
+
cancellation_token,
|
| 375 |
+
generation: int,
|
| 376 |
+
task_id: str,
|
| 377 |
+
camera_state: Optional[dict] = None,
|
| 378 |
+
):
|
| 379 |
"""Runs the planning, validation, execution with image streaming, and scoring using closed-loop execution monitor."""
|
| 380 |
global current_sim, pipeline_executing
|
| 381 |
+
pipeline_executing = True
|
| 382 |
+
current_sim.pipeline.set_cancellation_token(cancellation_token)
|
| 383 |
+
|
| 384 |
+
def publish(payload: dict, journal: bool = True):
|
| 385 |
+
payload = {**payload, "task_id": task_id, "generation": generation}
|
| 386 |
+
runtime.publish_threadsafe(payload, loop, journal=journal)
|
| 387 |
|
| 388 |
def log(message: str, step: Optional[int] = None):
|
| 389 |
try:
|
| 390 |
print(f"[WS Log] {message}", flush=True)
|
| 391 |
except Exception:
|
| 392 |
pass
|
| 393 |
+
publish({"type": "log", "message": message, "step": step})
|
| 394 |
|
| 395 |
# Step 1: Planning
|
| 396 |
log("⏳ [1/5] Tôi đang suy nghĩ cách thực hiện...")
|
|
|
|
| 408 |
log(f"✅ [1] Tôi đang phân tích yêu cầu...")
|
| 409 |
|
| 410 |
with pybullet_lock:
|
| 411 |
+
current_sim.pipeline.agent = LLMAgent(
|
| 412 |
+
planner=planner,
|
| 413 |
+
conversation_manager=runtime.conversation_manager,
|
| 414 |
+
)
|
| 415 |
|
| 416 |
+
try:
|
| 417 |
+
MAX_REPLANS = max(0, int(os.environ.get("MAX_REPLANS", "3")))
|
| 418 |
+
except ValueError:
|
| 419 |
+
MAX_REPLANS = 3
|
| 420 |
+
last_failed_sig = None
|
| 421 |
+
last_failed_state_sig = None
|
| 422 |
+
resolved_goal = None
|
| 423 |
|
| 424 |
# Hook pb.stepSimulation to capture states during movements
|
| 425 |
original_step = pb.stepSimulation
|
| 426 |
last_stream_time = [0.0]
|
| 427 |
throttle_interval = 0.033
|
| 428 |
|
| 429 |
+
def wrapped_step():
|
| 430 |
+
cancellation_token.checkpoint()
|
| 431 |
+
original_step()
|
| 432 |
if not current_sim.gui:
|
| 433 |
time.sleep(0.001)
|
| 434 |
curr_time = time.time()
|
|
|
|
| 436 |
last_stream_time[0] = curr_time
|
| 437 |
state_payload = get_simulation_state_payload(current_sim)
|
| 438 |
if state_payload:
|
| 439 |
+
publish(state_payload, journal=False)
|
| 440 |
|
| 441 |
+
for attempt in range(MAX_REPLANS + 1):
|
| 442 |
+
cancellation_token.checkpoint()
|
| 443 |
+
if attempt > 0:
|
| 444 |
+
runtime.set_status("replanning", generation=generation)
|
| 445 |
+
publish({"type": "execution_status", "state": "replanning"})
|
| 446 |
log(f"[MONITOR] Re-plan attempt {attempt}/{MAX_REPLANS} due to: {last_failed_sig}")
|
| 447 |
log("⏳ [1/5] Tôi đang suy nghĩ cách thực hiện...")
|
| 448 |
|
|
|
|
| 470 |
}
|
| 471 |
state_sig = json.dumps(state_sig_dict, sort_keys=True)
|
| 472 |
|
| 473 |
+
try:
|
| 474 |
+
with pybullet_lock:
|
| 475 |
+
llm_start_time = time.time()
|
| 476 |
+
planning_instruction = (
|
| 477 |
+
resolved_goal.canonical_instruction
|
| 478 |
+
if attempt > 0 and resolved_goal is not None
|
| 479 |
+
else user_prompt
|
| 480 |
+
)
|
| 481 |
+
current_sim.pipeline.agent.last_outcome = None
|
| 482 |
+
plan_kwargs = {
|
| 483 |
+
"previous_failed_reasons": last_failed_sig,
|
| 484 |
+
}
|
| 485 |
+
if attempt > 0:
|
| 486 |
+
plan_kwargs["resolve_goal"] = False
|
| 487 |
+
plan = current_sim.pipeline.agent.plan(
|
| 488 |
+
planning_instruction,
|
| 489 |
+
state_text,
|
| 490 |
+
**plan_kwargs,
|
| 491 |
+
)
|
| 492 |
+
outcome = current_sim.pipeline.agent.last_outcome
|
| 493 |
+
if attempt == 0 and outcome is not None:
|
| 494 |
+
resolved_goal = outcome.resolved_goal
|
| 495 |
+
llm_time = time.time() - llm_start_time
|
| 496 |
+
cancellation_token.checkpoint()
|
| 497 |
|
| 498 |
# Summarize plan
|
| 499 |
targets = []
|
|
|
|
| 541 |
"args": args
|
| 542 |
})
|
| 543 |
|
| 544 |
+
publish({"type": "plan", "plan": plan_steps, "summary": summary_msg, "llm_time": llm_time})
|
| 545 |
|
| 546 |
if plan and plan[0].get("function") in ("clarify", "reject"):
|
| 547 |
log(f"Robot phản hồi: {summary_msg}")
|
| 548 |
header_title = "Phản hồi từ Robot" if plan[0].get("function") == "clarify" else "Yêu cầu bị từ chối"
|
| 549 |
score_md = f"### {header_title}\n\n**Robot phản hồi:** {summary_msg}\n"
|
| 550 |
+
publish({
|
| 551 |
+
"type": "result",
|
| 552 |
+
"response_type": plan[0].get("function"),
|
| 553 |
+
"score_display": score_md,
|
| 554 |
+
"score_value": 0,
|
| 555 |
+
"success": False,
|
| 556 |
+
})
|
| 557 |
state_payload = get_simulation_state_payload(current_sim)
|
| 558 |
if state_payload:
|
| 559 |
+
publish(state_payload, journal=False)
|
| 560 |
pipeline_executing = False
|
| 561 |
return
|
| 562 |
|
|
|
|
| 564 |
log("⚠️ [1] Kế hoạch rỗng.")
|
| 565 |
log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
|
| 566 |
score_val, score_md = compute_and_format_score(current_sim, [], True)
|
| 567 |
+
publish({
|
| 568 |
+
"type": "result",
|
| 569 |
+
"score_display": score_md,
|
| 570 |
+
"score_value": score_val,
|
| 571 |
+
})
|
| 572 |
state_payload = get_simulation_state_payload(current_sim)
|
| 573 |
if state_payload:
|
| 574 |
+
publish(state_payload, journal=False)
|
| 575 |
pipeline_executing = False
|
| 576 |
return
|
| 577 |
|
|
|
|
| 591 |
pipeline_executing = False
|
| 592 |
return
|
| 593 |
|
| 594 |
+
# Step 3: PyBullet Execution (Live!)
|
| 595 |
+
log("⏳ [3/5] Tôi bắt đầu thực hiện các bước...")
|
| 596 |
+
runtime.set_status("executing", generation=generation)
|
| 597 |
+
publish({"type": "execution_status", "state": "executing"})
|
| 598 |
|
| 599 |
with pybullet_lock:
|
| 600 |
pb.stepSimulation = wrapped_step
|
|
|
|
| 608 |
# Trigger an initial simulation state transmission
|
| 609 |
state_payload = get_simulation_state_payload(current_sim)
|
| 610 |
if state_payload:
|
| 611 |
+
publish(state_payload, journal=False)
|
| 612 |
|
| 613 |
def format_skill_vn(step_data):
|
| 614 |
fn = step_data.get("function", "")
|
|
|
|
| 634 |
if fn == "close_gripper": return "Đóng tay kẹp"
|
| 635 |
return f"{fn}"
|
| 636 |
|
| 637 |
+
expected_location = None
|
| 638 |
+
for i, step in enumerate(plan, 1):
|
| 639 |
+
cancellation_token.checkpoint()
|
| 640 |
+
runtime.set_status("executing", generation=generation, current_step=i)
|
| 641 |
+
publish({"type": "current_step", "step": i})
|
| 642 |
+
friendly_text = format_skill_vn(step)
|
| 643 |
# Make the first letter lowercase for natural sentence integration
|
| 644 |
if friendly_text:
|
| 645 |
friendly_text = friendly_text[0].lower() + friendly_text[1:]
|
|
|
|
| 674 |
log("✅ [3] Tôi đã hoàn tất các bước.")
|
| 675 |
else:
|
| 676 |
log(f"❌ [3] Thực thi lỗi tại bước {failed_step_index} '{failed_step_data.get('function')}': {step_failure_reason}")
|
| 677 |
+
except ExecutionInterrupted:
|
| 678 |
+
with pybullet_lock:
|
| 679 |
+
current_sim.pipeline.interrupt_hold()
|
| 680 |
+
raise
|
| 681 |
+
except Exception as e:
|
| 682 |
log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
|
| 683 |
executed_successfully = False
|
| 684 |
step_failure_reason = str(e)
|
|
|
|
| 689 |
# Send a final state to ensure visual sync
|
| 690 |
state_payload = get_simulation_state_payload(current_sim)
|
| 691 |
if state_payload:
|
| 692 |
+
publish(state_payload, journal=False)
|
| 693 |
|
| 694 |
# Now check overall goal using execution monitor
|
| 695 |
goal_completed = False
|
|
|
|
| 698 |
with pybullet_lock:
|
| 699 |
final_scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=current_sim.scene.get_name(current_sim.pipeline._carried) if current_sim.pipeline._carried else None)
|
| 700 |
final_state_text = json.dumps(final_scene_state, indent=2)
|
| 701 |
+
goal_completed, goal_reason = (
|
| 702 |
+
current_sim.pipeline.execution_monitor.verify_goal(
|
| 703 |
+
user_prompt,
|
| 704 |
+
final_state_text,
|
| 705 |
+
resolved_goal=resolved_goal,
|
| 706 |
+
)
|
| 707 |
+
)
|
| 708 |
if goal_completed:
|
| 709 |
log(f"✅ [GOAL CHECK] OK: {goal_reason}")
|
| 710 |
else:
|
|
|
|
| 742 |
|
| 743 |
is_success = executed_successfully and goal_completed and score_val >= 50
|
| 744 |
|
| 745 |
+
publish({
|
| 746 |
+
"type": "result",
|
| 747 |
+
"score_display": score_md,
|
| 748 |
+
"score_value": score_val,
|
| 749 |
+
"error_cause": error_cause,
|
| 750 |
+
"success": is_success,
|
| 751 |
+
})
|
| 752 |
+
current_sim.pipeline.set_cancellation_token(None)
|
| 753 |
+
pipeline_executing = False
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
async def command_worker_loop(loop):
|
| 757 |
+
"""Serialize robot commands while allowing the newest prompt to interrupt."""
|
| 758 |
+
global command_worker_task, pipeline_executing
|
| 759 |
+
try:
|
| 760 |
+
while True:
|
| 761 |
+
command = web_runtime.take_pending()
|
| 762 |
+
if command is None:
|
| 763 |
+
return
|
| 764 |
+
generation = command["generation"]
|
| 765 |
+
task_id = command["task_id"]
|
| 766 |
+
interrupted = False
|
| 767 |
+
await web_runtime.publish({
|
| 768 |
+
"type": "command_accepted",
|
| 769 |
+
"prompt": command["prompt"],
|
| 770 |
+
"task_id": task_id,
|
| 771 |
+
"generation": generation,
|
| 772 |
+
})
|
| 773 |
+
await web_runtime.publish({
|
| 774 |
+
"type": "execution_status",
|
| 775 |
+
"state": "planning",
|
| 776 |
+
"task_id": task_id,
|
| 777 |
+
"generation": generation,
|
| 778 |
+
})
|
| 779 |
+
try:
|
| 780 |
+
await asyncio.to_thread(
|
| 781 |
+
run_pipeline_threadsafe,
|
| 782 |
+
command["prompt"],
|
| 783 |
+
loop,
|
| 784 |
+
command["use_mock"],
|
| 785 |
+
web_runtime,
|
| 786 |
+
command["token"],
|
| 787 |
+
generation,
|
| 788 |
+
task_id,
|
| 789 |
+
)
|
| 790 |
+
except ExecutionInterrupted as exc:
|
| 791 |
+
interrupted = True
|
| 792 |
+
pipeline_executing = False
|
| 793 |
+
with pybullet_lock:
|
| 794 |
+
if current_sim is not None and current_sim.pipeline is not None:
|
| 795 |
+
current_sim.pipeline.interrupt_hold()
|
| 796 |
+
web_runtime.set_status("interrupted", generation=generation)
|
| 797 |
+
await web_runtime.publish({
|
| 798 |
+
"type": "interrupted",
|
| 799 |
+
"reason": str(exc),
|
| 800 |
+
"task_id": task_id,
|
| 801 |
+
"generation": generation,
|
| 802 |
+
})
|
| 803 |
+
state_payload = await asyncio.to_thread(
|
| 804 |
+
get_simulation_state_payload,
|
| 805 |
+
current_sim,
|
| 806 |
+
)
|
| 807 |
+
if state_payload:
|
| 808 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 809 |
+
except Exception as exc:
|
| 810 |
+
pipeline_executing = False
|
| 811 |
+
await web_runtime.publish({
|
| 812 |
+
"type": "result",
|
| 813 |
+
"success": False,
|
| 814 |
+
"error_cause": "runtime",
|
| 815 |
+
"score_display": f"### Lỗi thực thi\n\n{exc}",
|
| 816 |
+
"task_id": task_id,
|
| 817 |
+
"generation": generation,
|
| 818 |
+
})
|
| 819 |
+
finally:
|
| 820 |
+
if current_sim is not None and current_sim.pipeline is not None:
|
| 821 |
+
current_sim.pipeline.set_cancellation_token(None)
|
| 822 |
+
web_runtime.complete(
|
| 823 |
+
generation,
|
| 824 |
+
state="interrupted" if interrupted else "completed",
|
| 825 |
+
)
|
| 826 |
+
finally:
|
| 827 |
+
command_worker_task = None
|
| 828 |
+
if web_runtime.has_pending:
|
| 829 |
+
command_worker_task = asyncio.create_task(command_worker_loop(loop))
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
async def wait_for_active_task_stop(timeout=5.0):
|
| 833 |
+
web_runtime.cancel_all("runtime_mutation")
|
| 834 |
+
deadline = time.monotonic() + timeout
|
| 835 |
+
while web_runtime.active_token is not None and time.monotonic() < deadline:
|
| 836 |
+
await asyncio.sleep(0.02)
|
| 837 |
+
return web_runtime.active_token is None
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
@app.websocket("/ws")
|
| 841 |
+
async def websocket_endpoint(websocket: WebSocket):
|
| 842 |
+
global current_sim, command_worker_task, physics_settle_task
|
| 843 |
+
await websocket.accept()
|
| 844 |
+
await web_runtime.subscribe(websocket)
|
| 845 |
loop = asyncio.get_running_loop()
|
| 846 |
|
| 847 |
# Retrieve user's desktop display preference from client query params
|
|
|
|
| 850 |
# Force gui = False to run PyBullet completely headless (DIRECT mode)
|
| 851 |
gui = False
|
| 852 |
|
| 853 |
+
camera_state = {
|
| 854 |
"target": [0.5, 0.0, 0.3],
|
| 855 |
"dist": 1.3,
|
| 856 |
"yaw": 45.0,
|
| 857 |
+
"pitch": -35.0
|
| 858 |
+
}
|
| 859 |
+
drag_state = {"constraint_id": None, "active": False}
|
| 860 |
|
| 861 |
+
async def physics_settle_loop():
|
| 862 |
try:
|
| 863 |
while True:
|
| 864 |
global pipeline_executing
|
|
|
|
| 882 |
pb.stepSimulation(physicsClientId=current_sim.client)
|
| 883 |
await asyncio.to_thread(step)
|
| 884 |
|
| 885 |
+
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 886 |
+
if state_payload:
|
| 887 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 888 |
await asyncio.sleep(1/30.0)
|
| 889 |
except asyncio.CancelledError:
|
| 890 |
pass
|
|
|
|
| 917 |
except Exception:
|
| 918 |
is_connected = False
|
| 919 |
|
| 920 |
+
# Reconnect/reload deliberately keeps the live PyBullet state.
|
| 921 |
await asyncio.to_thread(init_sim)
|
| 922 |
# Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
|
| 923 |
await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
|
| 924 |
|
| 925 |
# Send environment list
|
| 926 |
try:
|
| 927 |
+
env_files = _list_environment_files(
|
| 928 |
+
os.path.join(PROJECT_SRC, "envs")
|
| 929 |
+
)
|
| 930 |
+
await websocket.send_json({"type": "env_list", "envs": env_files})
|
| 931 |
|
| 932 |
# Send initial static scene data (only needs to be sent once)
|
| 933 |
+
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
|
| 934 |
+
web_runtime.latest_init = init_payload
|
| 935 |
+
await websocket.send_json(init_payload)
|
| 936 |
# Send the first simulation state to sync objects and joints
|
| 937 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 938 |
+
if state_payload:
|
| 939 |
+
web_runtime.latest_state = state_payload
|
| 940 |
+
await websocket.send_json(state_payload)
|
| 941 |
+
await websocket.send_json(web_runtime.snapshot())
|
| 942 |
+
|
| 943 |
+
if physics_settle_task is None or physics_settle_task.done():
|
| 944 |
+
physics_settle_task = asyncio.create_task(physics_settle_loop())
|
| 945 |
|
| 946 |
+
while True:
|
| 947 |
data = await websocket.receive_text()
|
| 948 |
payload = json.loads(data)
|
| 949 |
|
| 950 |
p_type = payload.get("type")
|
| 951 |
+
if p_type == "run":
|
| 952 |
+
prompt = payload.get("prompt", "")
|
| 953 |
+
use_mock = payload.get("mock", False)
|
| 954 |
+
if prompt.strip():
|
| 955 |
+
command = web_runtime.submit(prompt.strip(), use_mock)
|
| 956 |
+
await web_runtime.publish({
|
| 957 |
+
"type": "interrupt_requested",
|
| 958 |
+
"generation": command["generation"],
|
| 959 |
+
"task_id": command["task_id"],
|
| 960 |
+
})
|
| 961 |
+
if command_worker_task is None or command_worker_task.done():
|
| 962 |
+
command_worker_task = asyncio.create_task(
|
| 963 |
+
command_worker_loop(loop)
|
| 964 |
+
)
|
| 965 |
+
|
| 966 |
+
elif p_type == "cancel":
|
| 967 |
+
if web_runtime.cancel_all("user_cancelled"):
|
| 968 |
+
await web_runtime.publish({
|
| 969 |
+
"type": "interrupt_requested",
|
| 970 |
+
"generation": web_runtime.active_generation,
|
| 971 |
+
})
|
| 972 |
|
| 973 |
|
| 974 |
+
elif p_type == "mouse_pick_start":
|
| 975 |
+
if web_runtime.active_token is not None:
|
| 976 |
+
if not await wait_for_active_task_stop():
|
| 977 |
+
await websocket.send_json({
|
| 978 |
+
"type": "drag_rejected",
|
| 979 |
+
"reason": "Robot chưa dừng an toàn.",
|
| 980 |
+
})
|
| 981 |
+
continue
|
| 982 |
+
rayFrom = payload.get("rayFrom")
|
| 983 |
+
rayTo = payload.get("rayTo")
|
| 984 |
+
requested_type = payload.get("target_type")
|
| 985 |
+
requested_name = payload.get("object_id")
|
| 986 |
+
if _finite_vec3(rayFrom) and _finite_vec3(rayTo):
|
| 987 |
+
async with executor_lock:
|
| 988 |
+
def do_pick():
|
| 989 |
+
with pybullet_lock:
|
| 990 |
+
if drag_state.get("constraint_id") is not None:
|
| 991 |
+
pb.removeConstraint(
|
| 992 |
+
drag_state["constraint_id"],
|
| 993 |
+
physicsClientId=current_sim.client,
|
| 994 |
+
)
|
| 995 |
+
hit = pb.rayTest(
|
| 996 |
+
rayFrom,
|
| 997 |
+
rayTo,
|
| 998 |
+
physicsClientId=current_sim.client,
|
| 999 |
+
)[0]
|
| 1000 |
+
hit_uid, link_index, hit_pos = hit[0], hit[1], hit[3]
|
| 1001 |
+
drag_id = uuid.uuid4().hex
|
| 1002 |
+
|
| 1003 |
+
if requested_type == "robot_ee":
|
| 1004 |
+
if hit_uid != current_sim.controller.robot_id:
|
| 1005 |
+
return None
|
| 1006 |
+
drag_state.update({
|
| 1007 |
+
"drag_id": drag_id,
|
| 1008 |
+
"target_type": "robot_ee",
|
| 1009 |
+
"object_name": None,
|
| 1010 |
+
"constraint_id": None,
|
| 1011 |
+
"active": True,
|
| 1012 |
+
})
|
| 1013 |
+
return dict(drag_state)
|
| 1014 |
+
|
| 1015 |
+
object_id = current_sim.scene.name_to_id(
|
| 1016 |
+
requested_name
|
| 1017 |
+
)
|
| 1018 |
+
if object_id is None:
|
| 1019 |
+
return None
|
| 1020 |
+
mass = pb.getDynamicsInfo(
|
| 1021 |
+
object_id,
|
| 1022 |
+
-1,
|
| 1023 |
+
physicsClientId=current_sim.client,
|
| 1024 |
+
)[0]
|
| 1025 |
+
if mass <= 0:
|
| 1026 |
+
return None
|
| 1027 |
+
pos, _ = pb.getBasePositionAndOrientation(
|
| 1028 |
+
object_id,
|
| 1029 |
+
physicsClientId=current_sim.client,
|
| 1030 |
+
)
|
| 1031 |
+
constraint_id = pb.createConstraint(
|
| 1032 |
+
parentBodyUniqueId=object_id,
|
| 1033 |
+
parentLinkIndex=-1,
|
| 1034 |
+
childBodyUniqueId=-1,
|
| 1035 |
+
childLinkIndex=-1,
|
| 1036 |
+
jointType=pb.JOINT_POINT2POINT,
|
| 1037 |
+
jointAxis=[0, 0, 0],
|
| 1038 |
+
parentFramePosition=[0, 0, 0],
|
| 1039 |
+
childFramePosition=pos,
|
| 1040 |
+
physicsClientId=current_sim.client,
|
| 1041 |
+
)
|
| 1042 |
+
pb.changeConstraint(
|
| 1043 |
+
constraint_id,
|
| 1044 |
+
maxForce=500,
|
| 1045 |
+
physicsClientId=current_sim.client,
|
| 1046 |
+
)
|
| 1047 |
+
drag_state.update({
|
| 1048 |
+
"drag_id": drag_id,
|
| 1049 |
+
"target_type": "object",
|
| 1050 |
+
"object_name": requested_name,
|
| 1051 |
+
"constraint_id": constraint_id,
|
| 1052 |
+
"active": True,
|
| 1053 |
+
})
|
| 1054 |
+
return dict(drag_state)
|
| 1055 |
+
started = await asyncio.to_thread(do_pick)
|
| 1056 |
+
|
| 1057 |
+
if not started:
|
| 1058 |
+
await websocket.send_json({
|
| 1059 |
+
"type": "drag_rejected",
|
| 1060 |
+
"reason": "Vật được chọn trên web không khớp scene vật lý.",
|
| 1061 |
+
})
|
| 1062 |
+
continue
|
| 1063 |
+
await websocket.send_json({
|
| 1064 |
+
"type": "drag_started",
|
| 1065 |
+
"drag_id": started["drag_id"],
|
| 1066 |
+
"target_type": started["target_type"],
|
| 1067 |
+
"object_id": started.get("object_name"),
|
| 1068 |
+
})
|
| 1069 |
+
|
| 1070 |
+
if (
|
| 1071 |
+
started["target_type"] == "object"
|
| 1072 |
+
and (
|
| 1073 |
+
drag_state.get("task") is None
|
| 1074 |
+
or drag_state["task"].done()
|
| 1075 |
+
)
|
| 1076 |
+
):
|
| 1077 |
+
async def drag_loop():
|
| 1078 |
+
while drag_state.get("active") and drag_state.get("constraint_id") is not None:
|
| 1079 |
async with executor_lock:
|
| 1080 |
def step():
|
| 1081 |
with pybullet_lock:
|
|
|
|
| 1085 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1086 |
if state_payload:
|
| 1087 |
try:
|
| 1088 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 1089 |
except Exception:
|
| 1090 |
break
|
| 1091 |
await asyncio.sleep(1/60.0)
|
| 1092 |
drag_state["task"] = asyncio.create_task(drag_loop())
|
| 1093 |
|
| 1094 |
+
elif p_type == "mouse_pick_update":
|
| 1095 |
+
targetPos = payload.get("targetPos")
|
| 1096 |
+
drag_id = payload.get("drag_id")
|
| 1097 |
+
if (
|
| 1098 |
+
drag_id
|
| 1099 |
+
and drag_id == drag_state.get("drag_id")
|
| 1100 |
+
and _finite_vec3(targetPos)
|
| 1101 |
+
):
|
| 1102 |
+
target_pos = _clamp_manual_target(
|
| 1103 |
+
targetPos,
|
| 1104 |
+
drag_state.get("target_type", "object"),
|
| 1105 |
+
)
|
| 1106 |
+
async with executor_lock:
|
| 1107 |
+
def do_update():
|
| 1108 |
+
with pybullet_lock:
|
| 1109 |
+
if drag_state.get("target_type") == "robot_ee":
|
| 1110 |
+
link_state = pb.getLinkState(
|
| 1111 |
+
current_sim.controller.robot_id,
|
| 1112 |
+
current_sim.controller.ee_index,
|
| 1113 |
+
physicsClientId=current_sim.client,
|
| 1114 |
+
)
|
| 1115 |
+
solution = pb.calculateInverseKinematics(
|
| 1116 |
+
current_sim.controller.robot_id,
|
| 1117 |
+
current_sim.controller.ee_index,
|
| 1118 |
+
target_pos,
|
| 1119 |
+
link_state[1],
|
| 1120 |
+
lowerLimits=current_sim.controller._lower_limits,
|
| 1121 |
+
upperLimits=current_sim.controller._upper_limits,
|
| 1122 |
+
jointRanges=current_sim.controller._joint_ranges,
|
| 1123 |
+
restPoses=current_sim.controller._rest_poses,
|
| 1124 |
+
maxNumIterations=200,
|
| 1125 |
+
residualThreshold=1e-5,
|
| 1126 |
+
physicsClientId=current_sim.client,
|
| 1127 |
+
)
|
| 1128 |
+
for idx, q in enumerate(solution[:7]):
|
| 1129 |
+
pb.resetJointState(
|
| 1130 |
+
current_sim.controller.robot_id,
|
| 1131 |
+
idx,
|
| 1132 |
+
q,
|
| 1133 |
+
physicsClientId=current_sim.client,
|
| 1134 |
+
)
|
| 1135 |
+
elif drag_state.get("constraint_id") is not None:
|
| 1136 |
+
pb.changeConstraint(
|
| 1137 |
+
drag_state["constraint_id"],
|
| 1138 |
+
target_pos,
|
| 1139 |
+
maxForce=500,
|
| 1140 |
+
physicsClientId=current_sim.client,
|
| 1141 |
+
)
|
| 1142 |
+
await asyncio.to_thread(do_update)
|
| 1143 |
+
state_payload = await asyncio.to_thread(
|
| 1144 |
+
get_simulation_state_payload,
|
| 1145 |
+
current_sim,
|
| 1146 |
+
)
|
| 1147 |
+
if state_payload:
|
| 1148 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 1149 |
+
|
| 1150 |
+
elif p_type == "mouse_pick_end":
|
| 1151 |
+
drag_id = payload.get("drag_id")
|
| 1152 |
+
if drag_id != drag_state.get("drag_id"):
|
| 1153 |
+
continue
|
| 1154 |
+
drag_state["active"] = False
|
| 1155 |
+
async with executor_lock:
|
| 1156 |
+
def do_end():
|
| 1157 |
+
with pybullet_lock:
|
| 1158 |
if drag_state.get("constraint_id") is not None:
|
| 1159 |
+
pb.removeConstraint(drag_state["constraint_id"], physicsClientId=current_sim.client)
|
| 1160 |
+
drag_state["constraint_id"] = None
|
| 1161 |
+
if drag_state.get("target_type") == "robot_ee":
|
| 1162 |
+
current_sim.controller.hold_current_pose()
|
| 1163 |
+
await asyncio.to_thread(do_end)
|
| 1164 |
+
drag_state["drag_id"] = None
|
| 1165 |
+
drag_state["target_type"] = None
|
| 1166 |
+
for _ in range(20):
|
| 1167 |
+
with pybullet_lock:
|
| 1168 |
+
pb.stepSimulation(physicsClientId=current_sim.client)
|
| 1169 |
+
state_payload = await asyncio.to_thread(
|
| 1170 |
+
get_simulation_state_payload,
|
| 1171 |
+
current_sim,
|
| 1172 |
+
)
|
| 1173 |
+
if state_payload:
|
| 1174 |
+
await web_runtime.publish(state_payload, journal=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1175 |
|
| 1176 |
+
elif p_type == "spawn_catalog_object":
|
| 1177 |
+
if web_runtime.active_token is not None:
|
| 1178 |
+
if not await wait_for_active_task_stop():
|
| 1179 |
+
continue
|
| 1180 |
+
folder = payload.get("folder")
|
| 1181 |
+
position = payload.get("position")
|
| 1182 |
+
if not _finite_vec3(position):
|
| 1183 |
+
continue
|
| 1184 |
+
spawn_position = _clamp_manual_target(position, "object")
|
| 1185 |
+
async with executor_lock:
|
| 1186 |
+
def spawn_object():
|
| 1187 |
+
with pybullet_lock:
|
| 1188 |
+
return current_sim.env_builder.spawn_catalog_object(
|
| 1189 |
+
folder,
|
| 1190 |
+
spawn_position,
|
| 1191 |
+
)
|
| 1192 |
+
try:
|
| 1193 |
+
_, object_name = await asyncio.to_thread(spawn_object)
|
| 1194 |
+
except (ValueError, OSError) as exc:
|
| 1195 |
+
await websocket.send_json({
|
| 1196 |
+
"type": "spawn_rejected",
|
| 1197 |
+
"reason": str(exc),
|
| 1198 |
+
})
|
| 1199 |
+
continue
|
| 1200 |
+
for _ in range(30):
|
| 1201 |
+
with pybullet_lock:
|
| 1202 |
+
pb.stepSimulation(physicsClientId=current_sim.client)
|
| 1203 |
+
init_payload = await asyncio.to_thread(
|
| 1204 |
+
get_init_payload,
|
| 1205 |
+
current_sim,
|
| 1206 |
+
)
|
| 1207 |
+
web_runtime.latest_init = init_payload
|
| 1208 |
+
state_payload = await asyncio.to_thread(
|
| 1209 |
+
get_simulation_state_payload,
|
| 1210 |
+
current_sim,
|
| 1211 |
+
)
|
| 1212 |
+
await web_runtime.publish({
|
| 1213 |
+
"type": "object_added",
|
| 1214 |
+
"name": object_name,
|
| 1215 |
+
"config": init_payload["objects"][object_name],
|
| 1216 |
+
"state": (
|
| 1217 |
+
state_payload.get("objects", {}).get(object_name)
|
| 1218 |
+
if state_payload
|
| 1219 |
+
else None
|
| 1220 |
+
),
|
| 1221 |
+
}, journal=False)
|
| 1222 |
+
if state_payload:
|
| 1223 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 1224 |
+
await web_runtime.publish({
|
| 1225 |
+
"type": "log",
|
| 1226 |
+
"message": f"Đã thêm '{object_name}' vào môi trường.",
|
| 1227 |
+
})
|
| 1228 |
+
|
| 1229 |
+
elif p_type == "delete_object":
|
| 1230 |
+
if web_runtime.active_token is not None:
|
| 1231 |
+
if not await wait_for_active_task_stop():
|
| 1232 |
+
continue
|
| 1233 |
+
object_name = payload.get("name")
|
| 1234 |
+
async with executor_lock:
|
| 1235 |
+
def delete_object():
|
| 1236 |
+
with pybullet_lock:
|
| 1237 |
+
object_id = current_sim.scene.name_to_id(
|
| 1238 |
+
object_name
|
| 1239 |
+
)
|
| 1240 |
+
if object_id is None:
|
| 1241 |
+
return False
|
| 1242 |
+
if current_sim.pipeline._carried == object_id:
|
| 1243 |
+
return False
|
| 1244 |
+
pb.removeBody(
|
| 1245 |
+
object_id,
|
| 1246 |
+
physicsClientId=current_sim.client,
|
| 1247 |
+
)
|
| 1248 |
+
current_sim.scene.unregister_object(object_id)
|
| 1249 |
+
return True
|
| 1250 |
+
deleted = await asyncio.to_thread(delete_object)
|
| 1251 |
+
if not deleted:
|
| 1252 |
+
await websocket.send_json({
|
| 1253 |
+
"type": "delete_rejected",
|
| 1254 |
+
"reason": "Không thể xóa vật đang được giữ hoặc không tồn tại.",
|
| 1255 |
+
})
|
| 1256 |
+
continue
|
| 1257 |
+
await web_runtime.publish({
|
| 1258 |
+
"type": "object_removed",
|
| 1259 |
+
"name": object_name,
|
| 1260 |
+
}, journal=False)
|
| 1261 |
+
state_payload = await asyncio.to_thread(
|
| 1262 |
+
get_simulation_state_payload,
|
| 1263 |
+
current_sim,
|
| 1264 |
+
)
|
| 1265 |
+
if state_payload:
|
| 1266 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 1267 |
+
await web_runtime.publish({
|
| 1268 |
+
"type": "log",
|
| 1269 |
+
"message": f"Đã xóa '{object_name}' khỏi môi trường.",
|
| 1270 |
+
})
|
| 1271 |
+
|
| 1272 |
+
elif p_type == "reset":
|
| 1273 |
+
if not await wait_for_active_task_stop():
|
| 1274 |
+
await web_runtime.publish({
|
| 1275 |
+
"type": "log",
|
| 1276 |
+
"message": "Không thể reset khi robot chưa dừng an toàn.",
|
| 1277 |
+
})
|
| 1278 |
+
continue
|
| 1279 |
+
async with executor_lock:
|
| 1280 |
def reset_sim():
|
| 1281 |
with pybullet_lock:
|
| 1282 |
current_sim.reset_objects(seed=0)
|
| 1283 |
current_sim.controller.reset_to_home()
|
| 1284 |
+
await asyncio.to_thread(reset_sim)
|
| 1285 |
+
web_runtime.conversation_manager.clear()
|
| 1286 |
+
web_runtime.clear_task_history()
|
| 1287 |
|
| 1288 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1289 |
if state_payload:
|
| 1290 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 1291 |
+
await web_runtime.publish({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
|
| 1292 |
|
| 1293 |
+
elif p_type == "change_env":
|
| 1294 |
+
if not await wait_for_active_task_stop():
|
| 1295 |
+
await web_runtime.publish({
|
| 1296 |
+
"type": "log",
|
| 1297 |
+
"message": "Không thể đổi môi trường khi robot chưa dừng an toàn.",
|
| 1298 |
+
})
|
| 1299 |
+
continue
|
| 1300 |
+
env_file = payload.get("env")
|
| 1301 |
+
if (
|
| 1302 |
+
not isinstance(env_file, str)
|
| 1303 |
+
or os.path.basename(env_file) != env_file
|
| 1304 |
+
):
|
| 1305 |
+
await websocket.send_json({
|
| 1306 |
+
"type": "environment_rejected",
|
| 1307 |
+
"reason": "Tên environment không hợp lệ.",
|
| 1308 |
+
})
|
| 1309 |
+
continue
|
| 1310 |
+
env_path = os.path.join(PROJECT_SRC, "envs", env_file)
|
| 1311 |
+
try:
|
| 1312 |
+
_load_environment_config(env_path)
|
| 1313 |
+
except (
|
| 1314 |
+
OSError,
|
| 1315 |
+
ValueError,
|
| 1316 |
+
json.JSONDecodeError,
|
| 1317 |
+
) as exc:
|
| 1318 |
+
await websocket.send_json({
|
| 1319 |
+
"type": "environment_rejected",
|
| 1320 |
+
"reason": str(exc),
|
| 1321 |
+
})
|
| 1322 |
+
continue
|
| 1323 |
+
async with executor_lock:
|
| 1324 |
def change_sim_env():
|
| 1325 |
with pybullet_lock:
|
| 1326 |
current_sim.change_environment(env_path)
|
| 1327 |
+
await asyncio.to_thread(change_sim_env)
|
| 1328 |
+
web_runtime.conversation_manager.clear()
|
| 1329 |
+
web_runtime.clear_task_history()
|
| 1330 |
|
| 1331 |
# Send the new static data
|
| 1332 |
+
init_payload = await asyncio.to_thread(get_init_payload, current_sim)
|
| 1333 |
+
web_runtime.latest_init = init_payload
|
| 1334 |
+
await web_runtime.publish(init_payload, journal=False)
|
| 1335 |
|
| 1336 |
# Send the new dynamic state
|
| 1337 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1338 |
if state_payload:
|
| 1339 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 1340 |
+
await web_runtime.publish({"type": "log", "message": f"🌍 Đã chuyển sang môi trường {env_file}."})
|
| 1341 |
|
| 1342 |
+
elif p_type == "update_object_pose":
|
| 1343 |
+
if web_runtime.active_token is not None:
|
| 1344 |
+
continue
|
| 1345 |
name = payload.get("name")
|
| 1346 |
pos = payload.get("pos")
|
| 1347 |
ori = payload.get("ori")
|
|
|
|
| 1355 |
|
| 1356 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1357 |
if state_payload:
|
| 1358 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 1359 |
|
| 1360 |
+
elif p_type == "update_joints":
|
| 1361 |
+
if web_runtime.active_token is not None:
|
| 1362 |
+
continue
|
| 1363 |
joints_data = payload.get("joints")
|
| 1364 |
async with executor_lock:
|
| 1365 |
def move_joints():
|
|
|
|
| 1373 |
|
| 1374 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1375 |
if state_payload:
|
| 1376 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 1377 |
+
elif p_type == "update_robot_ee":
|
| 1378 |
+
if web_runtime.active_token is not None:
|
| 1379 |
+
continue
|
| 1380 |
pos = payload.get("pos")
|
| 1381 |
async with executor_lock:
|
| 1382 |
def move_robot_ee():
|
|
|
|
| 1413 |
|
| 1414 |
state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
|
| 1415 |
if state_payload:
|
| 1416 |
+
await web_runtime.publish(state_payload, journal=False)
|
| 1417 |
elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
|
| 1418 |
pass
|
| 1419 |
|
| 1420 |
except WebSocketDisconnect:
|
| 1421 |
print("Client disconnected")
|
| 1422 |
+
except Exception as e:
|
| 1423 |
+
print(f"WS Exception: {e}")
|
| 1424 |
+
finally:
|
| 1425 |
+
drag_state["active"] = False
|
| 1426 |
+
if drag_state.get("constraint_id") is not None:
|
| 1427 |
+
try:
|
| 1428 |
+
with pybullet_lock:
|
| 1429 |
+
pb.removeConstraint(
|
| 1430 |
+
drag_state["constraint_id"],
|
| 1431 |
+
physicsClientId=current_sim.client,
|
| 1432 |
+
)
|
| 1433 |
+
except Exception:
|
| 1434 |
+
pass
|
| 1435 |
+
drag_state["constraint_id"] = None
|
| 1436 |
+
await web_runtime.unsubscribe(websocket)
|
| 1437 |
if __name__ == "__main__":
|
| 1438 |
port = int(os.environ.get("PORT", 8000))
|
| 1439 |
+
uvicorn.run("interactive_server:app", host="0.0.0.0", port=port, reload=False)
|