845 lines
33 KiB
JavaScript
845 lines
33 KiB
JavaScript
// 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.
|
|
// ⚠️ Tone nay phai khop `PALETTE.world` trong app.js: hai khung cung the
|
|
// hien MOT the gioi, lech tone thi nhin nhu hai noi khac nhau.
|
|
V3D.scene.background = new THREE.Color(0xa9b8c6); // = PALETTE.world.bg
|
|
// 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, 0x93a2b0, 0xa6b3c0);
|
|
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) {
|
|
// ⚠️ CANH DI THEO TAY, va DAU CUA HAI TRUC KHONG GIONG NHAU.
|
|
//
|
|
// Suy luan tay o day rat de sai: phep xoay lam ca VI TRI lan HE TRUC cua
|
|
// camera doi cung luc, va phan he truc moi la phan quyet dinh. Toi da
|
|
// suy sai mot lan va dao ca hai truc, lam hong truc ngang trong khi
|
|
// dang sua truc doc.
|
|
//
|
|
// Dau duoi day duoc CHOT BANG PHEP DO: `test/www/test_orbit_camera.js`
|
|
// chieu mot diem the gioi qua dung phep camera cua v3dRender() roi xem
|
|
// no di ve phia nao. Doi dau o day ma khong chay bai do lai la quay ve
|
|
// dung cho cu.
|
|
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 {
|
|
// Keo canh: phai di theo HUONG NHIN, khong theo truc the gioi. Khong doi
|
|
// he thi o mot goc bat ky, keo sang phai lam canh di cheo.
|
|
//
|
|
// Dau tru: `tx`/`ty` la TAM NHIN. Canh di sang phai nghia la tam nhin
|
|
// di sang TRAI.
|
|
const c = Math.cos(V3D.orbit.az), s = Math.sin(V3D.orbit.az);
|
|
const k = V3D.orbit.dist * 0.0016;
|
|
// ⚠️ Truc DOC phai bu do rut ngan theo goc nhin.
|
|
//
|
|
// Mat san nhin cheo bi rut ngan mot he so sin(el): doi tam nhin 1 m ve
|
|
// phia truoc lam canh dich it hon nhieu so voi 1 m sang ngang. Dung
|
|
// chung mot he so cho ca hai truc lam canh KEO HUT theo chieu doc -- do
|
|
// duoc: ti le do doi 0.27 trong khi ti le keo la 0.63.
|
|
//
|
|
// Chan mau o 0.25 cho goc nhin "canh": o do sin(el) -> 0 va phep bu se
|
|
// no ra vo cuc.
|
|
const kf = k / Math.max(Math.sin(V3D.orbit.el), 0.25);
|
|
V3D.orbit.tx -= dx * s * k + dy * c * kf;
|
|
V3D.orbit.ty -= -dx * c * k + dy * s * kf;
|
|
}
|
|
});
|
|
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.
|
|
// ---------------------------------------------------------------------------
|
|
// Bo truc cho MOT frame tinh, kem nhan ten.
|
|
//
|
|
// Dung tu chinh `shape` ma backend da gui (laser_x/y/z, cam_x/y/z, cam_pitch)
|
|
// nen KHONG phai them gi o phia C++.
|
|
//
|
|
// Vi sao co lop nay: khi PCL khong chong khit scan thi cau hoi luon la "cam
|
|
// bien nao dang o sai cho", va mot khoi hop mau xanh khong tra loi duoc. Ba
|
|
// bo truc dat dung vi tri thi tra loi duoc ngay bang mat.
|
|
function v3dFrameAxes(name, x, y, z, pitch, size) {
|
|
const g = new THREE.Group();
|
|
g.add(new THREE.AxesHelper(size || 0.15));
|
|
// Dung toScene() nhu moi cho khac, khong chep lai phep doi truc: hai ban
|
|
// chep cua cung mot phep doi se lech nhau ngay lan sua dau tien.
|
|
g.position.copy(toScene(x || 0, y || 0, z || 0));
|
|
// Chuc xuong: cung quy uoc voi camG trong v3dBuildRobot.
|
|
if (pitch) g.rotation.z = -pitch;
|
|
g.userData.frameName = name;
|
|
return g;
|
|
}
|
|
|
|
// Ba frame tinh: base_link, laser_link, camera_link.
|
|
function v3dBuildFrames(r) {
|
|
const g = new THREE.Group();
|
|
// base_link o TAM TRUC banh. Ca nhom duoc nang len wheel_radius giong
|
|
// v3dBuildRobot de san nam o y = 0.
|
|
g.position.y = r.wheel_radius;
|
|
g.add(v3dFrameAxes('base_link', 0, 0, 0, 0, 0.25));
|
|
g.add(v3dFrameAxes('laser_link', r.laser_x, r.laser_y, r.laser_z, 0, 0.18));
|
|
g.add(v3dFrameAxes('camera_link', r.cam_x, r.cam_y, r.cam_z,
|
|
r.cam_pitch, 0.18));
|
|
return g;
|
|
}
|
|
|
|
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: 0x1a6ea8 });
|
|
const darkMat = new THREE.MeshLambertMaterial({ color: 0x20262e });
|
|
|
|
// Than: KHOI HOP, dung kich thuoc that tu robot.yaml.
|
|
//
|
|
// Ban truoc ve hinh tru ban kinh `robot_radius` vi robot.yaml chua co chieu
|
|
// cao than. Nhung robot that la mot hop 0.40 x 0.34 x 0.85 m -- hinh tru
|
|
// 0.24 m lam no trong lun va tron, khong nhan ra duoc huong.
|
|
//
|
|
// `robot_radius` van la thu dung cho va cham: mot hinh tron bao ngoai hop.
|
|
// Khong dung kich thuoc hop cho va cham -- lam vay thi phep va cham phu
|
|
// thuoc goc quay, va do la mot lop bug moi.
|
|
const bodyL = r.body_l || r.radius * 1.6;
|
|
const bodyW = r.body_w || r.radius * 1.4;
|
|
const bodyH = r.body_h || r.radius * 1.2;
|
|
const clear = r.clearance || 0.0;
|
|
const body = new THREE.Mesh(
|
|
new THREE.BoxGeometry(bodyL, bodyH, bodyW), bodyMat);
|
|
// `base_link` o tam truc banh; day hop cach SAN dung `clearance`, nen tam
|
|
// hop nam tren base_link mot doan (clearance + bodyH/2 - wheel_radius).
|
|
body.position.set(r.body_off_x || 0, clear + bodyH / 2 - r.wheel_radius, 0);
|
|
g.add(body);
|
|
|
|
// Mui chi huong +X, de nhin mot cai la biet dau la truoc.
|
|
const nose = new THREE.Mesh(
|
|
new THREE.ConeGeometry(bodyW * 0.16, bodyL * 0.22, 16),
|
|
new THREE.MeshLambertMaterial({ color: 0x8ec5ff }));
|
|
nose.rotation.z = -Math.PI / 2;
|
|
nose.position.set((r.body_off_x || 0) + bodyL / 2,
|
|
clear + bodyH * 0.85 - r.wheel_radius, 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.bodyMesh = v3dBuildRobot(r);
|
|
V3D.robotGroup.add(V3D.bodyMesh);
|
|
// Bo truc di CUNG robotGroup nen no bam theo pose -- dung cai can: xem cam
|
|
// bien nam dau khi robot da di chuyen, khong phai o goc toa do.
|
|
V3D.framesMesh = v3dBuildFrames(r);
|
|
V3D.framesMesh.visible = false;
|
|
V3D.robotGroup.add(V3D.framesMesh);
|
|
{
|
|
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);
|
|
// ⚠️ Ve ground truth bang KHUNG DAY, khong phai khoi dac mo.
|
|
//
|
|
// Mot khoi dac CUNG KICH THUOC dat chong len hinh uoc luong lam sai so 4 cm
|
|
// trong nhu HAI con robot: mat doc "hai hinh khac nhau" chu khong doc "mot
|
|
// hinh lech mot chut". Da mat nhieu luot trao doi vi hieu ung do -- sai so
|
|
// that do duoc chi 0.008-0.037 m o 0.7 m/s, va ban do quet ra khop tuong
|
|
// that voi p90 = 5 cm, tuc mot o luoi.
|
|
//
|
|
// Khung day thi lech nho hien ra dung nhu no la: mot vien xanh la mong ben
|
|
// canh hinh dac. Lech LON van nhin thay ngay, va do moi la luc no dang bao
|
|
// dieu gi that.
|
|
V3D.gtGroup.traverse((o) => {
|
|
if (o.material) {
|
|
o.material = o.material.clone();
|
|
o.material.wireframe = true;
|
|
o.material.transparent = true;
|
|
o.material.opacity = 0.85;
|
|
o.material.depthTest = false; // khong bi than robot che khuat
|
|
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: 0xe8edf1, 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),
|
|
0x93a2b0, 0xa6b3c0);
|
|
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;
|
|
}
|
|
|
|
// Dat khung nhin ve mot goc chuan.
|
|
//
|
|
// Ba goc nay la ba cau hoi khac nhau: "mat bang the nao" (tren), "cao thap ra
|
|
// sao" (canh), va "tong the" (cheo). Xoay tay toi dung mot trong ba goc do rat
|
|
// kho, nen chung la nut.
|
|
function v3dSetView(name) {
|
|
if (!V3D.ready) return;
|
|
const o = V3D.orbit;
|
|
if (name === 'top') {
|
|
o.el = 1.45; // gan thien dinh; 1.5708 lam khung nhin suy bien
|
|
o.az = -Math.PI / 2; // +X sang phai, +Y len tren -- nhu khung 2D
|
|
} else if (name === 'side') {
|
|
o.el = 0.06; // sat mat san
|
|
o.az = -Math.PI / 2;
|
|
} else {
|
|
o.el = 0.55;
|
|
o.az = -2.2;
|
|
}
|
|
o.tx = 0; o.ty = 0;
|
|
}
|
|
|
|
// Than robot va bo truc TF: bat/tat doc lap.
|
|
//
|
|
// `body = false, frames = true` cho ra che do "chi TF": huu ich khi can nhin
|
|
// cam bien nam dau ma khong bi khoi hop 0.85 m che mat.
|
|
function v3dSetBodyVisible(on) {
|
|
if (V3D.bodyMesh) V3D.bodyMesh.visible = !!on;
|
|
if (V3D.gtGroup) V3D.gtGroup.visible = !!on;
|
|
}
|
|
|
|
function v3dSetFramesVisible(on) {
|
|
if (V3D.framesMesh) V3D.framesMesh.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);
|
|
}
|