This commit is contained in:
trung09122002
2026-09-18 18:14:42 +07:00
commit 48bd5377dc
224 changed files with 37685 additions and 0 deletions

840
libs/vslam_web/www/app.js Normal file
View File

@@ -0,0 +1,840 @@
'use strict';
// Web UI thay RViz. Khong dependency.
//
// Ban do la occupancy grid 2D, scan la 2D, path la 2D, pose la mot tam giac.
// Thu 3D duy nhat la point cloud, va no la view debug perception -- nhin tu
// tren xuong to mau theo do cao la du. Do la ly do dung canvas 2D chu khong
// three.js: three.js ~600 kB phai vendor va theo doi license, doi lay mot
// goc nhin ma bai toan nay khong can.
// --- Giai ma nhi phan (khop libs/vslam_web/include/vslam/binary_codec.h) ---
const MAGIC = 0x314C5356; // 'VSL1' little-endian
// Phien ban ma nguon giao dien. TANG khi doi app.js / app3d.js / style.css.
// Hien ngay tren thanh tren cung de phan biet "chua sua" voi "trinh duyet con
// cache ban cu".
const UI_VERSION = '2026-09-18c';
const T_SCAN = 1, T_CLOUD = 2, T_MAP_FULL = 3, T_MAP_PATCH = 4, T_PATH = 5;
// Ban do THE GIOI cua bo mo phong -- khung nhin "Gazebo". Tinh: gui mot lan.
const T_WORLD_MAP = 6;
// Ba ngu nghia cua mot tia. Lan lon chung la lam sai ca man hinh.
const R_NAN = 0xFFFF; // khong do duoc (duoi range_min)
const R_INF = 0xFFFE; // khong co phan xa (vuot range_max)
const R_BLANKED = 0xFFFD; // bi sector mask cat (than robot che)
const state = {
pose: null, gt: null, scan: null, cloud: null, path: null,
map: null, mapImage: null, mapVersion: 0,
bytes: 0, lastBytes: 0, wireRate: 0,
};
const view = { x: 0, y: 0, scale: 40, init: false }; // scale = pixel/met
// --- WebSocket -------------------------------------------------------------
let ws = null;
let reconnectTimer = null;
function connect() {
const token = new URLSearchParams(location.search).get('token');
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const url = proto + '//' + location.host + '/ws' + (token ? '?token=' + token : '');
ws = new WebSocket(url);
ws.binaryType = 'arraybuffer';
ws.onopen = () => setConn(true);
ws.onclose = () => {
setConn(false);
if (!reconnectTimer) reconnectTimer = setTimeout(() => {
reconnectTimer = null;
connect();
}, 1000);
};
ws.onerror = () => ws.close();
ws.onmessage = (ev) => {
if (typeof ev.data === 'string') {
state.bytes += ev.data.length;
try { onState(JSON.parse(ev.data)); } catch (e) { /* khung hong, bo */ }
} else {
state.bytes += ev.data.byteLength;
onBinary(new DataView(ev.data));
}
};
}
function setConn(ok) {
const el = document.getElementById('conn');
el.textContent = ok ? 'da ket noi' : 'mat ket noi';
el.className = 'chip ' + (ok ? 'ok' : 'bad');
}
// --- Khung nhi phan --------------------------------------------------------
function onBinary(dv) {
if (dv.byteLength < 16 || dv.getUint32(0, true) !== MAGIC) return;
const type = dv.getUint8(4);
const off = 16;
if (type === T_SCAN) {
const angleMin = dv.getFloat32(off, true);
const angleInc = dv.getFloat32(off + 4, true);
const rangeMax = dv.getFloat32(off + 12, true);
const n = dv.getUint32(off + 16, true);
const pts = new Float32Array(n * 2);
let m = 0;
for (let i = 0; i < n; i++) {
const raw = dv.getUint16(off + 20 + i * 2, true);
// Ba gia tri canh bien deu KHONG ve. Ve tia blanked se lam ra mot
// vong cung gia o ban kinh range_max quanh robot -- trong nhu tuong.
if (raw === R_NAN || raw === R_INF || raw === R_BLANKED) continue;
const r = raw * 0.001;
const a = angleMin + i * angleInc;
pts[m++] = r * Math.cos(a);
pts[m++] = r * Math.sin(a);
}
state.scan = pts.subarray(0, m);
return;
}
if (type === T_CLOUD) {
const scale = dv.getFloat32(off + 12, true);
const n = dv.getUint32(off + 16, true);
const pts = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
const b = off + 20 + i * 6;
pts[i * 3] = dv.getInt16(b, true) * scale;
pts[i * 3 + 1] = dv.getInt16(b + 2, true) * scale;
pts[i * 3 + 2] = dv.getInt16(b + 4, true) * scale;
}
state.cloud = pts;
return;
}
if (type === T_MAP_FULL || type === T_WORLD_MAP) {
const res = dv.getFloat32(off, true);
const w = dv.getInt32(off + 4, true);
const h = dv.getInt32(off + 8, true);
const ox = dv.getFloat32(off + 12, true);
const oy = dv.getFloat32(off + 16, true);
const runs = dv.getUint32(off + 24, true);
const cells = new Int8Array(w * h);
let p = 0;
for (let r = 0; r < runs; r++) {
const b = off + 28 + r * 3;
const len = dv.getUint16(b, true);
const val = dv.getInt8(b + 2);
cells.fill(val, p, p + len);
p += len;
}
const grid = { res, w, h, ox, oy, cells };
if (type === T_WORLD_MAP) {
// Ban do THE GIOI: su that, de lai cho chuan. KHONG lan vao state.map.
state.worldMap = grid;
state.worldMapImage = rasterize(grid);
if (!view.init) centerOnMap(grid);
return;
}
state.map = grid;
state.mapImage = rasterize(grid);
// Can khung theo ban do THE GIOI neu co -- no la cai khong doi, con ban
// do SLAM lon dan khi quet va se keo khung nhin chay theo.
if (!view.init && !state.worldMap) centerOnMap(grid);
// Bao cho server biet da nhan: no se khong gui lai phien ban nay.
if (ws && ws.readyState === 1 && state.mapVersion) {
ws.send(JSON.stringify({ t: 'ack_map', version: state.mapVersion }));
}
return;
}
if (type === T_PATH) {
const n = dv.getUint32(off, true);
const pts = new Float32Array(n * 2);
for (let i = 0; i < n * 2; i++) pts[i] = dv.getFloat32(off + 4 + i * 4, true);
state.path = pts;
return;
}
}
// Giai RLE mot lan cho moi map_version roi blit -- moi khung chi con mot
// drawImage thay vi ve lai tung o.
function rasterize(map) {
const img = new ImageData(map.w, map.h);
const d = img.data;
for (let i = 0; i < map.cells.length; i++) {
const v = map.cells[i];
// Hang 0 cua occupancy grid la o duoi cung (goc o origin), con hang 0 cua
// ImageData la o tren cung -> lat theo truc y khi ghi.
const x = i % map.w;
const y = map.h - 1 - Math.floor(i / map.w);
const j = (y * map.w + x) * 4;
// ⚠️ CHUA BIET phai TRONG SUOT.
//
// Ban truoc ve no DAC (alpha 255) mau xam toi. Hau qua: ban do SLAM luc
// moi quet gan nhu toan o chua biet, nen no hien ra thanh mot TAM XAM DAC
// 11.8 x 21.7 m che kin khung -- va vi phan chua biet doi rat cham, ca
// khung trong nhu dung yen. Bao cao "khung SLAM khong realtime" chinh la
// trieu chung cua viec nay, KHONG phai cua tan so cap nhat.
//
// RViz ve chua-biet trong suot, va do la ly do ban do o do "lon dan" nhin
// thay duoc.
//
// Mau cung dao lai cho nen TOI: bi chiem SANG (tuong noi len), trong thi
// mo. Ban truoc de bi chiem gan DEN tren nen den -- vo hinh.
let c;
if (v < 0) c = [0, 0, 0, 0]; // chua biet -> TRONG SUOT
else if (v < 50) c = [58, 70, 86, 170]; // trong, mo
else c = [222, 232, 244, 255]; // bi chiem, SANG
d[j] = c[0]; d[j + 1] = c[1]; d[j + 2] = c[2]; d[j + 3] = c[3];
}
const cv = document.createElement('canvas');
cv.width = map.w; cv.height = map.h;
cv.getContext('2d').putImageData(img, 0, 0);
return cv;
}
// --- Khung trang thai (JSON) ----------------------------------------------
function onState(s) {
state.pose = s.pose;
state.mapVersion = s.slam.map_version;
// Hinh hoc robot den TU SERVER (robot.yaml). File nay khong duoc chua mot
// hang so kich thuoc nao -- xem ghi chu trong app3d.js.
if (s.robot) state.robot = s.robot;
txt('px', fmt(s.pose.x, 3));
txt('py', fmt(s.pose.y, 3));
txt('pyaw', fmt(s.pose.yaw, 3));
// Ground truth: chi hien khi CO. Khong co ma hien 0 la noi doi -- client
// khong phan biet duoc "dung o goc" voi "khong biet".
state.gt = s.gt || null;
txt('gtErr', s.gt ? fmt(s.gt.err, 3) + ' m' : '--');
state.slamMode = s.slam.mode;
txt('mode', s.slam.mode);
const st = s.safety.state;
const sv = document.getElementById('safeState');
sv.textContent = st;
sv.className = 'state ' + (st === 'OK' ? 'ok' : (st.indexOf('SLOW') >= 0 ? 'warn' : 'bad'));
txt('safeDetail', s.safety.detail || '');
// min_front la null khi khong do duoc (JSON khong co Infinity).
txt('minFront', s.safety.min_front === null ? 'inf' : fmt(s.safety.min_front, 2) + ' m');
txt('rays', s.safety.front_usable + ' / ' + s.safety.front_rays);
txt('blanked', String(s.safety.front_blanked));
// Vuc: ba trang thai phan biet ro. `detail` mang tien to "cliff:" khi
// khong phan xet duoc -- xem CliffBailName trong cliff_detect.cc.
const cd = String(s.safety.detail || '');
const cv = document.getElementById('cliffState');
if (cv) {
if (s.safety.cliff) {
cv.textContent = 'VUC PHIA TRUOC';
cv.className = 'state bad';
} else if (cd.indexOf('cliff:') === 0) {
cv.textContent = 'khong biet (' + cd.slice(6) + ')';
cv.className = 'state warn';
} else {
cv.textContent = 'khong co vuc';
cv.className = 'state ok';
}
}
if (s.tilt) {
txt('tRoll', fmt(s.tilt.roll * 57.2958, 2) + ' deg');
txt('tPitch', fmt(s.tilt.pitch * 57.2958, 2) + ' deg');
// accel_ok=false nghia la bo loc dang chi tich phan gyro (robot dang
// tang/giam toc hoac vua va cham) -> nghieng dang troi.
txt('tAccel', s.tilt.accel_ok ? 'neo trong luc' : 'gyro thuan (troi)');
}
txt('loc', s.slam.localized ? 'co' : 'khong');
txt('score', fmt(s.slam.score, 2));
txt('pms', fmt(s.slam.process_ms, 0) + ' ms');
txt('mapver', String(s.slam.map_version));
txt('hzLidar', fmt(s.health.lidar_hz, 1));
txt('hzCam', fmt(s.health.camera_hz, 1));
txt('hzImu', fmt(s.health.imu_hz, 1));
txt('hzEkf', fmt(s.health.ekf_hz, 1));
txt('cpu', fmt(s.health.cpu_pct, 0) + ' %');
txt('rss', fmt(s.health.rss_mb, 0) + ' MB');
let total = 0;
for (const k in s.health.drops) total += s.health.drops[k];
txt('drops', String(total));
if (s.teleop) {
txt('linSpeed', fmt(s.teleop.linear_speed, 2));
txt('angSpeed', fmt(s.teleop.angular_speed, 2));
}
const btn = document.getElementById('estop');
btn.textContent = s.safety.estop ? 'GO E-STOP' : 'E-STOP';
joy.classList.toggle('estop', !!s.safety.estop);
}
function txt(id, v) {
const el = document.getElementById(id);
if (el) el.textContent = v;
}
function fmt(v, d) {
return (v === null || v === undefined) ? '--' : Number(v).toFixed(d);
}
// --- Ve --------------------------------------------------------------------
const cv = document.getElementById('main');
const ctx = cv.getContext('2d');
function resize() {
const dpr = window.devicePixelRatio || 1;
cv.width = cv.clientWidth * dpr;
cv.height = cv.clientHeight * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
window.addEventListener('resize', resize);
function centerOnMap(grid) {
const m = grid || state.worldMap || state.map;
if (!m) return;
view.x = m.ox + m.w * m.res / 2;
view.y = m.oy + m.h * m.res / 2;
const w = cv.clientWidth, h = cv.clientHeight;
view.scale = Math.min(w / (m.w * m.res), h / (m.h * m.res)) * 0.9;
view.init = true;
}
// The gioi -> man hinh. y lat dau vi truc y cua canvas huong xuong.
// Canvas DANG duoc ve. O che do chia doi, hai khung dung CHUNG `view` -- co
// y: hai ban do phai thang hang thi moi doi chieu duoc, ma doi chieu chinh la
// ly do mo hai khung.
let curCv = null;
function sx(x) { return (x - view.x) * view.scale + curCv.clientWidth / 2; }
function sy(y) { return curCv.clientHeight / 2 - (y - view.y) * view.scale; }
function on(id) { return document.getElementById(id).checked; }
// Tam giac chi huong. Mot ham cho ca pose uoc luong lan ground truth: hai ban
// chep cua cung mot hinh se lech nhau ngay lan sua dau tien, va luc do khong ai
// so sanh duoc hai cai nua.
function drawRobot(ctx, x, y, yaw, color, alpha) {
const L = 0.30 * view.scale, W = 0.17 * view.scale;
ctx.save();
ctx.globalAlpha = alpha;
ctx.translate(sx(x), sy(y));
ctx.rotate(-yaw);
ctx.beginPath();
ctx.moveTo(L, 0);
ctx.lineTo(-L * 0.6, -W);
ctx.lineTo(-L * 0.6, W);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
}
// Ve MOT khung.
//
// `grid`/`gridImage` : ban do de ve (THE GIOI hay SLAM)
// `robotPose` : pose ve tam giac dac -- su that o khung trai, uoc
// luong o khung phai
// `showGt` : co ve them tam giac ground truth mo khong
//
// Mot ham cho ca hai khung: hai ban chep se lech nhau ngay lan sua dau, va
// luc do khong con doi chieu duoc nua.
function drawScene(targetCv, targetCtx, grid, gridImage, robotPose, showGt, mapToggle) {
curCv = targetCv;
const ctx = targetCtx;
const w = targetCv.clientWidth, h = targetCv.clientHeight;
if (targetCv.width !== w || targetCv.height !== h) {
targetCv.width = w; targetCv.height = h;
}
ctx.fillStyle = '#12151a';
ctx.fillRect(0, 0, w, h);
// Mot khung den khong noi duoc vi sao no den. Neu day la khung SLAM va
// SLAM dang TAT, viet ra -- nguoi van hanh khong phai doan.
if (!grid && mapToggle === 'lyMap' &&
(state.slamMode === 'off' || !state.slamMode)) {
ctx.fillStyle = '#7d8896';
ctx.font = '13px system-ui, sans-serif';
ctx.textAlign = 'center';
ctx.fillText('SLAM dang TAT', w / 2, h / 2 - 10);
ctx.fillText('them --slam vao lenh de quet ban do', w / 2, h / 2 + 10);
ctx.textAlign = 'left';
}
if (grid && gridImage && on(mapToggle || 'lyMap')) {
const m = grid;
ctx.imageSmoothingEnabled = false;
ctx.drawImage(gridImage,
sx(m.ox), sy(m.oy + m.h * m.res),
m.w * m.res * view.scale, m.h * m.res * view.scale);
}
if (state.path && on('lyPath')) {
ctx.strokeStyle = '#5aa9e6';
ctx.lineWidth = 1.5;
ctx.beginPath();
for (let i = 0; i < state.path.length; i += 2) {
const X = sx(state.path[i]), Y = sy(state.path[i + 1]);
i === 0 ? ctx.moveTo(X, Y) : ctx.lineTo(X, Y);
}
ctx.stroke();
}
// scan va cloud o frame robot -> xoay theo pose truoc khi ve.
const p = robotPose;
if (p) {
const c = Math.cos(p.yaw), s = Math.sin(p.yaw);
// Ground truth ve TRUOC pose uoc luong, de pose ve de len tren: cai ta
// dang danh gia phai nhin ro hon cai lam chuan.
if (showGt && state.gt && on('lyGt')) {
drawRobot(ctx, state.gt.x, state.gt.y, state.gt.yaw, '#00c853', 0.45);
}
if (state.cloud && on('lyCloud')) {
const pts = state.cloud;
for (let i = 0; i < pts.length; i += 3) {
const x = p.x + c * pts[i] - s * pts[i + 1];
const y = p.y + s * pts[i] + c * pts[i + 1];
const z = pts[i + 2];
// To mau theo do cao: day la view debug perception, va do cao la
// thu duy nhat dang nhin o goc tu tren xuong.
const t = Math.max(0, Math.min(1, z / 1.2));
ctx.fillStyle = 'rgb(' + Math.round(80 + 175 * t) + ',' +
Math.round(200 - 90 * t) + ',' + Math.round(120 + 60 * t) + ')';
ctx.fillRect(sx(x) - 1, sy(y) - 1, 2, 2);
}
}
if (state.scan && on('lyScan')) {
ctx.fillStyle = '#e2574c';
const pts = state.scan;
// ⚠️ Scan trong frame LASER -- phai bu vi tri gan LiDAR truoc khi dua
// vao pose cua base. Xem ghi chu trong v3dSetScan().
const lx = (state.robot && state.robot.laser_x) || 0;
const ly = (state.robot && state.robot.laser_y) || 0;
for (let i = 0; i < pts.length; i += 2) {
const bx = pts[i] + lx, by = pts[i + 1] + ly;
const x = p.x + c * bx - s * by;
const y = p.y + s * bx + c * by;
ctx.fillRect(sx(x) - 1.5, sy(y) - 1.5, 3, 3);
}
}
drawRobot(ctx, robotPose.x, robotPose.y, robotPose.yaw, '#4ec9a0', 1.0);
}
}
// Nhan khung phai noi KICH THUOC ban do SLAM.
//
// O muc zoom vua ca toa nha (26 x 58 m), ban do SLAM luc moi quet chi
// 1.3 x 1.1 m -- nho duoi mot pixel, va khung phai trong y het nhu hong. Mot
// con so lam ro khac biet giua "chua quet duoc gi" va "khung bi loi".
// ⚠️ Nhan phai noi DUNG trang thai cua SLAM, khong phai doan tu `state.map`.
//
// Ban truoc luon viet "SLAM dang dung", ke ca khi `slam.mode === 'off'`. Khung
// den kem mot nhan noi SLAM dang chay lam nguoi van hanh di tim loi trong SLAM
// suot nhieu phut, trong khi su that chi la node chay THIEU co `--slam`.
//
// Cung lop loi voi chuyen web hien `cliff` tu so do da cu 10 giay trong khi
// FSM da bo qua no: nguoi van hanh tin cai ho NHIN THAY.
function updateSlamLabel() {
if (state.slamMode === 'off' || !state.slamMode) {
labR.textContent = 'SLAM TAT -- chay lai voi --slam';
return;
}
const m = state.map;
labR.textContent = m
? 'SLAM ' + state.slamMode + ' ' + (m.w * m.res).toFixed(1) + ' x ' +
(m.h * m.res).toFixed(1) + ' m'
: 'SLAM ' + state.slamMode + ' (chua co ban do -- lai them)';
}
function draw() {
// ⚠️ 3D va CHIA DOI phai chay CUNG NHAU.
//
// Ban truoc viet `if (use3d) { draw3d(); return; }` -- tuc khi bat 3D thi
// khung PHAI khong bao gio duoc ve lai, no giu nguyen hinh cuoi truoc luc
// bam nut. Trieu chung dung la "tab SLAM khong cap nhat", va no chi xuat
// hien khi bat CA HAI nut -- dung to hop huu ich nhat:
// trai = the gioi 3D (Gazebo) | phai = ban do SLAM (RViz)
if (use3d) {
draw3d();
// Khung phai VAN phai chay khi dang chia doi.
if (split) {
updateSlamLabel();
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap');
}
requestAnimationFrame(draw);
return;
}
if (split) {
updateSlamLabel();
// TRAI = THE GIOI: ban do that + pose THAT. Day la khung de LAI.
drawScene(cv, ctx, state.worldMap, state.worldMapImage,
state.gt || state.pose, false, 'lyWorld');
// PHAI = SLAM: ban do dang dung + pose UOC LUONG. Khung de xem quet toi
// dau, va lech bao nhieu so voi khung trai.
drawScene(cvR, ctxR, state.map, state.mapImage, state.pose, true, 'lyMap');
} else {
// Mot khung: uu tien ban do SLAM neu co, khong thi ban do the gioi.
const haveSlam = !!state.map;
drawScene(cv, ctx,
haveSlam ? state.map : state.worldMap,
haveSlam ? state.mapImage : state.worldMapImage,
state.pose, true, haveSlam ? 'lyMap' : 'lyWorld');
}
requestAnimationFrame(draw);
}
// --- Tuong tac -------------------------------------------------------------
let dragging = false, lastX = 0, lastY = 0;
cv.addEventListener('mousedown', (e) => {
dragging = true; lastX = e.clientX; lastY = e.clientY;
});
window.addEventListener('mouseup', () => { dragging = false; });
window.addEventListener('mousemove', (e) => {
if (!dragging) return;
view.x -= (e.clientX - lastX) / view.scale;
view.y += (e.clientY - lastY) / view.scale;
lastX = e.clientX; lastY = e.clientY;
view.init = true;
});
cv.addEventListener('wheel', (e) => {
e.preventDefault();
view.scale *= e.deltaY < 0 ? 1.1 : 1 / 1.1;
view.scale = Math.max(2, Math.min(400, view.scale));
view.init = true;
}, { passive: false });
cv.addEventListener('dblclick', () => { centerOnMap(); });
// --- Lenh ------------------------------------------------------------------
function post(cmd, body) {
const token = new URLSearchParams(location.search).get('token');
const headers = { 'Content-Type': 'application/json' };
if (token) headers['X-Auth-Token'] = token;
return fetch('/api/' + cmd, { method: 'POST', headers, body: JSON.stringify(body || {}) })
.then(r => r.json())
.then(r => { if (r.code !== 0) alert(cmd + ': ' + r.message); })
.catch(e => alert(cmd + ': ' + e));
}
document.getElementById('estop').addEventListener('click', () => {
const on = document.getElementById('estop').textContent === 'E-STOP';
// Tuong minh, KHONG toggle: mot request bi retry khong duoc phep GO e-stop.
post('safety/estop', { on });
});
document.getElementById('reset').addEventListener('click', () => post('safety/reset', {}));
// --- Joystick --------------------------------------------------------------
//
// Thay cho virtual_joystick.py (896 dong Tkinter) cua ban ROS.
//
// Trang nay CHI gui gia tri da chuan hoa [-1, 1]. Moi phep ramp gia toc, moi
// gioi han van toc, va deadman deu nam o C++. Khong bao gio tin trinh duyet
// ve dinh dang chuyen dong: WebSocket co the lag, tab co the bi treo, va may
// tram co the ngu giua chung.
//
// Ba lop deadman doc lap, tu nong ra sau:
// 1. o day -- nha tay thi knob ve tam va gui 0
// 2. o day -- ngung gui hoan toan neu mat ket noi
// 3. o base -- tu dung neu khong nhan lenh trong 300 ms (lop duy nhat con
// song khi ca tab lan wifi deu chet)
const joy = document.getElementById('joy');
const knob = document.getElementById('knob');
const stick = { active: false, vx: 0, wz: 0, pointerId: null };
const JOY_RADIUS = 54; // do lech toi da cua knob, pixel
const DEADZONE = 0.08; // bo rung tay quanh tam
function setKnob(dx, dy) {
knob.style.transform = 'translate(' + dx + 'px,' + dy + 'px)';
}
function applyStick(dx, dy) {
// Kep vao hinh TRON, khong phai hinh vuong: keo cheo khong duoc phep cho ra
// van toc lon hon keo thang.
const len = Math.hypot(dx, dy);
if (len > JOY_RADIUS) {
dx = dx / len * JOY_RADIUS;
dy = dy / len * JOY_RADIUS;
}
setKnob(dx, dy);
let vx = -dy / JOY_RADIUS; // keo LEN = tien
let wz = -dx / JOY_RADIUS; // keo TRAI = quay trai (nguoc chieu kim dong ho)
if (Math.abs(vx) < DEADZONE) vx = 0;
if (Math.abs(wz) < DEADZONE) wz = 0;
stick.vx = vx;
stick.wz = wz;
txt('jvx', vx.toFixed(2));
txt('jwz', wz.toFixed(2));
}
function releaseStick() {
stick.active = false;
stick.pointerId = null;
joy.classList.remove('active');
applyStick(0, 0);
sendCmd(); // gui 0 NGAY, khong doi tick 20 Hz ke tiep
}
function pointerPos(e) {
const r = joy.getBoundingClientRect();
return {
dx: e.clientX - (r.left + r.width / 2),
dy: e.clientY - (r.top + r.height / 2),
};
}
joy.addEventListener('pointerdown', (e) => {
e.preventDefault();
stick.active = true;
stick.pointerId = e.pointerId;
joy.setPointerCapture(e.pointerId);
joy.classList.add('active');
const p = pointerPos(e);
applyStick(p.dx, p.dy);
});
joy.addEventListener('pointermove', (e) => {
if (!stick.active || e.pointerId !== stick.pointerId) return;
e.preventDefault();
const p = pointerPos(e);
applyStick(p.dx, p.dy);
});
// pointerup VA pointercancel: pointercancel la truong hop trinh duyet cuop
// lai con tro (cuon trang, goi den, chuyen tab). Thieu no thi knob ket o vi
// tri cu va robot chay tiep.
for (const ev of ['pointerup', 'pointercancel', 'lostpointercapture']) {
joy.addEventListener(ev, (e) => {
if (e.pointerId !== stick.pointerId) return;
releaseStick();
});
}
// --- Ban phim --------------------------------------------------------------
// Phim MUI TEN, khop SUPPORTED_KEYS cua TeleopModel ben C++
// ("Up"/"Down"/"Left"/"Right"). Ban dau toi dung WASD -- do la tu nghi ra,
// khong khop mo hinh da co.
const keys = new Set();
const KEY_MAP = {
ArrowUp: [1, 0], ArrowDown: [-1, 0], ArrowLeft: [0, 1], ArrowRight: [0, -1],
};
window.addEventListener('keydown', (e) => {
if (e.key === ' ') { keys.clear(); applyKeys(); e.preventDefault(); return; }
if (e.key === 'q' || e.key === 'Q') { adjustSpeed('lin', -1); return; }
if (e.key === 'e' || e.key === 'E') { adjustSpeed('lin', +1); return; }
if (e.key === '+' || e.key === '=') { adjustSpeed('lin', +1); return; }
if (e.key === '-' || e.key === '_') { adjustSpeed('lin', -1); return; }
if (!(e.key in KEY_MAP) || stick.active) return;
keys.add(e.key);
applyKeys();
e.preventDefault();
});
window.addEventListener('keyup', (e) => {
if (!keys.delete(e.key)) return;
applyKeys();
});
// Mat focus (chuyen tab, alt-tab) = nha het phim. Neu khong thi mot phim
// "dinh" se lam robot chay mai.
window.addEventListener('blur', () => { keys.clear(); applyKeys(); });
function applyKeys() {
if (stick.active) return;
let vx = 0, wz = 0;
for (const k of keys) { vx += KEY_MAP[k][0]; wz += KEY_MAP[k][1]; }
applyStick(-wz * JOY_RADIUS, -vx * JOY_RADIUS);
}
// --- Chinh toc do ----------------------------------------------------------
// Tinh nang cua teleop_model.py: doi scale van toc NGAY KHI DANG CHAY.
// Viec kep vao [min, max] do C++ lam; o day chi gui yeu cau.
function adjustSpeed(which, dir) {
post('teleop/adjust', { axis: which, dir: dir });
}
for (const b of document.querySelectorAll('.sbtn')) {
b.addEventListener('click', () => adjustSpeed(b.dataset.adj, Number(b.dataset.dir)));
}
// --- Gui lenh 20 Hz --------------------------------------------------------
function sendCmd() {
if (!ws || ws.readyState !== 1) return;
ws.send(JSON.stringify({ t: 'cmd', vx: stick.vx, wz: stick.wz }));
}
setInterval(() => {
// Gui LIEN TUC ke ca khi dung yen: deadman o base can nhan duoc lenh deu
// dan de biet nguoi lai van con day. Ngung gui = base tu dung sau 300 ms.
sendCmd();
}, 50);
// --- Do bang thong ---------------------------------------------------------
setInterval(() => {
state.wireRate = state.bytes - state.lastBytes;
state.lastBytes = state.bytes;
txt('wire', (state.wireRate / 1024).toFixed(1) + ' kB/s');
}, 1000);
resize();
connect();
// --- Doi 2D / 3D ----------------------------------------------------------
//
// Hai trinh ve doc CUNG mot `state`, nen khong the lech du lieu. Chi mot cai
// chay tai mot thoi diem: render WebGL khi khong ai nhin la dot CPU/GPU vo
// ich tren Jetson.
// ============ Chia doi: THE GIOI | SLAM ============
//
// Tuong duong mo ca Gazebo lan RViz. Khung trai la SU THAT (de lai cho
// chuan), khung phai la cai SLAM dang dung (de biet quet toi dau). Hai khung
// dung CHUNG `view`, nen pan/zoom khoa voi nhau va doi chieu duoc truc tiep.
const cvR = document.getElementById('mainR');
const ctxR = cvR.getContext('2d');
const btnSplit = document.getElementById('btnSplit');
const labR = document.getElementById('labR');
const wrap = document.querySelector('.canvas-wrap');
let split = false;
btnSplit.addEventListener('click', () => {
if (!state.worldMap) {
// Khong co su that de doi chieu -- chay that, khong phai mo phong.
btnSplit.textContent = 'khong co su that';
setTimeout(() => { btnSplit.textContent = 'chia doi'; }, 1800);
return;
}
split = !split;
wrap.classList.toggle('split', split);
document.getElementById('labL').style.display = split ? '' : 'none';
labR.style.display = split ? '' : 'none';
btnSplit.textContent = split ? 'mot khung' : 'chia doi';
// 3D va chia doi KHONG loai tru nhau: `.split.three` cho ra
// trai = the gioi 3D (Gazebo) | phai = ban do SLAM 2D (RViz)
// -- dung to hop huu ich nhat khi dang quet.
});
{
const el = document.getElementById('uiVer');
if (el) el.textContent = 'ui ' + UI_VERSION;
console.log('vslam ui ' + UI_VERSION);
}
const cv3d = document.getElementById('main3d');
const btn3d = document.getElementById('btn3d');
let use3d = false;
// Hinh hoc 3D THAT cua the gioi -- tai MOT lan, khi bat 3D lan dau.
//
// Khong tai luc mo trang: 6.7 MB la lang phi voi nguoi chi xem khung 2D. Va
// khong tai lai: the gioi khong doi trong mot phien.
//
// 404 KHONG phai loi -- nghia la node chay tu `--map` chu khong tu `--world`,
// va khung 3D quay ve khoi hop dung tu luoi chiem dung.
let worldMeshState = 'chua'; // chua | dang | xong | khong-co
function loadWorldMeshes() {
if (worldMeshState !== 'chua') return;
worldMeshState = 'dang';
fetch('/api/world.bin')
.then((r) => {
if (r.status === 404) { worldMeshState = 'khong-co'; return null; }
if (!r.ok) throw new Error('HTTP ' + r.status);
return r.arrayBuffer();
})
.then((buf) => {
if (!buf) return;
worldMeshState = v3dSetWorldMeshes(buf) ? 'xong' : 'khong-co';
})
.catch((e) => {
console.warn('world.bin:', e);
worldMeshState = 'khong-co';
});
}
btn3d.addEventListener('click', () => {
if (!use3d && !V3D.ready) {
if (!v3dInit(cv3d)) {
btn3d.textContent = '3D loi';
btn3d.classList.add('bad');
return;
}
}
if (!use3d) loadWorldMeshes();
use3d = !use3d;
// Chi doi CLASS. Dat style inline o day se de bep quy tac .split trong
// stylesheet -- dung cai bay da lam khung phai den xi mot lan.
wrap.classList.toggle('three', use3d);
btn3d.textContent = use3d ? '2D' : '3D';
});
// Khoang cach VE giua hai hinh robot -- do tren chinh hai doi tuong 3D, khong
// phai tinh lai tu du lieu.
//
// ⚠️ Doc NGAY tren cai dang duoc ve moi tra loi duoc cau hoi "no lech that hay
// chi trong nhu lech": sai so du lieu va khoang cach hien thi la HAI so khac
// nhau, va da co lan chung khac nhau that (hinh ground truth bi tut 0.075 m vi
// cau truc nhom lech mot tang).
function updateGapChip() {
const el = document.getElementById('gap');
if (!el) return;
const a = V3D.robotGroup && V3D.robotGroup.position;
const b = V3D.gtGroup && V3D.gtGroup.position;
if (!a || !b || !V3D.gtGroup.visible) { el.textContent = 'gap --'; return; }
const d = Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
el.textContent = 'gap ' + d.toFixed(3) + ' m';
el.classList.toggle('bad', d > 0.05);
}
function draw3d() {
if (state.robot) v3dSetShape(state.robot);
if (state.pose) v3dSetPose(V3D.robotGroup, state.pose);
if (state.gt && on('lyGt')) {
if (V3D.gtGroup) V3D.gtGroup.visible = true;
v3dSetPose(V3D.gtGroup, state.gt);
} else if (V3D.gtGroup) {
V3D.gtGroup.visible = false;
}
updateGapChip();
v3dSetScan(on('lyScan') ? state.scan : null, state.pose, state.robot);
v3dSetCloud(on('lyCloud') ? state.cloud : null, state.pose);
// THE GIOI: tuong 3D dung tu ban do mo phong -- day la phan "Gazebo".
// Dung MOT lan (ban do the gioi la tinh), roi chi bat/tat.
// Overlay cam bien (frustum, vanh cliff): tat mac dinh cho giong Gazebo.
v3dSetOverlays(on('lyCam'));
if (state.worldMap) v3dSetWorld(state.worldMap, 2.0);
v3dSetWorldVisible(on('lyWorld'));
// SLAM: lop phu tren san, hien DAN khi quet -- day la phan "RViz". O chua
// quet trong suot nen tuong 3D van nhin xuyen qua.
if (state.map && on('lyMap')) {
v3dSetMap({ ...state.map, data: state.map.cells, version: state.mapVersion });
}
if (V3D.mapMesh) V3D.mapMesh.visible = on('lyMap') && !!state.map;
if (on('lyPath')) v3dSetPath(state.path);
else if (V3D.pathLine) V3D.pathLine.visible = false;
v3dRender(cv3d, on('lyFollow'));
}
requestAnimationFrame(draw);

715
libs/vslam_web/www/app3d.js Normal file
View File

@@ -0,0 +1,715 @@
// Khung nhin 3D -- thay cho RViz.
//
// ================== VI SAO CAN 3D ==================
// Khung 2D nhin tu tren khong the hien duoc thu quan trong nhat cua he nay:
// CHIEU CAO. Camera o 0.80 m chuc xuong 15 do, va vung mu 1.10 m KHONG phai
// mot lua chon tham so -- no la hinh hoc: tia gan nhat cham san o do. Nhin tu
// tren thi con so 1.10 chi la mot vong tron; nhin nghieng thi thay ngay vi
// sao no la 1.10 chu khong phai 0.5.
//
// ================== KHONG DOAN KICH THUOC ==================
// Moi kich thuoc den tu khoi `robot` trong JSON, tuc tu `robot.yaml`. File
// nay KHONG duoc chua mot hang so hinh hoc nao. Ban 2D tung hardcode
// `L = 0.30, W = 0.17` -- khong khop voi bat ky so nao trong robot.yaml (ban
// kinh that 0.24), va khong ai phat hien vi mot tam giac sai kich thuoc van
// trong "nhu that".
//
// ================== HE TOA DO ==================
// ROS: +X truoc, +Y trai, +Z len. three.js: +Y len, -Z truoc.
// Doi MOT lan o `toScene()`, khong rai rac.
'use strict';
const V3D = {
ready: false,
scene: null, camera: null, renderer: null, root: null,
robotGroup: null, scanPts: null, cloudPts: null, mapMesh: null,
worldMesh: null, worldKey: null,
meshWorld: null, // nhom mesh THAT doc tu .world; co thi khong dung khoi hop
gtGroup: null, pathLine: null,
shape: null, // khoi `robot` gan nhat
orbit: { az: -2.2, el: 0.55, dist: 6.0, tx: 0, ty: 0 },
dragging: null,
};
// ROS (x, y, z) -> three.js (x, y, z).
function toScene(x, y, z) {
return new THREE.Vector3(x, z, -y);
}
function v3dInit(canvas) {
if (typeof THREE === 'undefined') {
console.error('three.js chua nap duoc');
return false;
}
V3D.renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
V3D.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
// Bong do: thu duy nhat lam cac khoi tuong tach khoi nhau tren mot ban do
// chi co ba trang thai o. Khong co no thi tat ca la mot mang xam.
V3D.renderer.shadowMap.enabled = true;
V3D.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
V3D.scene = new THREE.Scene();
// ============ BANG MAU KIEU GAZEBO ============
//
// Gazebo dung nen SANG (troi xam nhat), san xam, vat the trang nga. UI con
// lai cua trang nay la nen toi, nhung khung 3D co bang mau RIENG -- vi muc
// tieu cua no la trong giong Gazebo, va tuong trang tren nen toi doc rat te:
// khong co bong, khong co chieu sau, moi khoi thanh mot mang bet.
V3D.scene.background = new THREE.Color(0xb8c6d4);
// Suong mu xa: ban do 2000x2000 o do phan giai 0.05 m la 100 m moi chieu,
// ve het se thanh mot vung nhieu xam. Suong mu cat no mem hon la cat cung.
// Mau suong = mau nen, neu khong se thay mot duong chan troi gia.
V3D.scene.fog = new THREE.Fog(0xb8c6d4, 12, 40);
V3D.camera = new THREE.PerspectiveCamera(55, 1, 0.05, 200);
// Ba nguon sang, khong phai mot.
//
// Ban do occupancy chi co BA trang thai o -- khong vat lieu, khong mau,
// khong noi that. Thu duy nhat lam khoi tuong "doc duoc" la ANH SANG:
// * hemisphere -> troi sang / san toi, cho chieu cao mot huong ro rang
// * directional -> bong do xien, lam noi goc va khe cua
// * fill yeu -> chong mat hoan toan den o phia khuat
// Mot AmbientLight deu tit lam moi buc tuong thanh mot mang phang cung mau,
// va do la ly do ban truoc trong "khong co chi tiet".
V3D.scene.add(new THREE.HemisphereLight(0xdfe9f2, 0x8a9099, 0.9));
const key = new THREE.DirectionalLight(0xfff6e8, 1.15);
key.position.set(8, 16, 6);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
key.shadow.camera.left = -30; key.shadow.camera.right = 30;
key.shadow.camera.top = 30; key.shadow.camera.bottom = -30;
V3D.scene.add(key);
const fill = new THREE.DirectionalLight(0xa8bccc, 0.3);
fill.position.set(-6, 5, -8);
V3D.scene.add(fill);
V3D.root = new THREE.Group();
V3D.scene.add(V3D.root);
// Luoi san 1 m, va truc goc toa do map.
V3D.gridHelper = new THREE.GridHelper(40, 40, 0x93a3b3, 0xa9b6c4);
V3D.root.add(V3D.gridHelper);
V3D.root.add(new THREE.AxesHelper(0.5));
v3dBindMouse(canvas);
V3D.ready = true;
return true;
}
function v3dBindMouse(canvas) {
canvas.addEventListener('mousedown', (e) => {
V3D.dragging = { x: e.clientX, y: e.clientY, btn: e.button };
e.preventDefault();
});
window.addEventListener('mouseup', () => { V3D.dragging = null; });
window.addEventListener('mousemove', (e) => {
if (!V3D.dragging) return;
const dx = e.clientX - V3D.dragging.x, dy = e.clientY - V3D.dragging.y;
V3D.dragging.x = e.clientX; V3D.dragging.y = e.clientY;
if (V3D.dragging.btn === 0) {
V3D.orbit.az -= dx * 0.006;
// Chan o hai dau: qua thien dinh thi khung nhin lat nguoc va nguoi dung
// mat phuong huong.
V3D.orbit.el = Math.max(0.05, Math.min(1.45, V3D.orbit.el + dy * 0.006));
} else {
V3D.orbit.tx -= dx * 0.01;
V3D.orbit.ty += dy * 0.01;
}
});
canvas.addEventListener('wheel', (e) => {
V3D.orbit.dist = Math.max(1.0, Math.min(60, V3D.orbit.dist * (e.deltaY > 0 ? 1.1 : 0.9)));
e.preventDefault();
}, { passive: false });
}
// ---------------------------------------------------------------------------
// Mo hinh robot, dung tu khoi `robot` cua JSON.
// ---------------------------------------------------------------------------
function v3dBuildRobot(r) {
const g = new THREE.Group();
// `base_link` o TAM TRUC banh, cach san dung bang ban kinh banh. Nang ca
// nhom len de san o y = 0 -- moi thu khac (scan, cloud, ban do) deu o he
// toa do map voi san la 0.
g.position.y = r.wheel_radius;
const bodyMat = new THREE.MeshLambertMaterial({ color: 0x3d6ea5 });
const darkMat = new THREE.MeshLambertMaterial({ color: 0x20262e });
// Than: tru tron ban kinh `radius`. Chieu cao chon theo ban kinh, khong
// phai mot hang so -- robot.yaml khong co chieu cao than.
const bodyH = r.radius * 1.2;
const body = new THREE.Mesh(
new THREE.CylinderGeometry(r.radius, r.radius, bodyH, 28), bodyMat);
body.position.y = bodyH / 2;
g.add(body);
// Mui chi huong +X, de nhin mot cai la biet dau la truoc.
const nose = new THREE.Mesh(
new THREE.ConeGeometry(r.radius * 0.28, r.radius * 0.5, 16),
new THREE.MeshLambertMaterial({ color: 0x8ec5ff }));
nose.rotation.z = -Math.PI / 2;
nose.position.set(r.radius * 0.85, bodyH * 0.55, 0);
g.add(nose);
// Hai banh chu dong, cach nhau `wheel_sep`.
for (const side of [-1, 1]) {
const w = new THREE.Mesh(
new THREE.CylinderGeometry(r.wheel_radius, r.wheel_radius, 0.04, 20),
darkMat);
w.rotation.x = Math.PI / 2;
w.position.set(0, 0, side * r.wheel_sep / 2);
g.add(w);
}
// LiDAR: tru nho o dung vi tri trong robot.yaml.
const lidar = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.035, 0.06, 16),
new THREE.MeshLambertMaterial({ color: 0xe2574c }));
lidar.position.copy(toScene(r.laser_x, r.laser_y, r.laser_z));
g.add(lidar);
// Camera: hop nho tren cot, chuc xuong `cam_pitch`.
const camG = new THREE.Group();
camG.position.copy(toScene(r.cam_x, r.cam_y, r.cam_z));
// Chuc xuong = quay quanh truc +Z cua ROS = truc -Y cua three.js... nhung
// vi ta xoay CA NHOM roi moi dat frustum ben trong theo +X, chi can quay
// quanh truc Z cua scene (tuong ung truc Y cua ROS).
camG.rotation.z = -r.cam_pitch;
const cam = new THREE.Mesh(new THREE.BoxGeometry(0.03, 0.05, 0.10), darkMat);
camG.add(cam);
// Cot do camera, tu than len toi camera.
const mastH = r.cam_z - bodyH;
if (mastH > 0) {
const mast = new THREE.Mesh(
new THREE.CylinderGeometry(0.02, 0.02, mastH, 12), darkMat);
mast.position.copy(toScene(r.cam_x, r.cam_y, bodyH + mastH / 2));
g.add(mast);
}
// Frustum camera: hinh chop cut, ve bang duong vien de khong che mat cloud.
// Frustum va vanh cliff la OVERLAY kieu RViz, khong phai mot phan robot.
// Gazebo khong ve chung. Danh dau de bat/tat rieng -- chung to hon than
// robot nhieu lan (1.1-2.5 m so voi ban kinh 0.24 m) nen bat mac dinh se
// lan at ca khung nhin.
{
const fr = v3dFrustum(r);
fr.userData.overlay = true;
camG.add(fr);
}
g.add(camG);
return g;
}
// Khung day cua frustum camera, keo dai toi `cliff_max`.
//
// Day la thu 2D khong the hien duoc: no cho thay NGAY vi sao vung mu la
// `cliff_min` -- tia duoi cung cua frustum cham san o dung do.
function v3dFrustum(r) {
const far = r.cliff_max;
const hw = Math.tan(r.cam_hfov / 2) * far;
const hh = Math.tan(r.cam_vfov / 2) * far;
// Trong frame CAMERA (truoc khi nhom bi chuc xuong): +X la truc quang.
const corners = [
toScene(far, +hw, +hh), toScene(far, -hw, +hh),
toScene(far, -hw, -hh), toScene(far, +hw, -hh),
];
const pts = [];
for (const c of corners) { pts.push(new THREE.Vector3(0, 0, 0), c); }
for (let i = 0; i < 4; ++i) pts.push(corners[i], corners[(i + 1) % 4]);
return new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(pts),
new THREE.LineBasicMaterial({ color: 0x00c853, transparent: true, opacity: 0.45 }));
}
// Vanh danh dau cua so cliff_detect tren san: trong = VUNG MU.
function v3dCliffRings(r) {
const g = new THREE.Group();
const mk = (radius, color) => {
const pts = [];
for (let i = 0; i <= 64; ++i) {
const a = (i / 64) * Math.PI * 2;
pts.push(toScene(r.cam_x + radius * Math.cos(a), radius * Math.sin(a), 0.005));
}
return new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts),
new THREE.LineBasicMaterial({ color: color }));
};
g.add(mk(r.cliff_min, 0xe2574c)); // trong vanh do: camera KHONG THAY GI
g.add(mk(r.cliff_max, 0x4ec9a0));
return g;
}
// ---------------------------------------------------------------------------
// Cap nhat moi khung
// ---------------------------------------------------------------------------
function v3dSetShape(r) {
if (!V3D.ready || !r) return;
// Dung lai CHI khi hinh hoc that su doi -- dung lai moi khung la 10 lan/s
// cap phat hinh hoc vo ich.
const key = JSON.stringify(r);
if (V3D.shapeKey === key) return;
V3D.shapeKey = key;
V3D.shape = r;
if (V3D.robotGroup) V3D.root.remove(V3D.robotGroup);
V3D.robotGroup = new THREE.Group();
V3D.robotGroup.add(v3dBuildRobot(r));
{
const rings = v3dCliffRings(r);
rings.userData.overlay = true;
V3D.robotGroup.add(rings);
}
V3D.root.add(V3D.robotGroup);
if (V3D.gtGroup) V3D.root.remove(V3D.gtGroup);
// ⚠️ Phai BOC y het robotGroup o tren.
//
// Truoc day gtGroup la ket qua cua v3dBuildRobot() TRUC TIEP, con robotGroup
// la mot Group moi BOC lay no. Cau truc lech nhau mot tang, nen phep nang
// than (`g.position.y = wheel_radius`) roi vao tang KHAC nhau o hai ben:
// robotGroup giu duoc no o tang trong, gtGroup thi bi v3dSetPose() xoa mat.
//
// Ket qua: hinh ground truth nam THAP HON hinh uoc luong dung 0.075 m. O goc
// camera nghieng, chenh lech do chieu ra thanh mot khoang cach NGANG nhin
// thay duoc -- trong y het "robot co mot nhan ban o canh", trong khi sai so
// uoc luong that chi 9 mm.
V3D.gtGroup = new THREE.Group();
const gtBody = v3dBuildRobot(r);
V3D.gtGroup.add(gtBody);
V3D.gtGroup.traverse((o) => {
if (o.material) {
o.material = o.material.clone();
o.material.transparent = true;
o.material.opacity = 0.25;
if (o.material.color) o.material.color.set(0x00c853);
}
});
V3D.root.add(V3D.gtGroup);
}
function v3dSetPose(group, p) {
if (!group || !p) return;
// ⚠️ CHI dat x va z. `position.set(p.x, 0, -p.y)` ghi de luon y, ma y la
// phep nang than ma v3dBuildRobot() da dat (`g.position.y = wheel_radius`,
// vi `base_link` o TAM TRUC banh chu khong o san).
//
// Ghi de lam robot lun 0.075 m vao san: banh chim mot nua, va tru LiDAR
// tren robot nam o 0.125 m trong khi diem quet duoc ve o
// `laser_z + wheel_radius` = 0.20 m -- hai thu le nhau ngay tren cung mot
// robot, dung thu de nguoi xem nghi la "troi".
group.position.x = p.x;
group.position.z = -p.y;
group.rotation.y = p.yaw;
}
// scan: mang [x0,y0, x1,y1, ...] trong frame LASER (xem ghi chu ben trong).
function v3dSetScan(arr, pose, r) {
if (!V3D.ready) return;
if (!V3D.scanPts) {
V3D.scanPts = new THREE.Points(
new THREE.BufferGeometry(),
new THREE.PointsMaterial({ color: 0xe2574c, size: 0.05 }));
V3D.root.add(V3D.scanPts);
}
if (!arr || !pose || !r) { V3D.scanPts.visible = false; return; }
V3D.scanPts.visible = true;
const c = Math.cos(pose.yaw), s = Math.sin(pose.yaw);
const n = arr.length / 2;
const pos = new Float32Array(n * 3);
// Scan nam o do cao cua LiDAR, khong phai o san. Ve o san se lam nguoi xem
// tuong LiDAR thay duoc vat thap -- no KHONG thay.
const z = r.laser_z + r.wheel_radius;
// ⚠️ Scan den trong frame LASER, khong phai frame BASE.
//
// `laser_link` cach `base_link` 0.24 m ve phia truoc (robot.yaml). Dat thang
// toa do laser vao pose cua base lam CA vanh quet lui 24 cm: cac tia khong
// con nam tren tuong, va nhin nhu robot bi "troi".
//
// Da do tren the gioi benh vien: khong bu thi 752/944 diem roi trung tuong
// (79.7%); bu roi thi 944/944 (100%).
const lx = r.laser_x || 0, ly = r.laser_y || 0;
for (let i = 0; i < n; ++i) {
const x = arr[i * 2] + lx, y = arr[i * 2 + 1] + ly;
pos[i * 3] = pose.x + c * x - s * y;
pos[i * 3 + 1] = z;
pos[i * 3 + 2] = -(pose.y + s * x + c * y);
}
V3D.scanPts.geometry.dispose();
V3D.scanPts.geometry = new THREE.BufferGeometry();
V3D.scanPts.geometry.setAttribute('position', new THREE.BufferAttribute(pos, 3));
}
// cloud: mang [x,y,z, ...] trong frame BASE_FOOTPRINT (da can trong luc).
function v3dSetCloud(arr, pose) {
if (!V3D.ready) return;
if (!V3D.cloudPts) {
V3D.cloudPts = new THREE.Points(
new THREE.BufferGeometry(),
new THREE.PointsMaterial({ size: 0.03, vertexColors: true }));
V3D.root.add(V3D.cloudPts);
}
if (!arr || !pose) { V3D.cloudPts.visible = false; return; }
V3D.cloudPts.visible = true;
const c = Math.cos(pose.yaw), s = Math.sin(pose.yaw);
const n = arr.length / 3;
const pos = new Float32Array(n * 3), col = new Float32Array(n * 3);
for (let i = 0; i < n; ++i) {
const x = arr[i * 3], y = arr[i * 3 + 1], z = arr[i * 3 + 2];
pos[i * 3] = pose.x + c * x - s * y;
pos[i * 3 + 1] = z;
pos[i * 3 + 2] = -(pose.y + s * x + c * y);
// To mau theo do cao, cung bang mau voi khung 2D.
const t = Math.max(0, Math.min(1, z / 1.2));
col[i * 3] = (80 + 175 * t) / 255;
col[i * 3 + 1] = (200 - 90 * t) / 255;
col[i * 3 + 2] = (120 + 60 * t) / 255;
}
V3D.cloudPts.geometry.dispose();
V3D.cloudPts.geometry = new THREE.BufferGeometry();
V3D.cloudPts.geometry.setAttribute('position', new THREE.BufferAttribute(pos, 3));
V3D.cloudPts.geometry.setAttribute('color', new THREE.BufferAttribute(col, 3));
}
// The gioi 3D: o BI CHIEM -> hop, dung nhu Gazebo dung tuong tu ban do.
//
// ================== VI SAO INSTANCED ==================
// map_hospital co 32945 o bi chiem tren 611212 (5.4%). Mot `Mesh` moi o la
// San, luoi san va suong mu -- phu thuoc BAO cua the gioi, khong phu thuoc
// the gioi duoc ve bang mesh that hay bang khoi hop.
//
// ⚠️ Tach rieng khoi v3dSetWorld() la co chu y: khi chay tu `.world`, hang
// mesh that lam v3dSetWorld() thoat som, va neu san nam ben trong ham do thi
// ca toa nha se lo lung tren nen den.
//
// San dat o TOA DO THE GIOI chu khong theo robot. Dat theo robot la dung cai
// bay "sàn troi theo robot": robot dung yen giua man hinh con ca the gioi
// truot qua, trong y het loi dinh vi.
function v3dSetGround(grid) {
if (!V3D.ready || !grid) return;
const r = grid.res;
if (V3D.floorMesh) {
V3D.root.remove(V3D.floorMesh);
V3D.floorMesh.geometry.dispose();
}
const fw = grid.w * r, fh = grid.h * r;
V3D.floorMesh = new THREE.Mesh(
new THREE.PlaneGeometry(fw, fh),
new THREE.MeshStandardMaterial({ color: 0x9aa5ad, roughness: 1.0 }));
V3D.floorMesh.rotation.x = -Math.PI / 2;
V3D.floorMesh.position.set(grid.ox + fw / 2, -0.004, -(grid.oy + fh / 2));
V3D.floorMesh.receiveShadow = true;
V3D.root.add(V3D.floorMesh);
// Suong mu phai phu HET toa nha, khong thi phan lon ban do tan vao nen va
// trong nhu chua nap. Mac dinh 12-40 m vua cho the gioi tong hop; mot tang
// benh vien 27x59 m thi khong.
const span = Math.max(fw, fh);
V3D.scene.fog.near = span * 0.35;
V3D.scene.fog.far = span * 1.4;
if (V3D.gridHelper) V3D.root.remove(V3D.gridHelper);
V3D.gridHelper = new THREE.GridHelper(Math.ceil(span), Math.ceil(span),
0x93a3b3, 0xa9b6c4);
V3D.root.add(V3D.gridHelper);
}
// ---------------------------------------------------------------------------
// The gioi dung tu MESH THAT cua Gazebo
// ---------------------------------------------------------------------------
//
// Phia C++ da doc `.obj`/`.dae` va gui thang tam giac qua `GET /api/world.bin`
// -- trinh duyet khong co bo doc COLLADA offline, va 149 texture PNG cua bo
// model nay tong cong 74 MB, gui tung ay moi lan mo trang la khong duoc.
//
// Mau tung model lay tu TRUNG VI texture cua chinh no, tinh san phia may chu
// (tools/gen_model_colors.py). Khong co texture thi hinh dang van dung, va
// hinh dang moi la thu nguoi van hanh dung de nhan ra cho minh dang o.
//
// Khong co khoi nay (chay tu `--map` thay vi `--world`) thi v3dSetWorld() ben
// duoi dung khoi hop tu luoi chiem dung -- kem hon nhung van dinh huong duoc.
function v3dSetWorldMeshes(buf) {
if (!V3D.ready || !buf || buf.byteLength < 16) return false;
const dv = new DataView(buf);
if (String.fromCharCode(dv.getUint8(0), dv.getUint8(1), dv.getUint8(2),
dv.getUint8(3)) !== 'VSLW') {
console.error('world.bin: sai magic');
return false;
}
if (dv.getUint32(4, true) !== 1) {
console.error('world.bin: phien ban la');
return false;
}
const nGeom = dv.getUint32(8, true), nInst = dv.getUint32(12, true);
let o = 16;
const geoms = [];
for (let i = 0; i < nGeom; ++i) {
const nameLen = dv.getUint32(o, true); o += 4;
o += nameLen; // ten chi de go loi, khong ve
const r = dv.getUint8(o), g = dv.getUint8(o + 1), b = dv.getUint8(o + 2);
o += 3;
const nTri = dv.getUint32(o, true); o += 4;
// Doc thang tu buffer: 194k tam giac, mot vong lap tao Vector3 moi dinh
// se sinh 580k doi tuong rac.
const pos = new Float32Array(nTri * 9);
for (let k = 0; k < nTri * 3; ++k) {
// ROS (x, y, z) -> three (x, z, -y), lam NGAY o day chu khong qua
// toScene(): mot lan doi truc tren mang phang re hon nhieu lan.
const x = dv.getFloat32(o, true);
const y = dv.getFloat32(o + 4, true);
const z = dv.getFloat32(o + 8, true);
o += 12;
pos[k * 3] = x; pos[k * 3 + 1] = z; pos[k * 3 + 2] = -y;
}
const bg = new THREE.BufferGeometry();
bg.setAttribute('position', new THREE.BufferAttribute(pos, 3));
bg.computeVertexNormals();
geoms.push({ geom: bg, r: r, g: g, b: b, n: 0 });
}
// Dem the hien TRUOC khi cap phat: InstancedMesh co so luong co dinh.
const inst = [];
for (let i = 0; i < nInst; ++i) {
const gi = dv.getUint32(o, true);
const x = dv.getFloat32(o + 4, true);
const y = dv.getFloat32(o + 8, true);
const z = dv.getFloat32(o + 12, true);
const yaw = dv.getFloat32(o + 16, true);
o += 20;
if (gi < geoms.length) { geoms[gi].n++; inst.push([gi, x, y, z, yaw]); }
}
if (V3D.meshWorld) {
V3D.root.remove(V3D.meshWorld);
V3D.meshWorld.traverse((m) => {
if (m.geometry) m.geometry.dispose();
if (m.material) m.material.dispose();
});
}
const group = new THREE.Group();
const made = [];
for (const gd of geoms) {
if (gd.n === 0) { gd.geom.dispose(); made.push(null); continue; }
const mat = new THREE.MeshStandardMaterial({
color: new THREE.Color(gd.r / 255, gd.g / 255, gd.b / 255),
roughness: 0.85, metalness: 0.05,
});
const im = new THREE.InstancedMesh(gd.geom, mat, gd.n);
im.castShadow = true;
im.receiveShadow = true;
im.userData.fill = 0;
made.push(im);
group.add(im);
}
const m4 = new THREE.Matrix4(), q = new THREE.Quaternion();
const axisY = new THREE.Vector3(0, 1, 0), one = new THREE.Vector3(1, 1, 1);
for (const [gi, x, y, z, yaw] of inst) {
const im = made[gi];
if (!im) continue;
// Quay quanh z cua ROS = quay quanh y cua three voi CUNG dau goc: ROS x
// ung voi three x, ROS y ung voi three -z, nen hai phep quay trung nhau.
q.setFromAxisAngle(axisY, yaw);
m4.compose(toScene(x, y, z), q, one);
im.setMatrixAt(im.userData.fill++, m4);
}
for (const im of made) if (im) im.instanceMatrix.needsUpdate = true;
V3D.meshWorld = group;
V3D.root.add(group);
// Khoi hop tu luoi tro nen thua: bo di de khong ve chong len do dac that.
if (V3D.worldMesh) {
V3D.root.remove(V3D.worldMesh);
V3D.worldMesh.geometry.dispose();
V3D.worldMesh.dispose();
V3D.worldMesh = null;
V3D.worldKey = null;
}
return true;
}
// 33k draw call -- khung hinh sup. `InstancedMesh` ve tat ca trong MOT draw
// call: cung hinh hoc, khac ma tran.
//
// Ban do the gioi la TINH trong mo phong, nen chi dung MOT lan.
function v3dSetWorld(grid, wallHeight) {
if (!V3D.ready || !grid) return;
// Da co mesh that thi khong dung khoi hop nua -- ve ca hai se thay tuong
// hop bao quanh do dac that. Nhung SAN thi van phai dung.
if (V3D.meshWorld) { v3dSetGround(grid); return; }
const key = grid.w + 'x' + grid.h + '@' + grid.ox + ',' + grid.oy;
if (V3D.worldKey === key) return;
V3D.worldKey = key;
if (V3D.worldMesh) {
V3D.root.remove(V3D.worldMesh);
V3D.worldMesh.geometry.dispose();
V3D.worldMesh.dispose();
}
// Dem truoc de cap phat dung so instance.
let n = 0;
for (let i = 0; i < grid.cells.length; ++i) if (grid.cells[i] >= 50) n++;
if (n === 0) { V3D.worldMesh = null; return; }
const r = grid.res, hgt = wallHeight || 2.0;
// `MeshStandardMaterial` chu khong `Lambert`: co roughness nen be mat bat
// duoc huong sang, va goc tuong hien ra thay vi phang lì.
const mesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(r, hgt, r),
new THREE.MeshStandardMaterial({ roughness: 0.85, metalness: 0.05 }),
n);
mesh.castShadow = true;
mesh.receiveShadow = true;
const occ = (cx, cy) =>
cx >= 0 && cy >= 0 && cx < grid.w && cy < grid.h &&
grid.cells[cy * grid.w + cx] >= 50;
const m4 = new THREE.Matrix4();
const col = new THREE.Color();
let k = 0;
for (let cy = 0; cy < grid.h; ++cy) {
for (let cx = 0; cx < grid.w; ++cx) {
if (!occ(cx, cy)) continue;
const wx = grid.ox + (cx + 0.5) * r;
const wy = grid.oy + (cy + 0.5) * r;
// Chieu cao theo DO DAY cua buc tuong.
//
// Mot lop o don le (vach ngan, tu, cot) thap hon tuong chiu luc day
// nhieu lop. Do la thu duy nhat ve "chi tiet kien truc" suy ra duoc tu
// mot luoi occupancy -- va no lam mat bang doc duoc ngay: hanh lang,
// phong, do noi that tach han nhau thay vi mot khoi xam dong nhat.
let nb = 0;
for (let dy = -1; dy <= 1; ++dy)
for (let dx = -1; dx <= 1; ++dx)
if ((dx || dy) && occ(cx + dx, cy + dy)) nb++;
const thick = nb / 8; // 0 = don doc, 1 = trong khoi
const hh = hgt * (0.45 + 0.55 * thick);
m4.makeScale(1, hh / hgt, 1);
m4.setPosition(wx, hh / 2, -wy);
mesh.setMatrixAt(k, m4);
// Mau cung theo do day: vach mong sang hon, tuong day toi hon. Cong
// voi bong do, mat bang doc duoc nhu mot ban ve.
// Trang nga hoi am, dam dan theo do day vach -- kieu vat lieu mac
// dinh cua Gazebo.
col.setHSL(0.09, 0.06, 0.88 - 0.20 * thick);
mesh.setColorAt(k, col);
k++;
}
}
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
V3D.worldMesh = mesh;
V3D.root.add(mesh);
v3dSetGround(grid);
}
// Ban do occupancy -> mot mat phang co texture, dat o san.
function v3dSetMap(map) {
if (!V3D.ready || !map || !map.w || !map.h) return;
if (V3D.mapKey === map.version) return;
V3D.mapKey = map.version;
const cv = document.createElement('canvas');
cv.width = map.w; cv.height = map.h;
const g = cv.getContext('2d');
const img = g.createImageData(map.w, map.h);
for (let i = 0; i < map.w * map.h; ++i) {
const v = map.data[i];
// -1 = CHUA BIET. Ve no khac han o trong: "chua di toi" va "da di toi,
// khong co gi" la hai chuyen khac nhau, va gop lai se lam ban do trong
// day du hon thuc te.
// Day la lop phu "DA QUET" chong len the gioi 3D -- tuong duong lop
// Map cua RViz. O CHUA BIET phai TRONG SUOT, neu khong no phu kin ca toa
// nha va che mat tuong 3D.
let r, gg, b, a;
if (v < 0) { r = gg = b = 0; a = 0; } // chua quet -> trong suot
else if (v >= 50) { r = 90; gg = 200; b = 255; a = 230; } // tuong da quet
else { r = 40; gg = 90; b = 130; a = 120; } // san da quet
img.data[i * 4] = r; img.data[i * 4 + 1] = gg;
img.data[i * 4 + 2] = b; img.data[i * 4 + 3] = a;
}
g.putImageData(img, 0, 0);
const tex = new THREE.CanvasTexture(cv);
tex.magFilter = THREE.NearestFilter;
tex.minFilter = THREE.LinearMipmapLinearFilter;
if (V3D.mapMesh) { V3D.root.remove(V3D.mapMesh); V3D.mapMesh.geometry.dispose(); }
const wM = map.w * map.res, hM = map.h * map.res;
V3D.mapMesh = new THREE.Mesh(
new THREE.PlaneGeometry(wM, hM),
new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false }));
V3D.mapMesh.rotation.x = -Math.PI / 2;
// Hoi thap hon san mot chut de khong z-fight voi luoi va vanh cliff.
V3D.mapMesh.position.set(map.ox + wM / 2, -0.002, -(map.oy + hM / 2));
V3D.root.add(V3D.mapMesh);
}
function v3dSetPath(pts) {
if (!V3D.ready) return;
if (V3D.pathLine) { V3D.root.remove(V3D.pathLine); V3D.pathLine.geometry.dispose(); }
if (!pts || pts.length < 4) return;
const v = [];
for (let i = 0; i + 1 < pts.length; i += 2) v.push(toScene(pts[i], pts[i + 1], 0.01));
V3D.pathLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(v),
new THREE.LineBasicMaterial({ color: 0xffb300 }));
V3D.root.add(V3D.pathLine);
}
// Bat/tat cac overlay kieu RViz (frustum camera, vanh cliff).
//
// Gazebo chi ve THE GIOI va ROBOT. Frustum 2.5 m va vanh cliff 1.1-2.5 m to
// hon than robot (ban kinh 0.24 m) hang chuc lan, nen de mac dinh BAT thi
// khung nhin trong khong giong Gazebo chut nao.
// Bat/tat lop "the gioi", du no dung tu mesh that hay tu khoi hop.
function v3dSetWorldVisible(on) {
if (V3D.meshWorld) V3D.meshWorld.visible = on;
if (V3D.worldMesh) V3D.worldMesh.visible = on;
}
function v3dSetOverlays(on) {
if (!V3D.ready || !V3D.root) return;
V3D.root.traverse((o) => {
if (o.userData && o.userData.overlay) o.visible = on;
});
}
function v3dRender(canvas, follow) {
if (!V3D.ready) return;
const w = canvas.clientWidth, h = canvas.clientHeight;
if (canvas.width !== w || canvas.height !== h) {
V3D.renderer.setSize(w, h, false);
V3D.camera.aspect = w / Math.max(1, h);
V3D.camera.updateProjectionMatrix();
}
// Tam quay: bam theo robot neu bat, khong thi theo diem pan cua nguoi dung.
let cx = V3D.orbit.tx, cz = V3D.orbit.ty;
if (follow && V3D.robotGroup) {
cx = V3D.robotGroup.position.x + V3D.orbit.tx;
cz = V3D.robotGroup.position.z + V3D.orbit.ty;
}
const o = V3D.orbit;
V3D.camera.position.set(
cx + o.dist * Math.cos(o.el) * Math.cos(o.az),
o.dist * Math.sin(o.el),
cz + o.dist * Math.cos(o.el) * Math.sin(o.az));
V3D.camera.lookAt(cx, 0.2, cz);
V3D.renderer.render(V3D.scene, V3D.camera);
}

