update
This commit is contained in:
@@ -80,7 +80,7 @@ if(VSLAM_BUILD_SIM)
|
||||
vslam_add_test(test_sim_source LIBS vslam_sim vslam_drivers vslam_common)
|
||||
# Doc `.world` cua Gazebo. Fixture rieng trong test/data/world -- KHONG can
|
||||
# bo model 3 GB cua AWS, nen bai kiem nay chay duoc tren may sach.
|
||||
vslam_add_test(test_gazebo_world LIBS vslam_sim vslam_common)
|
||||
vslam_add_test(test_gazebo_world LIBS vslam_sim vslam_drivers vslam_common)
|
||||
if(VSLAM_BUILD_ODOMETRY)
|
||||
# Test TICH HOP: sim -> encoder -> wheel_odom -> EKF, do sai so so voi
|
||||
# ground truth. Day la bai L2 cua repo cu viet lai khong ROS.
|
||||
@@ -206,6 +206,21 @@ if(VSLAM_NODE_EXE AND TARGET vslam_world_export)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/www/test_robot_marker.js)
|
||||
set_tests_properties(www_robot_marker PROPERTIES
|
||||
PASS_REGULAR_EXPRESSION "=> DAT")
|
||||
# Phep bien doi cua khung 2D: xoay + keo canh. Bat bien duoc kiem la "diem
|
||||
# duoi con tro o nguyen duoi con tro sau khi keo", dung o MOI goc xoay.
|
||||
add_test(NAME www_view_transform
|
||||
COMMAND ${VSLAM_NODE_EXE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/www/test_view_transform.js)
|
||||
set_tests_properties(www_view_transform PROPERTIES
|
||||
PASS_REGULAR_EXPRESSION "=> DAT")
|
||||
# Chieu keo chuot trong khung 3D. Suy luan tay o day rat de sai vi phep xoay
|
||||
# doi CA vi tri lan he truc cua camera cung luc -- da sua sai mot lan. Bai
|
||||
# kiem chieu mot diem the gioi qua dung phep camera roi DO xem no di dau.
|
||||
add_test(NAME www_orbit_camera
|
||||
COMMAND ${VSLAM_NODE_EXE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/www/test_orbit_camera.js)
|
||||
set_tests_properties(www_orbit_camera PROPERTIES
|
||||
PASS_REGULAR_EXPRESSION "=> DAT")
|
||||
else()
|
||||
message(STATUS "vslam: khong tim thay `node` -- bo qua bai kiem frontend")
|
||||
endif()
|
||||
|
||||
@@ -269,3 +269,87 @@ TEST(GazeboWorld, MaHoaGhiDeKhongNoiThem) {
|
||||
vslam::EncodeWorldMeshes(wm, &blob);
|
||||
EXPECT_EQ(blob.size(), once);
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// RAYCAST PHAI DUNG O MAT TUONG, KHONG O BIEN O LUOI
|
||||
// ===========================================================================
|
||||
//
|
||||
// ⚠️ DDA tren luoi tra ve khoang cach toi MAT VAO cua o bi chiem dau tien, ma
|
||||
// o do chi duoc danh dau khi tam giac di qua TAM o. Mat vao ay nam lui vao
|
||||
// trong tuong toi mot o day du.
|
||||
//
|
||||
// Do tren the gioi benh vien, khoang cach tu diem quet toi mat tuong NHIN
|
||||
// THAY: p50 = 3.7 cm, p90 = 5.6 cm. MOI tia deu dung som. Nguoi van hanh nhin
|
||||
// thay vanh quet lo lung truoc tuong va tuong la robot bi troi -- trong khi
|
||||
// sai so dinh vi that chi 0.9 cm.
|
||||
//
|
||||
// Loi nay khong lam gi hong theo nghia van hanh: dung so tia, dung nhip,
|
||||
// khong mot ngoai le nao. Chi co hinh hoc moi phat hien duoc.
|
||||
|
||||
#include "vslam/sim_source.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// Hop `box_m_1` trong mini.world: 2.0 x 1.0 x 0.5 m, tam o goc toa do.
|
||||
// Mat x duong o x = +1.0, mat y duong o y = +0.5.
|
||||
std::unique_ptr<vslam::SimSource> OpenMiniSim() {
|
||||
vslam::SimConfig sc;
|
||||
sc.world_path = DataDir() + "/world/mini.world";
|
||||
sc.world_model_paths = {DataDir() + "/world/models"};
|
||||
// Goc toa do nam TRONG hop `box_m_1`, nen phai xuat phat cho khac.
|
||||
sc.start_x = 5.0;
|
||||
sc.start_y = 3.0;
|
||||
auto sim = std::unique_ptr<vslam::SimSource>(new vslam::SimSource(sc));
|
||||
const vslam::StatusResponse st = sim->Open();
|
||||
EXPECT_TRUE(st.ok()) << st.message;
|
||||
return sim;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Bo tri mini.world:
|
||||
// box_m_1 (0, 0) x [-1, 1] y [-0.5, 0.5]
|
||||
// box_cm_1 (5, 0) box_mtx_1 (10, 0) box_zup_1 (15, 0)
|
||||
// box_m_2 (0, 6) quay 90 do: x [-0.5, 0.5] y [5, 7]
|
||||
// Luoi phu x [-2, 17], y [-1.5, 8]. Ban tu ngoai vung do la vo nghia.
|
||||
TEST(GazeboWorld, RaycastDungOMatTuong) {
|
||||
auto sim = OpenMiniSim();
|
||||
|
||||
// Tu (0, 3) ban xuong: cham mat tren cua box_m_1 o y = +0.5 -> 2.500 m.
|
||||
EXPECT_NEAR(sim->RangeForTest(0.0, 3.0, -M_PI_2), 2.500, 0.002);
|
||||
|
||||
// Tu (0, 3) ban len: cham mat duoi cua box_m_2 o y = 5 -> 2.000 m.
|
||||
EXPECT_NEAR(sim->RangeForTest(0.0, 3.0, M_PI_2), 2.000, 0.002);
|
||||
|
||||
// Tu (2.5, 0) ban sang trai: cham mat x = +1.0 -> 1.500 m.
|
||||
EXPECT_NEAR(sim->RangeForTest(2.5, 0.0, M_PI), 1.500, 0.002);
|
||||
}
|
||||
|
||||
// Tia CHEO la phep kiem that su.
|
||||
//
|
||||
// Tia truc chinh co the dung TINH CO: bien o thang hang voi mat tuong khi goc
|
||||
// luoi roi dung cho. Tia cheo cham mat tuong o mot diem khong phai bien o nao,
|
||||
// nen no chi dung khi da that su cat voi tam giac.
|
||||
TEST(GazeboWorld, RaycastCheoCungDungOMatTuong) {
|
||||
auto sim = OpenMiniSim();
|
||||
|
||||
// Tu (3, 3) ngam toi (0, 0.5) -- mot diem GIUA mat tren cua box_m_1.
|
||||
const double dx = 0.0 - 3.0, dy = 0.5 - 3.0;
|
||||
const double want = std::sqrt(dx * dx + dy * dy);
|
||||
EXPECT_NEAR(sim->RangeForTest(3.0, 3.0, std::atan2(dy, dx)), want, 0.003);
|
||||
|
||||
// ⚠️ Dung sai 3 mm o tren la phep kiem: luoi 0.05 m, nen mot ket qua bi
|
||||
// luong tu hoa se lech toi 50 mm. Khong the lot.
|
||||
}
|
||||
|
||||
// Khong co mesh (chay tu `--map`) thi phai giu nguyen duong cu, khong hong.
|
||||
TEST(GazeboWorld, KhongCoMeshThiVanChay) {
|
||||
vslam::SimConfig sc; // khong world_path, khong map_yaml
|
||||
vslam::SimSource sim(sc);
|
||||
ASSERT_TRUE(sim.Open().ok());
|
||||
// The gioi tong hop: co tuong, nen phai do duoc mot cu ly huu han o dau do.
|
||||
const double r = sim.RangeForTest(sim.ground_truth().x, sim.ground_truth().y,
|
||||
0.0);
|
||||
EXPECT_GT(r, 0.0);
|
||||
EXPECT_TRUE(std::isfinite(r) || std::isinf(r));
|
||||
}
|
||||
|
||||
240
test/www/test_orbit_camera.js
Normal file
240
test/www/test_orbit_camera.js
Normal file
@@ -0,0 +1,240 @@
|
||||
// Chuot trong khung 3D: canh phai di THEO tay.
|
||||
//
|
||||
// ================== VI SAO CAN BAI KIEM NAY ==================
|
||||
// Da sua chieu keo mot lan bang cach suy luan, va sai: dao dung truc azimuth
|
||||
// thi dung, nhung dao ca truc elevation thi hong, va phep keo canh thi nguoc
|
||||
// hoan toan. Khong mot loi nao -- canh van ve, chi la no di nguoc tay.
|
||||
//
|
||||
// Nen bai kiem nay khong doc ma nguon ma DO: chieu mot diem the gioi qua dung
|
||||
// phep camera cua `v3dRender()`, keo chuot, roi xem diem do di ve phia nao
|
||||
// tren man hinh.
|
||||
//
|
||||
// Bat bien: keo sang PHAI thi diem di sang PHAI; keo XUONG thi diem di XUONG.
|
||||
// Voi phep KEO CANH con chat hon: diem duoi con tro phai O NGUYEN duoi con
|
||||
// tro, y nhu khung 2D.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
|
||||
// --- THREE gia: chi can du de app3d.js chay den cho gan chuot ---
|
||||
class V3 {
|
||||
constructor(x, y, z) { this.x = x || 0; this.y = y || 0; this.z = z || 0; }
|
||||
set(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }
|
||||
copy(o) { this.x = o.x; this.y = o.y; this.z = o.z; return this; }
|
||||
}
|
||||
const node = () => ({ position: new V3(), rotation: { x: 0, y: 0, z: 0 },
|
||||
userData: {}, visible: true });
|
||||
class Grp {
|
||||
constructor() { Object.assign(this, node()); this.children = []; }
|
||||
add(c) { this.children.push(c); }
|
||||
remove(c) { this.children = this.children.filter((x) => x !== c); }
|
||||
traverse(f) { f(this); this.children.forEach((c) => (c.traverse ? c.traverse(f) : f(c))); }
|
||||
}
|
||||
const leafCls = () => class { constructor(g, m) { Object.assign(this, node());
|
||||
this.geometry = g; this.material = m; } };
|
||||
const matCls = () => class {
|
||||
constructor(o) { Object.assign(this, o); this.color = { set() {}, setHSL() {} }; }
|
||||
clone() { const c = Object.create(Object.getPrototypeOf(this));
|
||||
Object.assign(c, this); c.color = { set() {}, setHSL() {} }; return c; }
|
||||
dispose() {}
|
||||
};
|
||||
global.THREE = {
|
||||
Group: Grp, Mesh: leafCls(), Line: leafCls(), LineLoop: leafCls(),
|
||||
LineSegments: leafCls(), Points: leafCls(), Vector3: V3,
|
||||
MeshLambertMaterial: matCls(), MeshStandardMaterial: matCls(),
|
||||
LineBasicMaterial: matCls(), PointsMaterial: matCls(),
|
||||
CylinderGeometry: class {}, ConeGeometry: class {}, BoxGeometry: class { dispose() {} },
|
||||
PlaneGeometry: class { dispose() {} },
|
||||
GridHelper: class { constructor() { Object.assign(this, node()); } },
|
||||
BufferGeometry: class {
|
||||
constructor() { this.attributes = {}; }
|
||||
setAttribute(n, a) { this.attributes[n] = a; }
|
||||
setFromPoints() { return this; } computeVertexNormals() {} dispose() {}
|
||||
},
|
||||
BufferAttribute: class { constructor(a, n) { this.array = a; this.itemSize = n; } },
|
||||
InstancedMesh: class { constructor() { Object.assign(this, node());
|
||||
this.instanceMatrix = {}; }
|
||||
setMatrixAt() {} dispose() {} },
|
||||
Matrix4: class { compose() {} }, Quaternion: class { setFromAxisAngle() {} },
|
||||
Color: class { constructor() { this.set = () => {}; this.setHSL = () => {}; } },
|
||||
Scene: class { constructor() { Object.assign(this, node()); this.fog = { near: 0, far: 0 }; } },
|
||||
PerspectiveCamera: class { constructor() { Object.assign(this, node());
|
||||
this.lookAt = () => {}; } },
|
||||
WebGLRenderer: class { constructor() { this.shadowMap = {}; }
|
||||
setPixelRatio() {} setSize() {} render() {} },
|
||||
HemisphereLight: class { constructor() { Object.assign(this, node()); } },
|
||||
DirectionalLight: class { constructor() { Object.assign(this, node());
|
||||
this.shadow = { camera: {}, mapSize: {} }; } },
|
||||
AmbientLight: class { constructor() { Object.assign(this, node()); } },
|
||||
Fog: class {}, FogExp2: class {},
|
||||
PCFSoftShadowMap: 1, DoubleSide: 2,
|
||||
};
|
||||
|
||||
// --- canvas + window gia, bat lay bo xu ly chuot ---
|
||||
const H = { win: {}, cv: {} };
|
||||
const canvas = {
|
||||
clientWidth: 900, clientHeight: 600, width: 900, height: 600,
|
||||
addEventListener(ev, fn) { H.cv[ev] = fn; },
|
||||
getContext: () => new Proxy({}, { get: () => () => {} }),
|
||||
};
|
||||
const sandbox = {
|
||||
THREE: global.THREE, console,
|
||||
window: { addEventListener(ev, fn) { H.win[ev] = fn; }, devicePixelRatio: 1 },
|
||||
document: { createElement: () => canvas },
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
vm.runInContext(
|
||||
fs.readFileSync(path.resolve(
|
||||
'/home/quangtrung/projects/vslam_cpp/libs/vslam_web/www/app3d.js'), 'utf8') +
|
||||
'\n;this.__V3D = V3D; this.__bind = v3dBindMouse; this.__setView = v3dSetView;',
|
||||
sandbox);
|
||||
|
||||
const V3D = sandbox.__V3D;
|
||||
V3D.ready = true;
|
||||
V3D.root = new Grp();
|
||||
sandbox.__bind(canvas);
|
||||
|
||||
// --- Chieu mot diem the gioi len man hinh, dung phep camera cua v3dRender ---
|
||||
//
|
||||
// Camera dat o goc cau quanh tam nhin, nhin ve tam, up = +Y. Day la copy
|
||||
// nguyen van cong thuc trong v3dRender() -- neu cong thuc do doi ma o day
|
||||
// khong doi, bai kiem se bao sai va do la dieu MONG MUON: hai noi phai khop.
|
||||
function project(p) {
|
||||
const o = V3D.orbit;
|
||||
const cx = o.tx, cz = o.ty;
|
||||
const cam = {
|
||||
x: cx + o.dist * Math.cos(o.el) * Math.cos(o.az),
|
||||
y: o.dist * Math.sin(o.el),
|
||||
z: cz + o.dist * Math.cos(o.el) * Math.sin(o.az),
|
||||
};
|
||||
const tgt = { x: cx, y: 0.2, z: cz };
|
||||
const sub = (a, b) => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z });
|
||||
const norm = (v) => { const n = Math.hypot(v.x, v.y, v.z);
|
||||
return { x: v.x / n, y: v.y / n, z: v.z / n }; };
|
||||
const cross = (a, b) => ({ x: a.y * b.z - a.z * b.y,
|
||||
y: a.z * b.x - a.x * b.z,
|
||||
z: a.x * b.y - a.y * b.x });
|
||||
const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
|
||||
const fwd = norm(sub(tgt, cam)); // huong nhin
|
||||
const right = norm(cross(fwd, { x: 0, y: 1, z: 0 }));
|
||||
const up = cross(right, fwd);
|
||||
const d = sub(p, cam);
|
||||
const depth = dot(d, fwd);
|
||||
if (depth <= 1e-6) return null; // sau lung camera
|
||||
// Phoi canh: chia cho do sau. He so tieu cu khong doi ket qua ve CHIEU.
|
||||
return { x: dot(d, right) / depth, y: dot(d, up) / depth, depth };
|
||||
}
|
||||
|
||||
const bad = [];
|
||||
const P = { x: 2.0, y: 0.0, z: 1.0 }; // mot diem co dinh trong canh
|
||||
|
||||
// --- TU KIEM phep chieu truoc khi tin no ---
|
||||
//
|
||||
// Mot bai kiem sai co the to cao code dung. Ba tinh huong duoi day co dap an
|
||||
// biet truoc, khong phu thuoc vao app3d.js chut nao.
|
||||
{
|
||||
V3D.orbit.az = -2.2; V3D.orbit.el = 0.55; V3D.orbit.dist = 6.0;
|
||||
V3D.orbit.tx = 0; V3D.orbit.ty = 0;
|
||||
const o = V3D.orbit;
|
||||
const cam = { x: o.dist * Math.cos(o.el) * Math.cos(o.az),
|
||||
y: o.dist * Math.sin(o.el),
|
||||
z: o.dist * Math.cos(o.el) * Math.sin(o.az) };
|
||||
const fwd = { x: -cam.x, y: 0.2 - cam.y, z: -cam.z };
|
||||
const n = Math.hypot(fwd.x, fwd.y, fwd.z);
|
||||
const f = { x: fwd.x / n, y: fwd.y / n, z: fwd.z / n };
|
||||
const rN = Math.hypot(-f.z, 0, f.x);
|
||||
const right = { x: -f.z / rN, y: 0, z: f.x / rN };
|
||||
|
||||
const c0 = project({ x: 0, y: 0.2, z: 0 }); // dung tam nhin
|
||||
const cR = project({ x: right.x, y: 0.2, z: right.z }); // lech sang PHAI 1 m
|
||||
const cU = project({ x: 0, y: 1.2, z: 0 }); // cao hon 1 m
|
||||
const good = Math.abs(c0.x) < 1e-9 && Math.abs(c0.y) < 1e-9 &&
|
||||
cR.x > 0 && cU.y > 0;
|
||||
console.log(` tu kiem: tam=(${c0.x.toFixed(3)}, ${c0.y.toFixed(3)}) ` +
|
||||
`phai.x=${cR.x.toFixed(3)} cao.y=${cU.y.toFixed(3)}` +
|
||||
(good ? '' : ' <-- PHEP CHIEU CUA BAI KIEM SAI'));
|
||||
if (!good) { bad.push('tu kiem phep chieu'); }
|
||||
}
|
||||
|
||||
function drag(btn, dx, dy) {
|
||||
H.cv.mousedown({ clientX: 100, clientY: 100, button: btn, preventDefault() {} });
|
||||
H.win.mousemove({ clientX: 100 + dx, clientY: 100 + dy });
|
||||
H.win.mouseup();
|
||||
}
|
||||
|
||||
function check(label, btn, dx, dy, wantX, wantY) {
|
||||
V3D.orbit.az = -2.2; V3D.orbit.el = 0.55; V3D.orbit.dist = 6.0;
|
||||
V3D.orbit.tx = 0; V3D.orbit.ty = 0;
|
||||
const a = project(P);
|
||||
drag(btn, dx, dy);
|
||||
const b = project(P);
|
||||
if (!a || !b) { bad.push(label + ' (diem ra sau camera)'); return; }
|
||||
const mx = b.x - a.x, my = b.y - a.y;
|
||||
// Truc y cua MAN HINH huong xuong, con `up` cua camera huong len -> dao dau.
|
||||
const sx = mx, sy = -my;
|
||||
// ⚠️ `null` = KHONG XET. Phep xoay lam diem lech tam di theo cung, nen mot
|
||||
// cu keo ngang cung sinh do doi doc -- doi truc kia bang 0 la doi sai.
|
||||
const okx = wantX === null ? true : Math.sign(sx) === wantX;
|
||||
const oky = wantY === null ? true : Math.sign(sy) === wantY;
|
||||
const nm = (v) => (v > 0 ? 'phai/xuong' : v < 0 ? 'trai/len' : 'khong doi');
|
||||
console.log(` ${label.padEnd(34)} diem di ${nm(sx).padEnd(11)} ` +
|
||||
`${nm(sy).padEnd(11)} ${okx && oky ? '' : ' <-- SAI'}`);
|
||||
if (!okx || !oky) bad.push(label);
|
||||
}
|
||||
|
||||
console.log(' --- keo TRAI (xoay) ---');
|
||||
check('keo sang phai -> canh sang phai', 0, 60, 0, +1, null);
|
||||
check('keo sang trai -> canh sang trai', 0, -60, 0, -1, null);
|
||||
check('keo xuong -> canh xuong', 0, 0, 50, null, +1);
|
||||
check('keo len -> canh len', 0, 0, -50, null, -1);
|
||||
|
||||
console.log(' --- keo PHAI (di chuyen canh) ---');
|
||||
check('keo sang phai -> canh sang phai', 2, 60, 0, +1, null);
|
||||
check('keo xuong -> canh xuong', 2, 0, 50, null, +1);
|
||||
|
||||
// ⚠️ Keo canh phai giu DIEM DUOI CON TRO. Chi kiem chieu thoi thi mot phep
|
||||
// keo qua manh hay qua nhe van "dung chieu".
|
||||
// Keo canh: HAI TRUC phai cung ti le.
|
||||
//
|
||||
// Khong doi khoa cung vao con tro -- phep chieu la phoi canh, muon khoa cung
|
||||
// thi phai cat tia voi mat san. Gazebo cung khong khoa cung. Cai PHAI dung la
|
||||
// hai truc cung ti le: keo cheo 40:25 thi canh cung phai di cheo xap xi 40:25,
|
||||
// khong phai 40:11 nhu khi quen bu do rut ngan theo goc nhin.
|
||||
console.log(' --- keo canh: hai truc cung ti le ---');
|
||||
for (const az of [-2.2, 0.0, 1.1]) {
|
||||
V3D.orbit.az = az; V3D.orbit.el = 0.55; V3D.orbit.dist = 6.0;
|
||||
V3D.orbit.tx = 0; V3D.orbit.ty = 0;
|
||||
// ⚠️ Do o DUNG TAM NHIN. Mot diem lech tam bi phoi canh lam meo ti le theo
|
||||
// do sau, va do sau lai doi theo goc nhin -- do la bien so cua PHEP DO, chu
|
||||
// khong phai cua code.
|
||||
const Q = { x: 0, y: 0.2, z: 0 };
|
||||
const a = project(Q);
|
||||
drag(2, 40, 25);
|
||||
const b = project(Q);
|
||||
// Do doi tren man hinh, quy ve pixel bang cung mot he so cho ca hai truc.
|
||||
const errx = (b.x - a.x), erry = -(b.y - a.y);
|
||||
console.log(` az=${az.toFixed(1).padStart(5)} do doi = ` +
|
||||
`(${errx.toFixed(4)}, ${erry.toFixed(4)}) ti le ` +
|
||||
`${(errx === 0 ? 0 : erry / errx).toFixed(3)}`);
|
||||
// Ti le do doi phai khop ti le keo (25/40 = 0.625), va cung dau.
|
||||
const want = 25 / 40;
|
||||
const got = erry / errx;
|
||||
if (!(errx > 0 && erry > 0 && got > want / 1.7 && got < want * 1.7)) {
|
||||
bad.push('keo canh @ az=' + az.toFixed(1));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Nut goc nhin ---
|
||||
console.log(' --- nut goc nhin ---');
|
||||
for (const [name, wantEl] of [['top', 1.45], ['side', 0.06], ['iso', 0.55]]) {
|
||||
V3D.orbit.tx = 9; V3D.orbit.ty = 9;
|
||||
sandbox.__setView(name);
|
||||
const o = V3D.orbit;
|
||||
const ok = Math.abs(o.el - wantEl) < 1e-9 && o.tx === 0 && o.ty === 0;
|
||||
console.log(` ${name.padEnd(6)} el=${o.el.toFixed(2)} az=${o.az.toFixed(2)} ` +
|
||||
`tx=${o.tx} ty=${o.ty}${ok ? '' : ' <-- SAI'}`);
|
||||
if (!ok) bad.push('goc nhin ' + name);
|
||||
}
|
||||
|
||||
console.log(bad.length ? '\n => HONG: ' + bad.join(', ') : '\n => DAT');
|
||||
process.exit(bad.length ? 1 : 0);
|
||||
233
test/www/test_view_transform.js
Normal file
233
test/www/test_view_transform.js
Normal file
@@ -0,0 +1,233 @@
|
||||
// Phep bien doi cua khung 2D: xoay, keo canh, va hinh hop robot.
|
||||
//
|
||||
// ================== VI SAO CAN BAI KIEM NAY ==================
|
||||
// Khung 2D vua co them phep XOAY. Ba thu phai dung cung luc: phep chieu
|
||||
// (`sx`/`sy`), phep keo canh (phai nghich dao dung phep xoay), va hinh robot.
|
||||
//
|
||||
// Sai mot dau se khong gay loi nao: canh van ve, robot van hien, chi la keo
|
||||
// chuot sang phai thi canh di cheo. Da co ba lan lien tiep loi nam o tang
|
||||
// hien thi trong khi build sach va ctest xanh.
|
||||
//
|
||||
// Phep kiem manh nhat la BAT BIEN: diem the gioi nam duoi con tro phai O
|
||||
// NGUYEN duoi con tro sau khi keo. Do la dinh nghia cua "canh di theo tay",
|
||||
// va no dung o MOI goc xoay.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
|
||||
// --- DOM gia: du de app.js chay het pham vi module ---
|
||||
const handlers = { window: {}, el: {} };
|
||||
function mkEl(id) {
|
||||
const h = {};
|
||||
return {
|
||||
id, checked: true, value: '0', max: '2', dataset: {}, style: {}, hidden: false,
|
||||
textContent: '', classList: { add() {}, remove() {}, toggle() {} },
|
||||
clientWidth: 800, clientHeight: 600, width: 800, height: 600,
|
||||
addEventListener(ev, fn) { (handlers.el[id] = handlers.el[id] || {})[ev] = fn; },
|
||||
getContext() {
|
||||
// ⚠️ Ghi LAI moi lenh ve. Mot ngu canh nuot het khong phan biet duoc
|
||||
// "ve dung" voi "khong ve gi" -- ma "khong ve gi" chinh la trieu chung
|
||||
// cua loi da xay ra: hai khung trang tinh trong khi du lieu van chay.
|
||||
const calls = (this.calls = this.calls || {});
|
||||
return new Proxy({}, {
|
||||
get: (_, k) => (...a) => { calls[k] = (calls[k] || 0) + 1; return a[0]; },
|
||||
set: () => true,
|
||||
});
|
||||
},
|
||||
getBoundingClientRect() { return { left: 0, top: 0, width: 800, height: 600 }; },
|
||||
appendChild() {}, removeChild() {}, setAttribute() {}, focus() {},
|
||||
};
|
||||
}
|
||||
const els = {};
|
||||
const doc = {
|
||||
getElementById(id) { return (els[id] = els[id] || mkEl(id)); },
|
||||
querySelectorAll() { return []; },
|
||||
querySelector(sel) { return (els[sel] = els[sel] || mkEl(sel)); },
|
||||
createElement(t) { return mkEl('#' + t); },
|
||||
addEventListener(ev, fn) { handlers.window[ev] = fn; },
|
||||
activeElement: null,
|
||||
body: mkEl('body'),
|
||||
};
|
||||
const sandbox = {
|
||||
document: doc, console,
|
||||
window: { addEventListener(ev, fn) { handlers.window[ev] = fn; },
|
||||
devicePixelRatio: 1, location: { search: '' } },
|
||||
location: { search: '' },
|
||||
requestAnimationFrame() {}, setInterval() {}, setTimeout() {},
|
||||
fetch() { return Promise.resolve({ json: () => Promise.resolve({ code: 0 }) }); },
|
||||
WebSocket: function () { this.send = () => {}; this.readyState = 0; },
|
||||
ImageData: function (w, h) { this.width = w; this.height = h;
|
||||
this.data = new Uint8ClampedArray(w * h * 4); },
|
||||
URLSearchParams: function () { this.get = () => null; },
|
||||
V3D: { ready: false },
|
||||
};
|
||||
sandbox.window.document = doc;
|
||||
for (const k of ['v3dInit', 'v3dSetShape', 'v3dSetPose', 'v3dSetScan', 'v3dSetCloud',
|
||||
'v3dSetWorld', 'v3dSetMap', 'v3dSetPath', 'v3dSetOverlays',
|
||||
'v3dRender', 'v3dSetWorldMeshes', 'v3dSetWorldVisible',
|
||||
'v3dSetView', 'v3dFrustum', 'v3dCliffRings']) {
|
||||
sandbox[k] = () => {};
|
||||
}
|
||||
vm.createContext(sandbox);
|
||||
const src = fs.readFileSync(
|
||||
path.resolve('/home/quangtrung/projects/vslam_cpp/libs/vslam_web/www/app.js'), 'utf8');
|
||||
vm.runInContext(src + '\n;this.__view = view; this.__sx = sx; this.__sy = sy;' +
|
||||
'\n;this.__ver = UI_VERSION; this.__setCv = (c) => { curCv = c; };' +
|
||||
'\n;this.__pal = PALETTE; this.__state = state;' +
|
||||
'\n;this.__draw = draw; this.__rasterize = rasterize;', sandbox);
|
||||
|
||||
const view = sandbox.__view;
|
||||
const sx = sandbox.__sx, sy = sandbox.__sy;
|
||||
// `curCv` chi duoc dat trong drawScene(); dat tay de do phep chieu rieng le.
|
||||
sandbox.__setCv(doc.getElementById('main'));
|
||||
const bad = [];
|
||||
const chk = (label, got, want, tol) => {
|
||||
const ok = Math.abs(got - want) <= (tol === undefined ? 1e-9 : tol);
|
||||
console.log(` ${label.padEnd(40)} ${got.toFixed(4)}${ok ? '' : ' != ' + want.toFixed(4)}`);
|
||||
if (!ok) bad.push(label);
|
||||
};
|
||||
|
||||
// Canvas 800x600, tam o (400, 300).
|
||||
view.x = 0; view.y = 0; view.scale = 50; view.rot = 0;
|
||||
chk('rot=0: goc the gioi o tam man hinh (x)', sx(0, 0), 400);
|
||||
chk('rot=0: goc the gioi o tam man hinh (y)', sy(0, 0), 300);
|
||||
chk('rot=0: (1,0) sang PHAI', sx(1, 0), 450);
|
||||
chk('rot=0: (0,1) LEN TREN', sy(0, 1), 250);
|
||||
|
||||
// Xoay 90 do: truc +X the gioi phai chi LEN TREN man hinh.
|
||||
view.rot = Math.PI / 2;
|
||||
chk('rot=90: (1,0) khong lech ngang', sx(1, 0), 400, 1e-9);
|
||||
chk('rot=90: (1,0) di LEN', sy(1, 0), 250, 1e-9);
|
||||
|
||||
// ⚠️ BAT BIEN: diem duoi con tro phai O NGUYEN duoi con tro sau khi keo.
|
||||
//
|
||||
// Day la dinh nghia cua "canh di theo tay". No phai dung o MOI goc xoay --
|
||||
// va chinh o goc khac 0 thi phep nghich dao sai moi lo ra.
|
||||
const down = handlers.el['main'] && handlers.el['main'].mousedown;
|
||||
const move = handlers.window.mousemove;
|
||||
const up = handlers.window.mouseup;
|
||||
if (!down || !move) {
|
||||
console.log(' khong bat duoc bo xu ly chuot cua khung 2D');
|
||||
bad.push('bo xu ly chuot');
|
||||
} else {
|
||||
for (const rot of [0, 0.7, Math.PI / 2, -1.3]) {
|
||||
view.x = 3; view.y = -2; view.scale = 50; view.rot = rot;
|
||||
// Diem the gioi dang nam duoi con tro tai (500, 250).
|
||||
// Giai nguoc: tu man hinh ve the gioi.
|
||||
const c = Math.cos(rot), s_ = Math.sin(rot);
|
||||
const rx = (500 - 400) / 50, ry = (300 - 250) / 50;
|
||||
const wx = view.x + rx * c + ry * s_;
|
||||
const wy = view.y + -rx * s_ + ry * c;
|
||||
// Kiem phep giai nguoc truoc.
|
||||
if (Math.abs(sx(wx, wy) - 500) > 1e-6 || Math.abs(sy(wx, wy) - 250) > 1e-6) {
|
||||
bad.push('giai nguoc rot=' + rot.toFixed(2));
|
||||
continue;
|
||||
}
|
||||
down({ button: 0, clientX: 500, clientY: 250, preventDefault() {} });
|
||||
move({ clientX: 560, clientY: 215 });
|
||||
up();
|
||||
const nx = sx(wx, wy), ny = sy(wx, wy);
|
||||
const err = Math.hypot(nx - 560, ny - 215);
|
||||
console.log(` keo theo tay @ rot=${rot.toFixed(2).padStart(5)}` +
|
||||
` lech ${err.toFixed(4)} px`);
|
||||
if (err > 1e-6) bad.push('keo @ rot=' + rot.toFixed(2));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Bang mau: hai mau canh nhau phai PHAN BIET DUOC ---
|
||||
//
|
||||
// ⚠️ Day la mot loi that, khong phai gia dinh. Ban truoc dung MOT bang cho ca
|
||||
// hai khung, voi `free` = #ffffff tren `bg` = #f3f6fa. Hai mau cach nhau 12
|
||||
// don vi -- vung DA QUET va vung chua co gi trong y het nhau, nen khong con
|
||||
// biet quet toi dau. Khong loi, khong canh bao: ban do van ve du.
|
||||
//
|
||||
// Cap quan trong nhat la `free` voi `bg`: cai nguoi van hanh can thay la vung
|
||||
// da quet LON DEN DAU, khong phai vi tri tung buc tuong.
|
||||
console.log('\n --- bang mau: khoang cach giua cac mau ---');
|
||||
const pal = sandbox.__pal;
|
||||
function rgb(v) {
|
||||
if (Array.isArray(v)) return v.slice(0, 3);
|
||||
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(v);
|
||||
return m ? [1, 2, 3].map((i) => parseInt(m[i], 16)) : null;
|
||||
}
|
||||
// Khoang cach co trong so theo do nhay cua mat (xap xi Rec. 601).
|
||||
function dist(a, b) {
|
||||
const A = rgb(a), B = rgb(b);
|
||||
const w = [0.30, 0.59, 0.11];
|
||||
let d = 0;
|
||||
for (let i = 0; i < 3; ++i) d += w[i] * (A[i] - B[i]) * (A[i] - B[i]);
|
||||
return Math.sqrt(d);
|
||||
}
|
||||
const MIN_GAP = 40;
|
||||
for (const name of ['world', 'slam']) {
|
||||
const P = pal[name];
|
||||
for (const [x, y] of [['free', 'bg'], ['occupied', 'free'], ['occupied', 'bg']]) {
|
||||
const d = dist(P[x], P[y]);
|
||||
const ok = d >= MIN_GAP;
|
||||
console.log(` ${name}: ${(x + ' vs ' + y).padEnd(17)} ${d.toFixed(1).padStart(6)}` +
|
||||
(ok ? '' : ` < ${MIN_GAP} <-- KHONG PHAN BIET DUOC`));
|
||||
if (!ok) bad.push(`${name}.${x} vs ${y}`);
|
||||
}
|
||||
}
|
||||
// Hai khung phai KHAC tone: cung tone thi khong biet dang nhin khung nao.
|
||||
const dpane = dist(pal.world.bg, pal.slam.bg);
|
||||
console.log(` nen hai khung khac nhau ${dpane.toFixed(1).padStart(6)}` +
|
||||
(dpane >= 60 ? '' : ' <-- QUA GIONG'));
|
||||
if (dpane < 60) bad.push('hai khung cung tone');
|
||||
|
||||
// --- CHAY THAT duong ve ---
|
||||
//
|
||||
// ⚠️ Bai kiem nay ton tai vi mot loi that: `drawRobot()` doc `pal.nose` nhung
|
||||
// khong co tham so `pal`. ReferenceError ngay lan ve dau, va vi
|
||||
// `requestAnimationFrame(draw)` nam o CUOI draw(), vong ve chet vinh vien.
|
||||
// Ca hai khung trang tinh trong khi thanh ben van cap nhat binh thuong --
|
||||
// WebSocket chay o duong khac.
|
||||
//
|
||||
// Cac bai kiem truoc do khong bat duoc vi chung khong lan nao GOI draw().
|
||||
console.log('\n --- chay that duong ve ---');
|
||||
{
|
||||
const st = sandbox.__state;
|
||||
const grid = { res: 0.05, w: 40, h: 30, ox: -1, oy: -1,
|
||||
cells: new Int8Array(40 * 30) };
|
||||
for (let i = 0; i < grid.cells.length; ++i) {
|
||||
grid.cells[i] = i % 7 === 0 ? 100 : (i % 3 === 0 ? -1 : 0);
|
||||
}
|
||||
st.pose = { x: 0.5, y: 0.5, yaw: 0.3 };
|
||||
st.gt = { x: 0.52, y: 0.5, yaw: 0.3, err: 0.02 };
|
||||
st.robot = { radius: 0.24, wheel_radius: 0.075, wheel_sep: 0.36,
|
||||
laser_x: 0.24, laser_y: 0, laser_z: 0.125,
|
||||
body_l: 0.40, body_w: 0.34, body_h: 0.85, body_off_x: -0.06,
|
||||
clearance: 0.04 };
|
||||
st.scan = new Float32Array([1.0, 0.0, 0.0, 1.0, -1.0, 0.0]);
|
||||
st.path = new Float32Array([0, 0, 0.5, 0.5, 1.0, 0.4]);
|
||||
st.worldMap = grid;
|
||||
st.worldMapImage = sandbox.__rasterize(grid, sandbox.__pal.world);
|
||||
st.map = grid;
|
||||
st.mapImage = sandbox.__rasterize(grid, sandbox.__pal.slam);
|
||||
st.slamMode = 'mapping';
|
||||
|
||||
const main = doc.getElementById('main');
|
||||
const mainR = doc.getElementById('mainR');
|
||||
// ⚠️ XOA KHOA, dung thay object: Proxy trong getContext() da giu tham chieu
|
||||
// toi object cu, nen gan mot object moi se cat mat duong ghi nhan.
|
||||
for (const el of [main, mainR]) {
|
||||
el.calls = el.calls || {};
|
||||
for (const k of Object.keys(el.calls)) delete el.calls[k];
|
||||
}
|
||||
|
||||
let threw = null;
|
||||
try { sandbox.__draw(); } catch (e) { threw = e; }
|
||||
console.log(' goi draw() ' +
|
||||
(threw ? 'NEM: ' + threw.message : 'khong nem'));
|
||||
if (threw) bad.push('draw() nem ngoai le');
|
||||
|
||||
// Dem NOI DUNG: draw() co that su ve gi khong.
|
||||
const n = (el) => Object.values(el.calls || {}).reduce((a, b) => a + b, 0);
|
||||
console.log(` lenh ve tren khung trai ${n(main)}`);
|
||||
if (n(main) < 5) bad.push('khung trai khong duoc ve');
|
||||
if (!(main.calls && main.calls.drawImage)) bad.push('ban do khong duoc ve');
|
||||
}
|
||||
|
||||
console.log('\n UI_VERSION = ' + sandbox.__ver);
|
||||
console.log(bad.length ? '\n => HONG: ' + bad.join(', ') : '\n => DAT');
|
||||
process.exit(bad.length ? 1 : 0);
|
||||
Reference in New Issue
Block a user