View File

@@ -0,0 +1,156 @@
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>vslam</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<div class="layers">
<label><input type="checkbox" id="lyWorld" checked> the gioi</label>
<label><input type="checkbox" id="lyMap" checked> map SLAM</label>
<label><input type="checkbox" id="lyScan" checked> scan</label>
<label><input type="checkbox" id="lyCloud" checked> cloud</label>
<label><input type="checkbox" id="lyPath" checked> path</label>
<label><input type="checkbox" id="lyCam"> overlay cam bien</label>
<label><input type="checkbox" id="lyGt" checked> ground truth</label>
<label><input type="checkbox" id="lyFollow"> bam robot</label>
</div>
<button id="btnSplit" class="chip" title="Hai khung: THE GIOI (de lai) va SLAM (de xem ban do dang dung)">chia doi</button>
<button id="btn3d" class="chip" title="Doi giua nhin tu tren (2D) va 3D">3D</button>
<div class="spacer"></div>
<!-- ⚠️ O nay ton tai de tra loi MOT cau hoi: trinh duyet dang chay ban JS
nao. Sua o `www/` la sua file tinh, khong phai sua server, nen khoi
dong lai node KHONG lam trinh duyet nap lai. Da mat mot vong trao doi
vi khong phan biet duoc "da sua chua chay" voi "sua roi ma van the". -->
<div id="uiVer" class="chip" title="Phien ban ma nguon giao dien. Khong khop voi ban moi nhat nghia la trinh duyet con cache -- Ctrl-Shift-R.">ui --</div>
<div id="gap" class="chip" title="Khoang cach VE giua hinh uoc luong (xanh duong) va hinh ground truth (xanh la). Day la con so that, do tren chinh hai doi tuong 3D.">gap --</div>
<div id="mode" class="chip">--</div>
<div id="conn" class="chip bad">mat ket noi</div>
</header>
<main>
<div class="canvas-wrap">
<canvas id="main"></canvas>
<!-- Canvas 3D nam CHONG len canvas 2D, an/hien bang nut. Hai trinh ve
doc CUNG mot `state`, nen khong the lech du lieu. -->
<canvas id="main3d"></canvas>
<!-- Khung PHAI o che do chia doi: ban do SLAM dang dung. Khung trai giu
nguyen `main`, hien ban do THE GIOI. -->
<canvas id="mainR"></canvas>
<div id="labL" class="pane-label" style="display:none">THE GIOI (su that)</div>
<div id="labR" class="pane-label" style="display:none">SLAM dang dung</div>
<div id="hint">keo de di chuyen &middot; cuon de phong to &middot; nhan dup de ve giua</div>
</div>
<aside>
<section>
<h2>pose (map)</h2>
<table>
<tr><td>x</td><td id="px">--</td></tr>
<tr><td>y</td><td id="py">--</td></tr>
<tr><td>yaw</td><td id="pyaw">--</td></tr>
<!-- Ground truth chi co khi mo phong. Sai so la thuoc do duy nhat
cho biet uoc luong dang tot hay te. -->
<tr><td>sai so</td><td id="gtErr">--</td></tr>
</table>
</section>
<section>
<h2>safety</h2>
<div id="safeState" class="state">--</div>
<div id="safeDetail" class="detail"></div>
<table>
<tr><td>min_front</td><td id="minFront">--</td></tr>
<tr><td>tia dung duoc</td><td id="rays">--</td></tr>
<tr><td>tia bi che</td><td id="blanked">--</td></tr>
</table>
</section>
<section>
<h2>perception</h2>
<!-- Ba trang thai KHAC NHAU, khong duoc gop: co vuc / khong co vuc /
khong biet. "Khong biet" la khi camera khong nhin thay san (bi vat
can che, khop mat san hong, robot khong bang phang). Gop no vao
"khong co vuc" la dung cai lam robot di thang vao bac thang. -->
<div id="cliffState" class="state">--</div>
<table>
<tr><td>roll</td><td id="tRoll">--</td></tr>
<tr><td>pitch</td><td id="tPitch">--</td></tr>
<tr><td>accel</td><td id="tAccel">--</td></tr>
</table>
</section>
<section>
<h2>slam</h2>
<table>
<tr><td>dinh vi</td><td id="loc">--</td></tr>
<tr><td>diem</td><td id="score">--</td></tr>
<tr><td>process</td><td id="pms">--</td></tr>
<tr><td>map ver</td><td id="mapver">--</td></tr>
</table>
</section>
<section>
<h2>tan so (Hz)</h2>
<table>
<tr><td>lidar</td><td id="hzLidar">--</td></tr>
<tr><td>camera</td><td id="hzCam">--</td></tr>
<tr><td>imu</td><td id="hzImu">--</td></tr>
<tr><td>ekf</td><td id="hzEkf">--</td></tr>
</table>
</section>
<section>
<h2>tai nguyen</h2>
<table>
<tr><td>cpu</td><td id="cpu">--</td></tr>
<tr><td>rss</td><td id="rss">--</td></tr>
<tr><td>drop</td><td id="drops">--</td></tr>
<tr><td>wire</td><td id="wire">--</td></tr>
</table>
</section>
<section>
<h2>dieu khien</h2>
<div class="joy-wrap">
<div id="joy" class="joy">
<div class="joy-cross"></div>
<div id="knob" class="joy-knob"></div>
</div>
</div>
<table>
<tr><td>vx</td><td id="jvx">0.00</td></tr>
<tr><td>wz</td><td id="jwz">0.00</td></tr>
</table>
<div class="speed-row">
<button class="sbtn" data-adj="lin" data-dir="-1">&minus;</button>
<span class="slabel">toc do</span>
<span id="linSpeed" class="sval">0.30</span>
<button class="sbtn" data-adj="lin" data-dir="1">+</button>
</div>
<div class="speed-row">
<button class="sbtn" data-adj="ang" data-dir="-1">&minus;</button>
<span class="slabel">quay</span>
<span id="angSpeed" class="sval">0.70</span>
<button class="sbtn" data-adj="ang" data-dir="1">+</button>
</div>
<div class="hint-sm">keo joystick &middot; phim mui ten &middot; Space = dung<br>+ &minus; hoac Q E de chinh toc do</div>
</section>
<section class="controls">
<button id="estop" class="danger">E-STOP</button>
<button id="reset">RESET</button>
</section>
</aside>
</main>
<script src="vendor/three.min.js"></script>
<script src="app3d.js"></script>
<script src="app.js"></script>
</body>
</html>

View File

@@ -0,0 +1,168 @@
/* Mot trang, khong dependency. Muc tieu < 60 kB cho ca ba file. */
:root {
--bg: #12151a;
--panel: #1a1f27;
--line: #2a323d;
--fg: #d6dde7;
--dim: #7c8798;
--ok: #4ec9a0;
--warn: #e0b34a;
--bad: #e2574c;
--accent: #5aa9e6;
}
* { box-sizing: border-box; }
html, body {
margin: 0; height: 100%;
background: var(--bg); color: var(--fg);
font: 13px/1.45 ui-monospace, "JetBrains Mono", Menlo, Consolas, monospace;
}
header {
display: flex; align-items: center; gap: 12px;
padding: 8px 12px; border-bottom: 1px solid var(--line);
background: var(--panel);
}
.spacer { flex: 1; }
.layers { display: flex; gap: 14px; }
.layers label { cursor: pointer; user-select: none; color: var(--dim); }
.layers input { accent-color: var(--accent); margin-right: 4px; }
.chip {
padding: 3px 10px; border-radius: 3px;
background: #222a34; border: 1px solid var(--line);
}
.chip.ok { color: var(--ok); border-color: #2c5b4c; }
.chip.bad { color: var(--bad); border-color: #5b2f2c; }
main { display: flex; height: calc(100% - 41px); }
.canvas-wrap { position: relative; flex: 1; min-width: 0; }
canvas { display: block; width: 100%; height: 100%; cursor: grab; }
canvas:active { cursor: grabbing; }
#hint {
position: absolute; left: 10px; bottom: 8px;
color: var(--dim); font-size: 11px; pointer-events: none;
}
aside {
width: 260px; flex: none; overflow-y: auto;
border-left: 1px solid var(--line); background: var(--panel);
}
aside section { padding: 10px 12px; border-bottom: 1px solid var(--line); }
aside h2 {
margin: 0 0 6px; font-size: 11px; font-weight: 500;
letter-spacing: .08em; text-transform: uppercase; color: var(--dim);
}
aside table { width: 100%; border-collapse: collapse; }
aside td { padding: 1px 0; }
aside td:first-child { color: var(--dim); }
aside td:last-child { text-align: right; font-variant-numeric: tabular-nums; }
.state {
padding: 5px 8px; border-radius: 3px; text-align: center;
background: #222a34; border: 1px solid var(--line); margin-bottom: 4px;
}
.state.ok { color: var(--ok); border-color: #2c5b4c; }
.state.warn { color: var(--warn); border-color: #5b4d2c; }
.state.bad { color: var(--bad); border-color: #5b2f2c; }
.detail { color: var(--dim); font-size: 11px; min-height: 16px; margin-bottom: 4px; }
.controls { display: flex; gap: 8px; }
button {
flex: 1; padding: 9px; cursor: pointer;
background: #222a34; color: var(--fg);
border: 1px solid var(--line); border-radius: 3px;
font: inherit;
}
button:hover { border-color: var(--accent); }
button.danger { color: var(--bad); border-color: #5b2f2c; }
button.danger:hover { background: var(--bad); color: #fff; }
/* --- Joystick ---
Thay cho virtual_joystick.py (896 dong Tkinter) cua ban ROS.
Chi gui gia tri da chuan hoa [-1,1]; moi phep ramp va deadman deu o C++. */
.joy-wrap { display: flex; justify-content: center; padding: 6px 0 10px; }
.joy {
position: relative;
width: 160px; height: 160px;
border-radius: 50%;
background: radial-gradient(circle at 50% 50%, #222a34 0%, #1a1f27 70%);
border: 1px solid var(--line);
touch-action: none; /* tat pan/zoom cua trinh duyet khi keo */
user-select: none;
cursor: grab;
}
.joy:active { cursor: grabbing; }
/* Hai vach chu thap de thay tam va truc */
.joy-cross::before, .joy-cross::after {
content: ''; position: absolute; background: var(--line);
}
.joy-cross::before { left: 50%; top: 8%; bottom: 8%; width: 1px; transform: translateX(-50%); }
.joy-cross::after { top: 50%; left: 8%; right: 8%; height: 1px; transform: translateY(-50%); }
.joy-knob {
position: absolute; left: 50%; top: 50%;
width: 52px; height: 52px; margin: -26px 0 0 -26px;
border-radius: 50%;
background: var(--accent);
border: 2px solid #7cc0f0;
box-shadow: 0 2px 10px rgba(0,0,0,.45);
transition: background .12s;
}
.joy.active .joy-knob { background: var(--ok); border-color: #7fe0c2; }
.joy.estop .joy-knob { background: var(--bad); border-color: #f08a82; }
.hint-sm { color: var(--dim); font-size: 11px; text-align: center; margin-top: 6px; }
.speed-row {
display: flex; align-items: center; gap: 6px;
margin-top: 5px;
}
.speed-row .slabel { flex: 1; color: var(--dim); }
.speed-row .sval {
min-width: 42px; text-align: right;
font-variant-numeric: tabular-nums;
}
.sbtn {
flex: none; width: 26px; height: 24px; padding: 0;
font-size: 15px; line-height: 1;
}
/* ============ Khung chia doi ============ */
/* Trai = THE GIOI (tuong duong Gazebo), phai = SLAM (tuong duong RViz).
Hai canvas tuyet doi chong len .canvas-wrap; JS dat chieu rong. */
/* ⚠️ An bang CSS, KHONG bang style="display:none" tren the.
Style inline thang stylesheet, nen quy tac .split ben duoi se khong bao gio
ap duoc va khung phai ĐEN XI -- da mac loi do mot lan. */
/* ⚠️ An/hien HOAN TOAN bang class tren `.canvas-wrap`, KHONG bao gio bang
style="display:none" tren the.
Style inline thang stylesheet, nen quy tac .split se khong ap duoc va khung
phai ĐEN XI -- da mac loi do mot lan voi #mainR.
Bon to hop:
(khong gi) : #main -- 2D mot khung
.three : #main3d -- 3D mot khung
.split : #main | #mainR -- 2D | 2D
.split.three : #main3d | #mainR -- 3D (Gazebo) | 2D SLAM (RViz) */
#mainR, #main3d { display: none; }
.canvas-wrap.three #main { display: none; }
.canvas-wrap.three #main3d { display: block; }
.canvas-wrap.split #main,
.canvas-wrap.split #main3d { width: 50%; }
.canvas-wrap.split #mainR { display: block; position: absolute;
right: 0; top: 0; width: 50%; height: 100%;
border-left: 1px solid #2a3442; }
.pane-label {
position: absolute; top: 6px;
font: 11px/1.4 ui-monospace, monospace;
color: #8fa3bf; background: rgba(18,21,26,.82);
padding: 2px 7px; border-radius: 3px; pointer-events: none;
}
#labL { left: 8px; }
#labR { left: 50%; margin-left: 8px; }

File diff suppressed because one or more lines are too long