upload
This commit is contained in:
72
libs/vslam_web/CMakeLists.txt
Normal file
72
libs/vslam_web/CMakeLists.txt
Normal file
@@ -0,0 +1,72 @@
|
||||
# Web UI mot trang thay RViz.
|
||||
#
|
||||
# Dep ngoai DUY NHAT them vao: Boost. Va Beast la header-only nen chi phai
|
||||
# link Boost::system. Day la ly do chon Beast thay vi cai libwebsockets hay
|
||||
# cpp-httplib: ca hai deu khong co san tren may nao trong hai may dich.
|
||||
|
||||
find_package(Boost REQUIRED COMPONENTS system)
|
||||
|
||||
# Nhung asset vao .so: Jetson ngoai hien truong phuc vu duoc UI ke ca khi
|
||||
# /var/lib chua duoc .deb dien, va khong bao gio lech phien ban .so <-> UI.
|
||||
vslam_embed_assets(vslam_web VSLAM_WEB_ASSETS_SRC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/www
|
||||
index.html
|
||||
app.js
|
||||
app3d.js
|
||||
style.css
|
||||
# three.js r160 UMD, vendor vao repo CO Y: robot ngoai hien truong khong
|
||||
# co internet, nen dung CDN la cach chac chan de UI trang tram.
|
||||
#
|
||||
# 654 KB -- lon hon toan bo UI con lai 20 lan. Doi lai la mot trinh ve 3D
|
||||
# da duoc kiem chung, thay vi mot ban WebGL tu viet phai tu go loi trong
|
||||
# mot san pham co lop an toan.
|
||||
vendor/three.min.js)
|
||||
|
||||
vslam_add_library(vslam_web
|
||||
PUBLIC_HDRS
|
||||
web_server.h
|
||||
web_config.h
|
||||
web_snapshot.h
|
||||
binary_codec.h
|
||||
rle.h
|
||||
PUBLIC_DEPS
|
||||
vslam_common
|
||||
FIND_DEPS
|
||||
vslam_common
|
||||
)
|
||||
|
||||
# File sinh khong nam trong src/ nen GLOB cua vslam_add_library() khong thay.
|
||||
target_sources(vslam_web PRIVATE ${VSLAM_WEB_ASSETS_SRC})
|
||||
|
||||
# Bien dich file asset KHONG kem debug info.
|
||||
#
|
||||
# Day la du lieu MAY SINH: mot mang `const unsigned char[]` 3.5 MB. Khong ai
|
||||
# dat breakpoint vao no, va DWARF cho no la lang phi thuan tuy. Do duoc:
|
||||
# `.o` con 726 KB thay vi vai chuc MB.
|
||||
#
|
||||
# ⚠️ Dieu nay KHONG lam .so nho di nhieu. `libvslam_web.so` la ~25 MB o ban
|
||||
# RelWithDebInfo, va gan het den tu `web_server.cc.o` (41.9 MB) -- debug info
|
||||
# cua Boost.Beast/Asio, co TU TRUOC va khong lien quan asset. Sau `strip` thi
|
||||
# .so con ~2 MB. three.js chi them ~650 KB vao `.rodata`.
|
||||
set_source_files_properties(${VSLAM_WEB_ASSETS_SRC} PROPERTIES
|
||||
COMPILE_OPTIONS "-g0")
|
||||
|
||||
target_link_libraries(vslam_web PRIVATE Boost::system)
|
||||
target_include_directories(vslam_web SYSTEM PRIVATE ${Boost_INCLUDE_DIRS})
|
||||
|
||||
# Beast/Asio sinh rat nhieu canh bao trong header cua chinh no tren Boost 1.71
|
||||
# + GCC 9. Khong tat -Wall cua minh, chi danh dau header cua Boost la SYSTEM
|
||||
# (o tren) de canh bao cua ho khong lan vao canh bao cua minh.
|
||||
#
|
||||
# TUYET DOI KHONG dat BOOST_BEAST_USE_STD_STRING_VIEW hay
|
||||
# BOOST_ASIO_NO_DEPRECATED o day.
|
||||
#
|
||||
# Chung doi DINH NGHIA cua cac kieu va ham inline cua Beast/Asio. Neu lib nay
|
||||
# compile voi chung con mot TU khac (vd mot test cung include Beast) thi
|
||||
# khong, linker se gop cac ham inline trung ten va chon MOT ban tuy y -- vi
|
||||
# pham ODR. Trieu chung da gap: client Beast chay dung khi ban vao server
|
||||
# ngoai process, nhung cung client do trong cung process voi server thi nem
|
||||
# std::length_error "field value too large" ngay o request dau tien.
|
||||
#
|
||||
# Neu that su can mot co nhu vay thi no phai la PUBLIC de lan sang moi
|
||||
# consumer, khong bao gio PRIVATE.
|
||||
95
libs/vslam_web/include/vslam/binary_codec.h
Normal file
95
libs/vslam_web/include/vslam/binary_codec.h
Normal file
@@ -0,0 +1,95 @@
|
||||
#ifndef VSLAM_BINARY_CODEC_H
|
||||
#define VSLAM_BINARY_CODEC_H
|
||||
|
||||
// Ma hoa nhi phan cho khung WebSocket. Khung text (JSON) lo o json_writer.h.
|
||||
//
|
||||
// Header 16 byte, little-endian:
|
||||
// off size truong
|
||||
// 0 4 magic 'V','S','L','1'
|
||||
// 4 1 type
|
||||
// 5 1 version = 1
|
||||
// 6 2 flags
|
||||
// 8 8 stamp_ns (uint64, unix ns)
|
||||
// 16 ... payload
|
||||
//
|
||||
// Vi sao nhi phan chu khong JSON cho phan nay: mot sweep 1081 tia dang JSON
|
||||
// la ~15 kB va phai parse 1081 so; dang nhi phan la 2198 byte va doc thang
|
||||
// vao Uint16Array. O 10 Hz thi khac biet la that.
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
enum class BinaryType : uint8_t {
|
||||
kScan = 1,
|
||||
kCloud = 2,
|
||||
kMapFull = 3,
|
||||
kMapPatch = 4,
|
||||
kPath = 5,
|
||||
// Ban do THE GIOI THAT cua bo mo phong -- tuong duong khung nhin Gazebo.
|
||||
//
|
||||
// Tach han khoi kMapFull (ban do SLAM DUNG): hai thu do tra loi hai cau hoi
|
||||
// khac nhau. Ban do the gioi de LAI cho chuan; ban do SLAM de biet phien
|
||||
// quet dang ra sao. Gop lam mot la mat kha nang doi chieu -- ma doi chieu
|
||||
// chinh la ly do nguoi ta mo ca Gazebo lan RViz.
|
||||
//
|
||||
// TINH: trong mo phong no khong bao gio doi, nen chi gui MOT lan cho moi
|
||||
// client.
|
||||
kWorldMap = 6,
|
||||
};
|
||||
|
||||
constexpr size_t kBinaryHeaderSize = 16;
|
||||
constexpr uint8_t kBinaryVersion = 1;
|
||||
|
||||
// Gia tri canh bien cho tia laser, khop ba ngu nghia o vslam_common.h.
|
||||
// Doc ky: ba thu nay KHAC NHAU va lan lon chung lam robot dung im hoac dam
|
||||
// vao tuong.
|
||||
constexpr uint16_t kRangeNaN = 0xFFFF; // khong do duoc (duoi range_min)
|
||||
constexpr uint16_t kRangeInf = 0xFFFE; // khong co phan xa (vuot range_max)
|
||||
constexpr uint16_t kRangeBlanked = 0xFFFD; // bi sector mask cat (than robot)
|
||||
constexpr uint16_t kRangeMaxValid = 0xFFFC; // 65.532 m -- qua du cho 40 m
|
||||
|
||||
// Tat ca deu NOI THEM vao `out`, khong xoa truoc. Cho phep gom nhieu khung.
|
||||
void EncodeScan(const LaserScan& scan, UnixTime stamp, std::string* out);
|
||||
|
||||
// Giam mau xuong `max_points` bang cach lay buoc deu, roi luong tu hoa theo
|
||||
// `quant_m`. Bo diem NaN.
|
||||
void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points,
|
||||
float quant_m, std::string* out);
|
||||
|
||||
// RLE hang-chinh. Xem rle.h.
|
||||
// `type` cho phep dung chung bo ma hoa cho ban do SLAM (kMapFull) va ban do
|
||||
// THE GIOI cua bo mo phong (kWorldMap): khung giong het nhau, chi khac y
|
||||
// nghia. Mot bo ma hoa thu hai se la hai cho de lech dinh dang.
|
||||
void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
|
||||
BinaryType type = BinaryType::kMapFull);
|
||||
|
||||
// Chi vung bao (bbox) cac o doi so voi `prev`. Tra false neu kich thuoc hai
|
||||
// map khac nhau (khi do phai gui MAP_FULL) hoac khong co o nao doi.
|
||||
bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev,
|
||||
UnixTime stamp, std::string* out);
|
||||
|
||||
// Thua hoa: chi giu diem cach diem truoc > min_step_m.
|
||||
void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m,
|
||||
std::string* out);
|
||||
|
||||
// --- Giai ma, chi dung cho test round-trip --------------------------------
|
||||
|
||||
struct BinaryHeader {
|
||||
BinaryType type = BinaryType::kScan;
|
||||
uint8_t version = 0;
|
||||
uint16_t flags = 0;
|
||||
uint64_t stamp_ns = 0;
|
||||
};
|
||||
|
||||
bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out);
|
||||
bool DecodeScan(const std::string& buf, LaserScan* out);
|
||||
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_BINARY_CODEC_H
|
||||
38
libs/vslam_web/include/vslam/rle.h
Normal file
38
libs/vslam_web/include/vslam/rle.h
Normal file
@@ -0,0 +1,38 @@
|
||||
#ifndef VSLAM_RLE_H
|
||||
#define VSLAM_RLE_H
|
||||
|
||||
// Ma hoa do dai loat cho occupancy grid.
|
||||
//
|
||||
// Moi run la {u16 count, i8 value} = 3 byte, hang-chinh.
|
||||
// `count` la u16 nen run > 65535 phai TACH -- de quen cho nay la bug im lang
|
||||
// tren ban do lon.
|
||||
//
|
||||
// Do tren du lieu that (tools/probe_rtabmap):
|
||||
// map_house.db 323x356 -> 5705 run, 17 kB (6.7x)
|
||||
// map_hospital.db 526x1162 -> 21242 run, 62 kB (9.6x)
|
||||
//
|
||||
// Luu y: ban do trong nha o day chi 16-42% la o "chua biet", KHONG phai >90%
|
||||
// nhu uoc luong ban dau. Ti le nen thuc te vi vay thap hon du kien, nhung
|
||||
// 62 kB cho ban do lon nhat van du nho de gui mot lan luc ket noi.
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Noi them vao `out`. Tra ve so run da ghi.
|
||||
size_t RleEncode(const std::vector<int8_t>& data, std::string* out);
|
||||
|
||||
// Doc `count` run tu `buf` bat dau tu `offset`, ghi vao `out`.
|
||||
// Tra false neu du lieu cut hoac kich thuoc khong khop `expected_size`.
|
||||
bool RleDecode(const std::string& buf, size_t offset, size_t run_count,
|
||||
size_t expected_size, std::vector<int8_t>* out);
|
||||
|
||||
// So byte can de ma hoa `data` (= so run * 3). Dung de quyet dinh gui
|
||||
// MAP_FULL hay MAP_PATCH ma khong phai ma hoa hai lan.
|
||||
size_t RleEncodedSize(const std::vector<int8_t>& data);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_RLE_H
|
||||
51
libs/vslam_web/include/vslam/web_config.h
Normal file
51
libs/vslam_web/include/vslam/web_config.h
Normal file
@@ -0,0 +1,51 @@
|
||||
#ifndef VSLAM_WEB_CONFIG_H
|
||||
#define VSLAM_WEB_CONFIG_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace vslam {
|
||||
|
||||
struct WebConfig {
|
||||
// --- Mang -------------------------------------------------------------
|
||||
std::string bind_address = "0.0.0.0";
|
||||
uint16_t port = 8080;
|
||||
int io_threads = 1; // 1 la du: moi viec nang deu o luong khac
|
||||
|
||||
// --- Bao mat ----------------------------------------------------------
|
||||
// Neu dat: moi POST /api/* can header X-Auth-Token, WS upgrade can ?token=
|
||||
// Neu bo trong: log WARN to luc khoi dong.
|
||||
//
|
||||
// BAT DOI XUNG CO Y (xem web_server.cc):
|
||||
// BAT e-stop -> luon duoc phep, khong can token (fail-safe)
|
||||
// GO e-stop -> BAT BUOC co token
|
||||
// reset bumper -> BAT BUOC co token
|
||||
// Mot endpoint e-stop khong xac thuc tren WiFi LAN nghia la bat ky ai trong
|
||||
// mang deu e-stop duoc; nhung te hon nhieu la GO duoc e-stop cua nguoi khac.
|
||||
std::string auth_token;
|
||||
|
||||
// --- Tan so gui -------------------------------------------------------
|
||||
double state_hz = 10.0; // JSON: pose, safety, slam, health
|
||||
double scan_hz = 10.0; // giam mau tu 25 Hz cua LiDAR
|
||||
double cloud_hz = 2.0;
|
||||
double path_hz = 1.0;
|
||||
// MAP khong co tan so: chi gui khi map_version doi.
|
||||
|
||||
// --- Giam bang thong --------------------------------------------------
|
||||
uint32_t cloud_max_points = 4000; // voxel-stride truoc khi ma hoa
|
||||
float cloud_quant_m = 0.01f; // luong tu hoa i16 -> dai +-327 m
|
||||
double path_min_step_m = 0.1; // thua hoa quy dao
|
||||
|
||||
// Hang doi gui moi phien. Day thi drop khung CU NHAT khong phai MAP.
|
||||
// MAP khong bao gio bi drop -- thay vao do bat co map_pending.
|
||||
size_t max_queued_frames = 4;
|
||||
|
||||
// --- Asset ------------------------------------------------------------
|
||||
// Rong = dung asset nhung trong binary (mac dinh, va la cach .deb chay).
|
||||
// Co gia tri = doc tu dia, che do dev: sua CSS khong phai build lai.
|
||||
std::string asset_dir;
|
||||
};
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_WEB_CONFIG_H
|
||||
95
libs/vslam_web/include/vslam/web_server.h
Normal file
95
libs/vslam_web/include/vslam/web_server.h
Normal file
@@ -0,0 +1,95 @@
|
||||
#ifndef VSLAM_WEB_SERVER_H
|
||||
#define VSLAM_WEB_SERVER_H
|
||||
|
||||
// Web UI mot trang thay RViz. HTTP + WebSocket tren Boost.Beast.
|
||||
//
|
||||
// KIEN TRUC:
|
||||
// * io_context chay tren `io_threads` luong (mac dinh 1 -- moi viec nang
|
||||
// nam o luong khac).
|
||||
// * Publish() goi tu luong web_tx o 10 Hz, KHONG BAO GIO CHAN: no serialize
|
||||
// roi asio::post sang strand cua tung phien.
|
||||
// * Luong web KHONG BAO GIO sua state cua estimator. Moi POST /api/* di qua
|
||||
// CommandHandler -> hang doi lenh -> luong so huu tai nguyen drain.
|
||||
//
|
||||
// GIAO THUC: mot WebSocket /ws, hai loai khung.
|
||||
// Text = JSON, du lieu tan so thap, nguoi doc duoc.
|
||||
// Binary = scan / cloud / map / path, header 16 byte (xem binary_codec.h).
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "vslam/web_config.h"
|
||||
#include "vslam/web_snapshot.h"
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Trang thai dung chung cua server. Dinh nghia trong web_server.cc.
|
||||
//
|
||||
// KHONG lam struct long trong WebServer: cac lop phien (HttpSession,
|
||||
// WsSession) o file .cc phai truy cap duoc, ma mot kieu long private thi ho
|
||||
// khong goi ten duoc. Day la cung lop loi da gap o ConfigNode::Impl.
|
||||
class WebServerImpl;
|
||||
|
||||
class WebServer {
|
||||
public:
|
||||
// Xu ly lenh tu POST /api/<cmd>. `json_args` la body tho (co the rong).
|
||||
// Duoc goi TREN LUONG IO -- phai tra ve ngay, khong duoc chan. Cach dung
|
||||
// dung la day vao hang doi roi tra Ok.
|
||||
using CommandHandler =
|
||||
std::function<StatusResponse(const std::string& cmd, const std::string& json_args)>;
|
||||
|
||||
// Teleop tu joypad cam ung, gia tri chuan hoa [-1, 1] o 20 Hz.
|
||||
// TOAN BO shaping (ramp gia toc, deadman) lam o C++ trong teleop_shaper,
|
||||
// KHONG o JS: khong bao gio tin browser ve dinh dang chuyen dong, vi WS co
|
||||
// the lag hoac mat ket noi giua chung.
|
||||
using TeleopHandler = std::function<void(double vx_norm, double wz_norm)>;
|
||||
|
||||
WebServer(WebConfig cfg, CommandHandler on_command, TeleopHandler on_teleop);
|
||||
~WebServer();
|
||||
|
||||
WebServer(const WebServer&) = delete;
|
||||
WebServer& operator=(const WebServer&) = delete;
|
||||
|
||||
StatusResponse Start();
|
||||
void Stop();
|
||||
|
||||
// Khong chan. An toan goi tu bat ky luong nao.
|
||||
void Publish(const WebSnapshot& snap);
|
||||
|
||||
// Khoi hinh hoc 3D cua the gioi, phuc vu tai `GET /api/world.bin`.
|
||||
//
|
||||
// Dat MOT lan luc khoi dong roi thoi -- the gioi khong doi trong mot phien.
|
||||
// Trinh duyet tai no mot lan de dung do dac THAT thay vi khoi hop dung tu
|
||||
// luoi chiem dung. Rong = khong co, trinh duyet quay ve khoi hop.
|
||||
void SetWorldMesh(std::string blob);
|
||||
|
||||
size_t client_count() const;
|
||||
|
||||
// Cong thuc su dang nghe. Khac cfg.port khi cau hinh port=0 (test).
|
||||
uint16_t port() const;
|
||||
|
||||
struct Stats {
|
||||
uint64_t connections_total = 0;
|
||||
uint64_t frames_sent = 0;
|
||||
uint64_t frames_dropped = 0; // hang doi phien day
|
||||
uint64_t bytes_sent = 0;
|
||||
uint64_t commands_handled = 0;
|
||||
uint64_t auth_failures = 0;
|
||||
};
|
||||
Stats stats() const;
|
||||
|
||||
private:
|
||||
void DoAccept();
|
||||
|
||||
// shared_ptr chu khong unique_ptr: moi phien HTTP/WS giu mot tham chieu toi
|
||||
// trang thai nay va co the song lau hon loi goi Stop() mot chut (async
|
||||
// handler dang bay). unique_ptr o day la use-after-free luc tat may.
|
||||
std::shared_ptr<WebServerImpl> impl_;
|
||||
};
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_WEB_SERVER_H
|
||||
142
libs/vslam_web/include/vslam/web_snapshot.h
Normal file
142
libs/vslam_web/include/vslam/web_snapshot.h
Normal file
@@ -0,0 +1,142 @@
|
||||
#ifndef VSLAM_WEB_SNAPSHOT_H
|
||||
#define VSLAM_WEB_SNAPSHOT_H
|
||||
|
||||
// Anh chup trang thai he thong tai mot thoi diem, do luong web_tx dung tu
|
||||
// Channel::Latest() cua tung kenh roi day sang WebServer::Publish().
|
||||
//
|
||||
// Moi truong du lieu lon la shared_ptr<const T>: khong copy cloud/scan/map.
|
||||
// Neu khong co client nao ket noi thi web_tx khong serialize gi ca -- kiem
|
||||
// bang WebServer::client_count() TRUOC khi dung Snapshot.
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/stats.h"
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
struct SafetySnapshot {
|
||||
std::string state = "OK"; // ten trang thai FSM
|
||||
std::string detail;
|
||||
double min_front = 0.0; // met; INFINITY neu khong do duoc
|
||||
int front_rays = 0; // tong so tia trong quat truoc
|
||||
int front_blanked = 0; // tia bi sector mask cat (sentinel range_max+1)
|
||||
int front_usable = 0; // tia thuc su dung duoc
|
||||
bool estop = false;
|
||||
bool bumper_latched = false;
|
||||
bool cliff = false;
|
||||
};
|
||||
|
||||
struct SlamSnapshot {
|
||||
std::string mode = "idle"; // mapping | localization | update_map | idle
|
||||
bool localized = false;
|
||||
double score = 0.0;
|
||||
int loop_closure_id = 0;
|
||||
uint32_t map_version = 0;
|
||||
double process_ms = 0.0;
|
||||
};
|
||||
|
||||
struct TeleopSnapshot {
|
||||
double linear_speed = 0.0; // scale hien tai, chinh duoc luc chay
|
||||
double angular_speed = 0.0;
|
||||
double max_linear_speed = 0.0;
|
||||
double max_angular_speed = 0.0;
|
||||
};
|
||||
|
||||
struct HealthSnapshot {
|
||||
double lidar_hz = 0.0;
|
||||
double camera_hz = 0.0;
|
||||
double imu_hz = 0.0;
|
||||
double ekf_hz = 0.0;
|
||||
double clock_skew = 1.0; // he so skew cua ClockSync (1.0 = khop)
|
||||
double cpu_pct = 0.0;
|
||||
double rss_mb = 0.0;
|
||||
// Ten kenh -> so ban tin bi drop. Day la thu queue cua ROS khong cho biet.
|
||||
std::vector<std::pair<std::string, uint64_t>> drops;
|
||||
};
|
||||
|
||||
// Hinh hoc robot cho trinh ve 3D, lay tu `robot.yaml` qua `RobotModel`.
|
||||
//
|
||||
// ⚠️ TRINH DUYET KHONG DUOC TU DOAN KICH THUOC. Truoc khi co khoi nay, app.js
|
||||
// hardcode `L = 0.30, W = 0.17` -- khong khop voi bat ky so nao trong
|
||||
// robot.yaml (ban kinh that la 0.24). Do la dung lop bug "hai cho phai giu
|
||||
// dong bo" ma `RobotModel` sinh ra de xoa, chi la no da tron sang JavaScript.
|
||||
//
|
||||
// Gui moi khung: ~120 byte, khong dang ke so voi ngan sach 120 kB/s. Doi lai
|
||||
// UI khong can bat tay rieng va khong bao gio hien sai kich thuoc sau khi
|
||||
// nguoi dung sua robot.yaml.
|
||||
struct RobotShape {
|
||||
bool valid = false;
|
||||
|
||||
double radius = 0.24; // ban kinh bao than, cho footprint
|
||||
double wheel_radius = 0.075;
|
||||
double wheel_separation = 0.36;
|
||||
double body_half_width = 0.17;
|
||||
|
||||
// Vi tri cam bien trong base_link (met). z do tu TAM TRUC banh, khong tu
|
||||
// san -- trinh ve tu cong wheel_radius khi can toa do so voi san.
|
||||
double laser_x = 0.24, laser_y = 0.0, laser_z = 0.125;
|
||||
double camera_x = 0.19, camera_y = 0.0, camera_z = 0.725;
|
||||
double camera_pitch = 0.2618; // rad, DUONG la chuc XUONG
|
||||
|
||||
// Goc mo cua camera depth, de ve frustum. Khong doc duoc tu robot.yaml --
|
||||
// day la thong so ONG KINH, lay tu CameraInfo khi co, khong thi mac dinh
|
||||
// theo D410 (69 do ngang).
|
||||
double camera_hfov = 1.204; // rad
|
||||
double camera_vfov = 0.733;
|
||||
|
||||
// Cua so cliff_detect, de ve vung mu len san. Duoi `cliff_min` camera
|
||||
// KHONG THAY GI -- do la vung hinh hoc, khong phai lua chon.
|
||||
double cliff_min = 1.10;
|
||||
double cliff_max = 2.50;
|
||||
};
|
||||
|
||||
struct WebSnapshot {
|
||||
UnixTime stamp;
|
||||
|
||||
RobotShape robot;
|
||||
|
||||
Pose2D pose_map; // pose trong frame map
|
||||
Pose2D pose_odom;
|
||||
double vx = 0.0;
|
||||
double vyaw = 0.0;
|
||||
double slip_metric = 0.0;
|
||||
|
||||
double roll = 0.0; // DO tu IMU, khong uoc luong
|
||||
double pitch = 0.0;
|
||||
bool accel_ok = true;
|
||||
|
||||
// ============ GROUND TRUTH ============
|
||||
// CHI co khi chay mo phong. Day la tuong duong cua /ground_truth/odom trong
|
||||
// repo cu, noi ghi ro "khong estimator nao duoc subscribe".
|
||||
//
|
||||
// No len web vi do la cach DUY NHAT nhin thay drift. RViz ve duoc ca pose
|
||||
// uoc luong lan ground truth canh nhau; khong co no thi mot ban do dep va
|
||||
// mot ban do SAI trong y het nhau.
|
||||
//
|
||||
// ⚠️ KHONG stage nao duoc doc gia tri nay. No di thang tu nguon len web.
|
||||
bool have_ground_truth = false;
|
||||
Pose2D ground_truth;
|
||||
double gt_roll = 0.0; // nghieng THAT, de doi chung gravity_align
|
||||
double gt_pitch = 0.0;
|
||||
|
||||
SafetySnapshot safety;
|
||||
SlamSnapshot slam;
|
||||
HealthSnapshot health;
|
||||
TeleopSnapshot teleop;
|
||||
|
||||
LaserScanPtr scan;
|
||||
PointCloudXYZPtr cloud;
|
||||
OccupancyGridPtr map; // ban do SLAM dung
|
||||
// Ban do THE GIOI cua bo mo phong (khung nhin "Gazebo"). Null khi chay
|
||||
// that -- luc do khong co su that nao de doi chieu.
|
||||
OccupancyGridPtr world_map;
|
||||
std::vector<Pose2D> trajectory;
|
||||
};
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_WEB_SNAPSHOT_H
|
||||
330
libs/vslam_web/src/binary_codec.cc
Normal file
330
libs/vslam_web/src/binary_codec.cc
Normal file
@@ -0,0 +1,330 @@
|
||||
#include "vslam/binary_codec.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
|
||||
#include "vslam/rle.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
void PutU8(std::string* out, uint8_t v) { out->push_back(static_cast<char>(v)); }
|
||||
|
||||
void PutU16(std::string* out, uint16_t v) {
|
||||
out->push_back(static_cast<char>(v & 0xFF));
|
||||
out->push_back(static_cast<char>((v >> 8) & 0xFF));
|
||||
}
|
||||
|
||||
void PutU32(std::string* out, uint32_t v) {
|
||||
for (int i = 0; i < 4; ++i) out->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
|
||||
}
|
||||
|
||||
void PutI32(std::string* out, int32_t v) { PutU32(out, static_cast<uint32_t>(v)); }
|
||||
|
||||
void PutU64(std::string* out, uint64_t v) {
|
||||
for (int i = 0; i < 8; ++i) out->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
|
||||
}
|
||||
|
||||
void PutF32(std::string* out, float v) {
|
||||
uint32_t bits;
|
||||
std::memcpy(&bits, &v, 4);
|
||||
PutU32(out, bits);
|
||||
}
|
||||
|
||||
void PutI16(std::string* out, int16_t v) { PutU16(out, static_cast<uint16_t>(v)); }
|
||||
|
||||
uint16_t GetU16(const std::string& b, size_t o) {
|
||||
return static_cast<uint16_t>(static_cast<uint8_t>(b[o])) |
|
||||
(static_cast<uint16_t>(static_cast<uint8_t>(b[o + 1])) << 8);
|
||||
}
|
||||
|
||||
uint32_t GetU32(const std::string& b, size_t o) {
|
||||
uint32_t v = 0;
|
||||
for (int i = 0; i < 4; ++i) v |= static_cast<uint32_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
|
||||
return v;
|
||||
}
|
||||
|
||||
uint64_t GetU64(const std::string& b, size_t o) {
|
||||
uint64_t v = 0;
|
||||
for (int i = 0; i < 8; ++i) v |= static_cast<uint64_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
|
||||
return v;
|
||||
}
|
||||
|
||||
float GetF32(const std::string& b, size_t o) {
|
||||
const uint32_t bits = GetU32(b, o);
|
||||
float f;
|
||||
std::memcpy(&f, &bits, 4);
|
||||
return f;
|
||||
}
|
||||
|
||||
int32_t GetI32(const std::string& b, size_t o) {
|
||||
return static_cast<int32_t>(GetU32(b, o));
|
||||
}
|
||||
|
||||
void PutHeader(std::string* out, BinaryType type, UnixTime stamp, uint16_t flags = 0) {
|
||||
out->append("VSL1", 4);
|
||||
PutU8(out, static_cast<uint8_t>(type));
|
||||
PutU8(out, kBinaryVersion);
|
||||
PutU16(out, flags);
|
||||
PutU64(out, static_cast<uint64_t>(stamp.toNSec()));
|
||||
}
|
||||
|
||||
// Ba ngu nghia cua mot tia -> ba gia tri canh bien. Xem vslam_common.h.
|
||||
uint16_t RangeToMm(float r, float range_max) {
|
||||
if (std::isnan(r)) return kRangeNaN;
|
||||
if (std::isinf(r)) return kRangeInf;
|
||||
// Sentinel "bi che boi than robot" la range_max + 1.0, dat boi sector mask
|
||||
// cua ScanSanitizer. Phai phan biet duoc voi inf: inf nghia la "nhin duoc
|
||||
// nhung khong co gi", sentinel nghia la "khong duoc phep nhin".
|
||||
if (r > range_max + 0.5f) return kRangeBlanked;
|
||||
if (r < 0.0f) return kRangeNaN;
|
||||
|
||||
const float mm = r * 1000.0f;
|
||||
if (mm >= static_cast<float>(kRangeMaxValid)) return kRangeMaxValid;
|
||||
return static_cast<uint16_t>(mm + 0.5f);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void EncodeScan(const LaserScan& scan, UnixTime stamp, std::string* out) {
|
||||
PutHeader(out, BinaryType::kScan, stamp);
|
||||
PutF32(out, scan.angle_min);
|
||||
PutF32(out, scan.angle_increment);
|
||||
PutF32(out, scan.range_min);
|
||||
PutF32(out, scan.range_max);
|
||||
PutU32(out, static_cast<uint32_t>(scan.ranges.size()));
|
||||
for (const float r : scan.ranges) {
|
||||
PutU16(out, RangeToMm(r, scan.range_max));
|
||||
}
|
||||
}
|
||||
|
||||
void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points,
|
||||
float quant_m, std::string* out) {
|
||||
if (quant_m <= 0.0f) quant_m = 0.01f;
|
||||
|
||||
// Lay buoc deu thay vi cat duoi: cat duoi lam mat ca mot vung khong gian,
|
||||
// buoc deu giu duoc hinh dang tong the.
|
||||
const size_t n_in = cloud.points.size();
|
||||
const size_t stride =
|
||||
(max_points > 0 && n_in > max_points) ? (n_in + max_points - 1) / max_points : 1;
|
||||
|
||||
// Dem truoc so diem hop le de khong phai sua lai truong n sau khi ghi.
|
||||
uint32_t n_out = 0;
|
||||
for (size_t i = 0; i < n_in; i += stride) {
|
||||
const PointXYZ& p = cloud.points[i];
|
||||
if (std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z)) ++n_out;
|
||||
}
|
||||
|
||||
PutHeader(out, BinaryType::kCloud, stamp);
|
||||
// Goc = (0,0,0): cloud da o frame base_footprint sau gravity_align.
|
||||
PutF32(out, 0.0f);
|
||||
PutF32(out, 0.0f);
|
||||
PutF32(out, 0.0f);
|
||||
PutF32(out, quant_m);
|
||||
PutU32(out, n_out);
|
||||
|
||||
const float inv = 1.0f / quant_m;
|
||||
constexpr float kLim = 32767.0f;
|
||||
for (size_t i = 0; i < n_in; i += stride) {
|
||||
const PointXYZ& p = cloud.points[i];
|
||||
if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue;
|
||||
// Kep vao dai i16. Voi quant 0.01 m thi dai la +-327 m -- khong bao gio
|
||||
// cham toi trong nha, nhung kep van re hon la de tran am tham.
|
||||
const float qx = std::max(-kLim, std::min(kLim, p.x * inv));
|
||||
const float qy = std::max(-kLim, std::min(kLim, p.y * inv));
|
||||
const float qz = std::max(-kLim, std::min(kLim, p.z * inv));
|
||||
PutI16(out, static_cast<int16_t>(std::lround(qx)));
|
||||
PutI16(out, static_cast<int16_t>(std::lround(qy)));
|
||||
PutI16(out, static_cast<int16_t>(std::lround(qz)));
|
||||
}
|
||||
}
|
||||
|
||||
void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
|
||||
BinaryType type) {
|
||||
PutHeader(out, type, stamp);
|
||||
PutF32(out, map.resolution);
|
||||
PutI32(out, static_cast<int32_t>(map.width));
|
||||
PutI32(out, static_cast<int32_t>(map.height));
|
||||
PutF32(out, static_cast<float>(map.origin.position.x));
|
||||
PutF32(out, static_cast<float>(map.origin.position.y));
|
||||
// Goc quay cua ban do: RTAB-Map luon tra ban do truc giao nen thuong la 0,
|
||||
// nhung giu truong nay de khong phai doi dinh dang neu sau co xoay.
|
||||
PutF32(out, 0.0f);
|
||||
|
||||
// Ghi truoc so run = 0 roi vá lai sau khi ma hoa: khong phai ma hoa hai lan.
|
||||
const size_t run_count_off = out->size();
|
||||
PutU32(out, 0);
|
||||
|
||||
const size_t runs = RleEncode(map.data, out);
|
||||
|
||||
const uint32_t r32 = static_cast<uint32_t>(runs);
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
(*out)[run_count_off + static_cast<size_t>(i)] =
|
||||
static_cast<char>((r32 >> (8 * i)) & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev,
|
||||
UnixTime stamp, std::string* out) {
|
||||
// Kich thuoc doi -> khong vá duoc, phai gui full.
|
||||
if (map.width != prev.width || map.height != prev.height ||
|
||||
map.data.size() != prev.data.size() ||
|
||||
std::abs(map.resolution - prev.resolution) > 1e-6f ||
|
||||
std::abs(map.origin.position.x - prev.origin.position.x) > 1e-6 ||
|
||||
std::abs(map.origin.position.y - prev.origin.position.y) > 1e-6) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Vung bao cac o doi.
|
||||
int32_t x0 = static_cast<int32_t>(map.width);
|
||||
int32_t y0 = static_cast<int32_t>(map.height);
|
||||
int32_t x1 = -1, y1 = -1;
|
||||
|
||||
for (uint32_t y = 0; y < map.height; ++y) {
|
||||
const size_t row = static_cast<size_t>(y) * map.width;
|
||||
for (uint32_t x = 0; x < map.width; ++x) {
|
||||
if (map.data[row + x] == prev.data[row + x]) continue;
|
||||
const int32_t xi = static_cast<int32_t>(x);
|
||||
const int32_t yi = static_cast<int32_t>(y);
|
||||
if (xi < x0) x0 = xi;
|
||||
if (yi < y0) y0 = yi;
|
||||
if (xi > x1) x1 = xi;
|
||||
if (yi > y1) y1 = yi;
|
||||
}
|
||||
}
|
||||
|
||||
if (x1 < 0) return false; // khong o nao doi
|
||||
|
||||
const int32_t w = x1 - x0 + 1;
|
||||
const int32_t h = y1 - y0 + 1;
|
||||
|
||||
std::vector<int8_t> patch;
|
||||
patch.reserve(static_cast<size_t>(w) * static_cast<size_t>(h));
|
||||
for (int32_t y = y0; y <= y1; ++y) {
|
||||
const size_t row = static_cast<size_t>(y) * map.width;
|
||||
for (int32_t x = x0; x <= x1; ++x) {
|
||||
patch.push_back(map.data[row + static_cast<size_t>(x)]);
|
||||
}
|
||||
}
|
||||
|
||||
PutHeader(out, BinaryType::kMapPatch, stamp);
|
||||
PutI32(out, x0);
|
||||
PutI32(out, y0);
|
||||
PutI32(out, w);
|
||||
PutI32(out, h);
|
||||
|
||||
const size_t run_count_off = out->size();
|
||||
PutU32(out, 0);
|
||||
const size_t runs = RleEncode(patch, out);
|
||||
const uint32_t r32 = static_cast<uint32_t>(runs);
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
(*out)[run_count_off + static_cast<size_t>(i)] =
|
||||
static_cast<char>((r32 >> (8 * i)) & 0xFF);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m,
|
||||
std::string* out) {
|
||||
std::vector<const Pose2D*> kept;
|
||||
kept.reserve(path.size());
|
||||
|
||||
const double min_sq = min_step_m * min_step_m;
|
||||
const Pose2D* last = nullptr;
|
||||
for (const auto& p : path) {
|
||||
if (last != nullptr) {
|
||||
const double dx = p.x - last->x, dy = p.y - last->y;
|
||||
if (dx * dx + dy * dy < min_sq) continue;
|
||||
}
|
||||
kept.push_back(&p);
|
||||
last = &p;
|
||||
}
|
||||
// Luon giu diem cuoi: do la vi tri hien tai, mat no thi duong di trong nhu
|
||||
// dang tut hau.
|
||||
if (!path.empty() && (kept.empty() || kept.back() != &path.back())) {
|
||||
kept.push_back(&path.back());
|
||||
}
|
||||
|
||||
PutHeader(out, BinaryType::kPath, stamp);
|
||||
PutU32(out, static_cast<uint32_t>(kept.size()));
|
||||
for (const Pose2D* p : kept) {
|
||||
PutF32(out, static_cast<float>(p->x));
|
||||
PutF32(out, static_cast<float>(p->y));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Giai ma (test) --------------------------------------------------------
|
||||
|
||||
bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out) {
|
||||
if (buf.size() < offset + kBinaryHeaderSize) return false;
|
||||
if (std::memcmp(buf.data() + offset, "VSL1", 4) != 0) return false;
|
||||
out->type = static_cast<BinaryType>(static_cast<uint8_t>(buf[offset + 4]));
|
||||
out->version = static_cast<uint8_t>(buf[offset + 5]);
|
||||
out->flags = GetU16(buf, offset + 6);
|
||||
out->stamp_ns = GetU64(buf, offset + 8);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DecodeScan(const std::string& buf, LaserScan* out) {
|
||||
BinaryHeader h;
|
||||
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kScan) return false;
|
||||
|
||||
size_t o = kBinaryHeaderSize;
|
||||
if (buf.size() < o + 20) return false;
|
||||
|
||||
out->angle_min = GetF32(buf, o); o += 4;
|
||||
out->angle_increment = GetF32(buf, o); o += 4;
|
||||
out->range_min = GetF32(buf, o); o += 4;
|
||||
out->range_max = GetF32(buf, o); o += 4;
|
||||
const uint32_t n = GetU32(buf, o); o += 4;
|
||||
|
||||
if (buf.size() < o + static_cast<size_t>(n) * 2) return false;
|
||||
|
||||
out->ranges.clear();
|
||||
out->ranges.reserve(n);
|
||||
for (uint32_t i = 0; i < n; ++i) {
|
||||
const uint16_t v = GetU16(buf, o + static_cast<size_t>(i) * 2);
|
||||
switch (v) {
|
||||
case kRangeNaN:
|
||||
out->ranges.push_back(std::numeric_limits<float>::quiet_NaN());
|
||||
break;
|
||||
case kRangeInf:
|
||||
out->ranges.push_back(std::numeric_limits<float>::infinity());
|
||||
break;
|
||||
case kRangeBlanked:
|
||||
out->ranges.push_back(out->range_max + 1.0f);
|
||||
break;
|
||||
default:
|
||||
out->ranges.push_back(static_cast<float>(v) * 0.001f);
|
||||
break;
|
||||
}
|
||||
}
|
||||
out->header.stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) {
|
||||
BinaryHeader h;
|
||||
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kMapFull) return false;
|
||||
|
||||
size_t o = kBinaryHeaderSize;
|
||||
if (buf.size() < o + 28) return false;
|
||||
|
||||
out->resolution = GetF32(buf, o); o += 4;
|
||||
out->width = static_cast<uint32_t>(GetI32(buf, o)); o += 4;
|
||||
out->height = static_cast<uint32_t>(GetI32(buf, o)); o += 4;
|
||||
out->origin.position.x = GetF32(buf, o); o += 4;
|
||||
out->origin.position.y = GetF32(buf, o); o += 4;
|
||||
o += 4; // oyaw
|
||||
const uint32_t runs = GetU32(buf, o); o += 4;
|
||||
|
||||
const size_t expected = static_cast<size_t>(out->width) * out->height;
|
||||
if (!RleDecode(buf, o, runs, expected, &out->data)) return false;
|
||||
|
||||
out->header.stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
213
libs/vslam_web/src/json_writer.cc
Normal file
213
libs/vslam_web/src/json_writer.cc
Normal file
@@ -0,0 +1,213 @@
|
||||
#include "json_writer.h"
|
||||
|
||||
#include "vslam/geometry.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
void Key(const char* k, std::string* out) {
|
||||
out->push_back('"');
|
||||
out->append(k);
|
||||
out->append("\":");
|
||||
}
|
||||
|
||||
void Comma(std::string* out) { out->push_back(','); }
|
||||
|
||||
void Str(const char* k, const std::string& v, std::string* out) {
|
||||
Key(k, out);
|
||||
out->push_back('"');
|
||||
JsonEscape(v, out);
|
||||
out->push_back('"');
|
||||
}
|
||||
|
||||
void Num(const char* k, double v, int dec, std::string* out) {
|
||||
Key(k, out);
|
||||
JsonNumber(v, dec, out);
|
||||
}
|
||||
|
||||
void Int(const char* k, long long v, std::string* out) {
|
||||
Key(k, out);
|
||||
char buf[24];
|
||||
std::snprintf(buf, sizeof(buf), "%lld", v);
|
||||
out->append(buf);
|
||||
}
|
||||
|
||||
void Bool(const char* k, bool v, std::string* out) {
|
||||
Key(k, out);
|
||||
out->append(v ? "true" : "false");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void JsonEscape(const std::string& in, std::string* out) {
|
||||
for (const char c : in) {
|
||||
switch (c) {
|
||||
case '"': out->append("\\\""); break;
|
||||
case '\\': out->append("\\\\"); break;
|
||||
case '\n': out->append("\\n"); break;
|
||||
case '\r': out->append("\\r"); break;
|
||||
case '\t': out->append("\\t"); break;
|
||||
default:
|
||||
if (static_cast<unsigned char>(c) < 0x20) {
|
||||
char buf[8];
|
||||
std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned char>(c));
|
||||
out->append(buf);
|
||||
} else {
|
||||
out->push_back(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void JsonNumber(double v, int decimals, std::string* out) {
|
||||
// JSON khong co NaN/Infinity. De nguyen thi JSON.parse() nem loi va browser
|
||||
// mat CA khung chu khong chi mot truong -- mot min_front = inf (hop le, co
|
||||
// nghia "khong thay gi") se lam ca bang trang thai bien mat.
|
||||
if (!std::isfinite(v)) {
|
||||
out->append("null");
|
||||
return;
|
||||
}
|
||||
char buf[40];
|
||||
std::snprintf(buf, sizeof(buf), "%.*f", decimals, v);
|
||||
out->append(buf);
|
||||
}
|
||||
|
||||
void WriteStateJson(const WebSnapshot& s, std::string* out) {
|
||||
out->append("{\"t\":\"state\",");
|
||||
Num("stamp", s.stamp.toSec(), 3, out); Comma(out);
|
||||
|
||||
// Hinh hoc robot -- trinh duyet KHONG duoc tu doan kich thuoc.
|
||||
//
|
||||
// Chi xuat khi `valid`: mot trinh ve nhan so 0 se dung ban kinh 0 va ve ra
|
||||
// mot cham, con nhan KHONG GI thi biet la chua co du lieu va bao ro.
|
||||
if (s.robot.valid) {
|
||||
Key("robot", out);
|
||||
out->push_back('{');
|
||||
Num("radius", s.robot.radius, 4, out); Comma(out);
|
||||
Num("wheel_radius", s.robot.wheel_radius, 4, out); Comma(out);
|
||||
Num("wheel_sep", s.robot.wheel_separation, 4, out); Comma(out);
|
||||
Num("half_width", s.robot.body_half_width, 4, out); Comma(out);
|
||||
Num("laser_x", s.robot.laser_x, 4, out); Comma(out);
|
||||
Num("laser_y", s.robot.laser_y, 4, out); Comma(out);
|
||||
Num("laser_z", s.robot.laser_z, 4, out); Comma(out);
|
||||
Num("cam_x", s.robot.camera_x, 4, out); Comma(out);
|
||||
Num("cam_y", s.robot.camera_y, 4, out); Comma(out);
|
||||
Num("cam_z", s.robot.camera_z, 4, out); Comma(out);
|
||||
Num("cam_pitch", s.robot.camera_pitch, 4, out); Comma(out);
|
||||
Num("cam_hfov", s.robot.camera_hfov, 4, out); Comma(out);
|
||||
Num("cam_vfov", s.robot.camera_vfov, 4, out); Comma(out);
|
||||
Num("cliff_min", s.robot.cliff_min, 3, out); Comma(out);
|
||||
Num("cliff_max", s.robot.cliff_max, 3, out);
|
||||
out->push_back('}');
|
||||
Comma(out);
|
||||
}
|
||||
|
||||
Key("pose", out);
|
||||
out->push_back('{');
|
||||
Num("x", s.pose_map.x, 3, out); Comma(out);
|
||||
Num("y", s.pose_map.y, 3, out); Comma(out);
|
||||
Num("yaw", s.pose_map.theta, 4, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
// Ground truth chi xuat khi CO. Xuat 0 khi khong co la noi doi: client
|
||||
// khong phan biet duoc "dung o goc" voi "khong biet".
|
||||
if (s.have_ground_truth) {
|
||||
Key("gt", out);
|
||||
out->push_back('{');
|
||||
Num("x", s.ground_truth.x, 3, out); Comma(out);
|
||||
Num("y", s.ground_truth.y, 3, out); Comma(out);
|
||||
Num("yaw", s.ground_truth.theta, 4, out); Comma(out);
|
||||
Num("roll", s.gt_roll, 4, out); Comma(out);
|
||||
Num("pitch", s.gt_pitch, 4, out); Comma(out);
|
||||
// Sai so vi tri cua uoc luong so voi su that. Tinh o day thay vi de
|
||||
// client tu tru: neu sau nay map va gt khac goc toa do thi phep tru
|
||||
// ngay tren client se sai am tham.
|
||||
Num("err", Distance2D(s.pose_map, s.ground_truth), 4, out);
|
||||
out->push_back('}');
|
||||
Comma(out);
|
||||
}
|
||||
|
||||
Key("odom", out);
|
||||
out->push_back('{');
|
||||
Num("x", s.pose_odom.x, 3, out); Comma(out);
|
||||
Num("y", s.pose_odom.y, 3, out); Comma(out);
|
||||
Num("yaw", s.pose_odom.theta, 4, out); Comma(out);
|
||||
Num("vx", s.vx, 3, out); Comma(out);
|
||||
Num("vyaw", s.vyaw, 3, out); Comma(out);
|
||||
Num("slip", s.slip_metric, 3, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("tilt", out);
|
||||
out->push_back('{');
|
||||
Num("roll", s.roll, 4, out); Comma(out);
|
||||
Num("pitch", s.pitch, 4, out); Comma(out);
|
||||
Bool("accel_ok", s.accel_ok, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("safety", out);
|
||||
out->push_back('{');
|
||||
Str("state", s.safety.state, out); Comma(out);
|
||||
Str("detail", s.safety.detail, out); Comma(out);
|
||||
Num("min_front", s.safety.min_front, 3, out); Comma(out);
|
||||
Int("front_rays", s.safety.front_rays, out); Comma(out);
|
||||
Int("front_blanked", s.safety.front_blanked, out); Comma(out);
|
||||
Int("front_usable", s.safety.front_usable, out); Comma(out);
|
||||
Bool("estop", s.safety.estop, out); Comma(out);
|
||||
Bool("bumper_latched", s.safety.bumper_latched, out); Comma(out);
|
||||
Bool("cliff", s.safety.cliff, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("slam", out);
|
||||
out->push_back('{');
|
||||
Str("mode", s.slam.mode, out); Comma(out);
|
||||
Bool("localized", s.slam.localized, out); Comma(out);
|
||||
Num("score", s.slam.score, 3, out); Comma(out);
|
||||
Int("loop_id", s.slam.loop_closure_id, out); Comma(out);
|
||||
Int("map_version", s.slam.map_version, out); Comma(out);
|
||||
Num("process_ms", s.slam.process_ms, 1, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("teleop", out);
|
||||
out->push_back('{');
|
||||
Num("linear_speed", s.teleop.linear_speed, 3, out); Comma(out);
|
||||
Num("angular_speed", s.teleop.angular_speed, 3, out); Comma(out);
|
||||
Num("max_linear_speed", s.teleop.max_linear_speed, 3, out); Comma(out);
|
||||
Num("max_angular_speed", s.teleop.max_angular_speed, 3, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("health", out);
|
||||
out->push_back('{');
|
||||
Num("lidar_hz", s.health.lidar_hz, 1, out); Comma(out);
|
||||
Num("camera_hz", s.health.camera_hz, 1, out); Comma(out);
|
||||
Num("imu_hz", s.health.imu_hz, 1, out); Comma(out);
|
||||
Num("ekf_hz", s.health.ekf_hz, 1, out); Comma(out);
|
||||
Num("clock_skew", s.health.clock_skew, 7, out); Comma(out);
|
||||
Num("cpu_pct", s.health.cpu_pct, 1, out); Comma(out);
|
||||
Num("rss_mb", s.health.rss_mb, 0, out); Comma(out);
|
||||
|
||||
Key("drops", out);
|
||||
out->push_back('{');
|
||||
bool first = true;
|
||||
for (const auto& kv : s.health.drops) {
|
||||
if (!first) Comma(out);
|
||||
first = false;
|
||||
Int(kv.first.c_str(), static_cast<long long>(kv.second), out);
|
||||
}
|
||||
out->push_back('}');
|
||||
out->push_back('}');
|
||||
|
||||
out->push_back('}');
|
||||
}
|
||||
|
||||
void WriteStatusJson(const StatusResponse& st, std::string* out) {
|
||||
out->push_back('{');
|
||||
Int("code", static_cast<long long>(st.code), out);
|
||||
Comma(out);
|
||||
Str("message", st.message, out);
|
||||
out->push_back('}');
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
36
libs/vslam_web/src/json_writer.h
Normal file
36
libs/vslam_web/src/json_writer.h
Normal file
@@ -0,0 +1,36 @@
|
||||
#ifndef VSLAM_JSON_WRITER_H_
|
||||
#define VSLAM_JSON_WRITER_H_
|
||||
|
||||
// Sinh JSON bang cach noi chuoi. Header NOI BO, khong phat hanh.
|
||||
//
|
||||
// Vi sao khong dung nlohmann/json: no khong co san tren may nao trong hai may
|
||||
// (dev focal lan Jetson jammy), va schema o day co dinh va nho -- mot
|
||||
// serializer ~150 dong khong phai danh doi gi dang ke.
|
||||
//
|
||||
// Chi ho tro chieu GHI. Doc JSON (body cua POST /api/*) lam bang json_parse.h,
|
||||
// cung mot ly do.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/web_snapshot.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Escape theo RFC 8259: ", \, va cac ky tu dieu khien < 0x20.
|
||||
void JsonEscape(const std::string& in, std::string* out);
|
||||
|
||||
// Ghi so thuc voi so chu so co dinh. Tra "null" neu NaN hoac inf -- JSON
|
||||
// khong co hai gia tri do, va de nguyen thi JSON.parse() cua browser nem loi
|
||||
// lam mat CA khung, khong chi mot truong.
|
||||
void JsonNumber(double v, int decimals, std::string* out);
|
||||
|
||||
// Toan bo khung trang thai, khop schema mo ta trong ke hoach.
|
||||
void WriteStateJson(const WebSnapshot& snap, std::string* out);
|
||||
|
||||
// Tra loi cho POST /api/*.
|
||||
void WriteStatusJson(const StatusResponse& st, std::string* out);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_JSON_WRITER_H_
|
||||
85
libs/vslam_web/src/rle.cc
Normal file
85
libs/vslam_web/src/rle.cc
Normal file
@@ -0,0 +1,85 @@
|
||||
#include "vslam/rle.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
constexpr uint16_t kMaxRun = 65535;
|
||||
|
||||
void PutU16(std::string* out, uint16_t v) {
|
||||
out->push_back(static_cast<char>(v & 0xFF));
|
||||
out->push_back(static_cast<char>((v >> 8) & 0xFF));
|
||||
}
|
||||
|
||||
uint16_t GetU16(const std::string& buf, size_t off) {
|
||||
return static_cast<uint16_t>(static_cast<uint8_t>(buf[off])) |
|
||||
(static_cast<uint16_t>(static_cast<uint8_t>(buf[off + 1])) << 8);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
size_t RleEncode(const std::vector<int8_t>& data, std::string* out) {
|
||||
if (data.empty()) return 0;
|
||||
|
||||
size_t runs = 0;
|
||||
int8_t value = data[0];
|
||||
uint32_t len = 1;
|
||||
|
||||
for (size_t i = 1; i < data.size(); ++i) {
|
||||
if (data[i] == value && len < kMaxRun) {
|
||||
++len;
|
||||
continue;
|
||||
}
|
||||
PutU16(out, static_cast<uint16_t>(len));
|
||||
out->push_back(static_cast<char>(value));
|
||||
++runs;
|
||||
value = data[i];
|
||||
len = 1;
|
||||
}
|
||||
|
||||
PutU16(out, static_cast<uint16_t>(len));
|
||||
out->push_back(static_cast<char>(value));
|
||||
++runs;
|
||||
return runs;
|
||||
}
|
||||
|
||||
size_t RleEncodedSize(const std::vector<int8_t>& data) {
|
||||
if (data.empty()) return 0;
|
||||
|
||||
size_t runs = 1;
|
||||
int8_t value = data[0];
|
||||
uint32_t len = 1;
|
||||
|
||||
for (size_t i = 1; i < data.size(); ++i) {
|
||||
if (data[i] == value && len < kMaxRun) {
|
||||
++len;
|
||||
continue;
|
||||
}
|
||||
++runs;
|
||||
value = data[i];
|
||||
len = 1;
|
||||
}
|
||||
return runs * 3;
|
||||
}
|
||||
|
||||
bool RleDecode(const std::string& buf, size_t offset, size_t run_count,
|
||||
size_t expected_size, std::vector<int8_t>* out) {
|
||||
if (offset + run_count * 3 > buf.size()) return false;
|
||||
|
||||
out->clear();
|
||||
out->reserve(expected_size);
|
||||
|
||||
for (size_t r = 0; r < run_count; ++r) {
|
||||
const size_t off = offset + r * 3;
|
||||
const uint16_t len = GetU16(buf, off);
|
||||
const int8_t value = static_cast<int8_t>(buf[off + 2]);
|
||||
// Chan phinh bo nho neu du lieu hong: khong reserve theo len chua kiem.
|
||||
if (out->size() + len > expected_size) return false;
|
||||
out->insert(out->end(), len, value);
|
||||
}
|
||||
|
||||
return out->size() == expected_size;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
29
libs/vslam_web/src/web_assets.h
Normal file
29
libs/vslam_web/src/web_assets.h
Normal file
@@ -0,0 +1,29 @@
|
||||
#ifndef VSLAM_WEB_ASSETS_H_
|
||||
#define VSLAM_WEB_ASSETS_H_
|
||||
|
||||
// Asset tinh (html/js/css) nhung trong .so luc build boi vslam_embed_assets()
|
||||
// trong cmake/vslam_helpers.cmake.
|
||||
//
|
||||
// Vi sao nhung chu khong doc tu dia: Jetson ngoai hien truong phai phuc vu
|
||||
// duoc UI ke ca khi /var/lib chua duoc .deb dien, va lech phien ban giua .so
|
||||
// voi UI la chi phi ho tro co that.
|
||||
//
|
||||
// Cua hau: WebConfig::asset_dir khac rong thi doc tu dia (che do dev).
|
||||
|
||||
#include <cstddef>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
namespace vslam {
|
||||
|
||||
struct EmbeddedAsset {
|
||||
const unsigned char* data;
|
||||
std::size_t size;
|
||||
};
|
||||
|
||||
// Dinh nghia nam trong web_assets_generated.cc do CMake sinh.
|
||||
const std::map<std::string, EmbeddedAsset>& EmbeddedAssets();
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_WEB_ASSETS_H_
|
||||
779
libs/vslam_web/src/web_server.cc
Normal file
779
libs/vslam_web/src/web_server.cc
Normal file
@@ -0,0 +1,779 @@
|
||||
#include "vslam/web_server.h"
|
||||
|
||||
#include <boost/asio/dispatch.hpp>
|
||||
#include <boost/asio/io_context.hpp>
|
||||
#include <boost/asio/ip/tcp.hpp>
|
||||
#include <boost/asio/post.hpp>
|
||||
#include <boost/asio/strand.hpp>
|
||||
#include <boost/beast/core.hpp>
|
||||
#include <boost/beast/http.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <deque>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/json_parse.h"
|
||||
#include "json_writer.h"
|
||||
#include "vslam/binary_codec.h"
|
||||
#include "vslam/log.h"
|
||||
#include "web_assets.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
namespace beast = boost::beast;
|
||||
namespace http = beast::http;
|
||||
namespace websocket = beast::websocket;
|
||||
namespace asio = boost::asio;
|
||||
using tcp = asio::ip::tcp;
|
||||
|
||||
const char* MimeType(const std::string& path) {
|
||||
const size_t dot = path.rfind('.');
|
||||
const std::string ext = dot == std::string::npos ? "" : path.substr(dot);
|
||||
if (ext == ".html") return "text/html; charset=utf-8";
|
||||
if (ext == ".js") return "application/javascript; charset=utf-8";
|
||||
if (ext == ".css") return "text/css; charset=utf-8";
|
||||
if (ext == ".json") return "application/json";
|
||||
if (ext == ".svg") return "image/svg+xml";
|
||||
if (ext == ".ico") return "image/x-icon";
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
// Chan duong dan di len tren (..) va duong dan tuyet doi. Endpoint nay khong
|
||||
// xac thuc nen phai gia dinh duong dan la thu dich.
|
||||
bool SafeAssetPath(const std::string& target, std::string* out) {
|
||||
if (target.empty() || target[0] != '/') return false;
|
||||
std::string p = target.substr(1);
|
||||
const size_t q = p.find('?');
|
||||
if (q != std::string::npos) p = p.substr(0, q);
|
||||
if (p.empty()) p = "index.html";
|
||||
if (p.find("..") != std::string::npos) return false;
|
||||
if (p.find('\\') != std::string::npos) return false;
|
||||
*out = p;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Giao dien chung cho HttpSession va WsSession, de Stop() dong duoc moi phien
|
||||
// ma khong can biet loai.
|
||||
class SessionBase {
|
||||
public:
|
||||
virtual ~SessionBase() = default;
|
||||
virtual void Close() = 0;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class WebServerImpl {
|
||||
public:
|
||||
WebConfig cfg;
|
||||
WebServer::CommandHandler on_command;
|
||||
WebServer::TeleopHandler on_teleop;
|
||||
|
||||
asio::io_context ioc;
|
||||
std::unique_ptr<tcp::acceptor> acceptor;
|
||||
std::vector<std::thread> threads;
|
||||
std::atomic<bool> running{false};
|
||||
uint16_t bound_port = 0;
|
||||
|
||||
// MOI phien deu giu mot shared_ptr<WebServerImpl> (chung can cfg, stats,
|
||||
// handler). Neu o day giu nguoc lai bang shared_ptr thi thanh chu trinh va
|
||||
// khong gi duoc giai phong. Giu bang weak_ptr.
|
||||
//
|
||||
// Chu trinh thu hai, tinh vi hon, da tung lam ro toan bo server: io_context
|
||||
// la THANH VIEN cua WebServerImpl, con handler dang cho thi giu
|
||||
// shared_ptr<WebServerImpl>. ioc.stop() KHONG huy handler dang cho -- chung
|
||||
// nam lai trong hang doi cua io_context cho toi khi io_context bi huy, ma
|
||||
// io_context lai khong the bi huy vi chinh chung dang giu no. Vi vay Stop()
|
||||
// phai DONG MOI PHIEN TRUOC, de handler hoan tat voi loi va nha con tro ra.
|
||||
mutable std::mutex sessions_mu;
|
||||
std::map<const SessionBase*, std::weak_ptr<SessionBase>> all_sessions;
|
||||
std::map<const class WsSession*, std::weak_ptr<class WsSession>> ws_sessions;
|
||||
|
||||
void Register(const SessionBase* key, std::weak_ptr<SessionBase> w) {
|
||||
std::lock_guard<std::mutex> lk(sessions_mu);
|
||||
all_sessions.emplace(key, std::move(w));
|
||||
}
|
||||
void Unregister(const SessionBase* key) {
|
||||
std::lock_guard<std::mutex> lk(sessions_mu);
|
||||
all_sessions.erase(key);
|
||||
}
|
||||
|
||||
mutable std::mutex stats_mu;
|
||||
WebServer::Stats stats;
|
||||
|
||||
// Hinh hoc 3D cua the gioi. Dat mot lan luc khoi dong, doc tu luong web --
|
||||
// mutex RIENG, khong dung chung voi stats_mu: mot yeu cau world.bin sao 6.7
|
||||
// MB duoi lock, giu stats_mu ngan ay lau se lam nghen moi khung gui di.
|
||||
mutable std::mutex world_mu;
|
||||
std::string world_blob;
|
||||
|
||||
WebServerImpl(WebConfig c, WebServer::CommandHandler cmd,
|
||||
WebServer::TeleopHandler tel)
|
||||
: cfg(std::move(c)), on_command(std::move(cmd)), on_teleop(std::move(tel)) {}
|
||||
|
||||
void BumpSent(size_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(stats_mu);
|
||||
stats.frames_sent++;
|
||||
stats.bytes_sent += bytes;
|
||||
}
|
||||
void BumpDropped() {
|
||||
std::lock_guard<std::mutex> lk(stats_mu);
|
||||
stats.frames_dropped++;
|
||||
}
|
||||
void BumpAuthFailure() {
|
||||
std::lock_guard<std::mutex> lk(stats_mu);
|
||||
stats.auth_failures++;
|
||||
}
|
||||
void BumpCommand() {
|
||||
std::lock_guard<std::mutex> lk(stats_mu);
|
||||
stats.commands_handled++;
|
||||
}
|
||||
void BumpConnection() {
|
||||
std::lock_guard<std::mutex> lk(stats_mu);
|
||||
stats.connections_total++;
|
||||
}
|
||||
// Goi khi da giu sessions_mu. stats_mu la khoa khac nen khong deadlock,
|
||||
// nhung THU TU phai luon la sessions_mu -> stats_mu, khong bao gio nguoc.
|
||||
void BumpConnectionLocked() { BumpConnection(); }
|
||||
|
||||
// Bat doi xung co y: BAT e-stop luon duoc phep (fail-safe); GO e-stop va
|
||||
// reset bumper bat buoc co token. Mot endpoint e-stop khong xac thuc tren
|
||||
// WiFi LAN nghia la ai cung e-stop duoc -- chap nhan duoc; nhung ai cung
|
||||
// GO duoc e-stop cua nguoi khac thi khong.
|
||||
bool CommandNeedsAuth(const std::string& cmd, const std::string& body) const {
|
||||
if (cfg.auth_token.empty()) return false;
|
||||
if (cmd != "safety/estop") return true;
|
||||
|
||||
bool on = false;
|
||||
if (!JsonGetBool(body, "on", &on)) {
|
||||
// KHONG parse duoc -> DOI XAC THUC (fail closed).
|
||||
//
|
||||
// Ban dau cho nay mac dinh on=true roi bo qua xac thuc, va do la mot lo
|
||||
// hong that: handler dien giai cung mot body hong theo cach khac (no
|
||||
// tim chuoi "true") nen co the GO e-stop, trong khi lop xac thuc tuong
|
||||
// la dang BAT. Hai ben bat dong y nghia cua body la du de vuot xac thuc.
|
||||
//
|
||||
// Quy tac: khi khong chac y dinh la gi thi doi token. Chi mien xac thuc
|
||||
// cho truong hop da doc duoc TUONG MINH la on=true.
|
||||
return true;
|
||||
}
|
||||
return !on; // BAT e-stop: mien. GO e-stop: doi token.
|
||||
}
|
||||
|
||||
bool AuthOk(const std::string& provided) const {
|
||||
return cfg.auth_token.empty() || provided == cfg.auth_token;
|
||||
}
|
||||
|
||||
bool LoadAsset(const std::string& name, std::string* body, const char** mime) {
|
||||
*mime = MimeType(name);
|
||||
|
||||
if (!cfg.asset_dir.empty()) {
|
||||
const std::string path = cfg.asset_dir + "/" + name;
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
if (!f) return false;
|
||||
std::ostringstream ss;
|
||||
ss << f.rdbuf();
|
||||
*body = ss.str();
|
||||
return true;
|
||||
}
|
||||
|
||||
const auto& assets = EmbeddedAssets();
|
||||
const auto it = assets.find(name);
|
||||
if (it == assets.end()) return false;
|
||||
body->assign(reinterpret_cast<const char*>(it->second.data), it->second.size);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WsSession: mot ket noi WebSocket.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class WsSession : public std::enable_shared_from_this<WsSession>,
|
||||
public SessionBase {
|
||||
public:
|
||||
WsSession(tcp::socket&& socket, std::shared_ptr<WebServerImpl> impl)
|
||||
: ws_(std::move(socket)), impl_(std::move(impl)) {}
|
||||
|
||||
~WsSession() override { impl_->Unregister(this); }
|
||||
|
||||
void Run(http::request<http::string_body> req) {
|
||||
ws_.set_option(websocket::stream_base::timeout::suggested(beast::role_type::server));
|
||||
ws_.set_option(websocket::stream_base::decorator([](websocket::response_type& res) {
|
||||
res.set(http::field::server, "vslam");
|
||||
}));
|
||||
impl_->Register(this, std::weak_ptr<SessionBase>(
|
||||
std::static_pointer_cast<SessionBase>(shared_from_this())));
|
||||
auto self = shared_from_this();
|
||||
ws_.async_accept(req, [self](beast::error_code ec) { self->OnAccept(ec); });
|
||||
}
|
||||
|
||||
// Goi tu luong web_tx. Khong chan.
|
||||
void Send(std::shared_ptr<const std::string> payload, bool is_binary, bool is_map) {
|
||||
auto self = shared_from_this();
|
||||
asio::post(ws_.get_executor(), [self, payload, is_binary, is_map] {
|
||||
self->Enqueue(std::move(payload), is_binary, is_map);
|
||||
});
|
||||
}
|
||||
|
||||
uint32_t acked_map_version() const { return acked_map_version_.load(); }
|
||||
bool world_map_sent() const { return world_map_sent_.load(); }
|
||||
void mark_world_map_sent() { world_map_sent_.store(true); }
|
||||
void set_acked_map_version(uint32_t v) { acked_map_version_.store(v); }
|
||||
|
||||
void Close() override {
|
||||
auto self = shared_from_this();
|
||||
asio::post(ws_.get_executor(), [self] {
|
||||
beast::error_code ec;
|
||||
// close() tu te truoc; neu that bai thi dong tho de handler dang cho
|
||||
// hoan tat voi loi va nha shared_ptr ra.
|
||||
self->ws_.close(websocket::close_code::going_away, ec);
|
||||
if (ec) {
|
||||
beast::get_lowest_layer(self->ws_).close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
struct Frame {
|
||||
std::shared_ptr<const std::string> data;
|
||||
bool binary = true;
|
||||
bool is_map = false;
|
||||
};
|
||||
|
||||
void OnAccept(beast::error_code ec) {
|
||||
if (ec) {
|
||||
VSLAM_DEBUG("ws accept: " << ec.message());
|
||||
Remove();
|
||||
return;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
impl_->ws_sessions.emplace(this, weak_from_this());
|
||||
impl_->BumpConnectionLocked();
|
||||
VSLAM_INFO("web: client ket noi (tong " << impl_->ws_sessions.size() << ")");
|
||||
}
|
||||
Read();
|
||||
}
|
||||
|
||||
void Read() {
|
||||
auto self = shared_from_this();
|
||||
ws_.async_read(buffer_, [self](beast::error_code ec, size_t n) {
|
||||
self->OnRead(ec, n);
|
||||
});
|
||||
}
|
||||
|
||||
void OnRead(beast::error_code ec, size_t /*n*/) {
|
||||
if (ec) {
|
||||
Remove();
|
||||
return;
|
||||
}
|
||||
const std::string msg = beast::buffers_to_string(buffer_.data());
|
||||
buffer_.consume(buffer_.size());
|
||||
HandleClientMessage(msg);
|
||||
Read();
|
||||
}
|
||||
|
||||
void HandleClientMessage(const std::string& msg) {
|
||||
std::string type;
|
||||
if (!JsonGetString(msg, "t", &type)) return;
|
||||
|
||||
if (type == "cmd") {
|
||||
// Joypad cam ung: gia tri chuan hoa [-1,1] o 20 Hz.
|
||||
// Toan bo shaping (ramp, deadman) lam o C++ trong teleop_shaper, khong
|
||||
// o JS -- khong bao gio tin browser ve dinh dang chuyen dong.
|
||||
double vx = 0.0, wz = 0.0;
|
||||
JsonGetNumber(msg, "vx", &vx);
|
||||
JsonGetNumber(msg, "wz", &wz);
|
||||
vx = std::max(-1.0, std::min(1.0, vx));
|
||||
wz = std::max(-1.0, std::min(1.0, wz));
|
||||
if (impl_->on_teleop) impl_->on_teleop(vx, wz);
|
||||
return;
|
||||
}
|
||||
|
||||
if (type == "ack_map") {
|
||||
double v = 0.0;
|
||||
if (JsonGetNumber(msg, "version", &v) && v >= 0.0) {
|
||||
set_acked_map_version(static_cast<uint32_t>(v));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void Enqueue(std::shared_ptr<const std::string> payload, bool is_binary, bool is_map) {
|
||||
if (queue_.size() >= impl_->cfg.max_queued_frames) {
|
||||
// Day hang doi. Drop khung CU NHAT KHONG PHAI MAP.
|
||||
// MAP khong bao gio bi drop: mat mot khung scan la mat 100 ms du lieu,
|
||||
// mat khung MAP la client hien ban do sai cho toi lan doi version sau --
|
||||
// co the la vinh vien trong che do localization.
|
||||
auto it = std::find_if(queue_.begin(), queue_.end(),
|
||||
[](const Frame& f) { return !f.is_map; });
|
||||
if (it != queue_.end()) {
|
||||
queue_.erase(it);
|
||||
impl_->BumpDropped();
|
||||
} else if (!is_map) {
|
||||
impl_->BumpDropped();
|
||||
return; // hang doi toan MAP, bo khung moi
|
||||
}
|
||||
}
|
||||
|
||||
queue_.push_back(Frame{std::move(payload), is_binary, is_map});
|
||||
if (!writing_) Write();
|
||||
}
|
||||
|
||||
void Write() {
|
||||
if (queue_.empty()) {
|
||||
writing_ = false;
|
||||
return;
|
||||
}
|
||||
writing_ = true;
|
||||
const Frame& f = queue_.front();
|
||||
ws_.binary(f.binary);
|
||||
|
||||
auto self = shared_from_this();
|
||||
const size_t n = f.data->size();
|
||||
ws_.async_write(asio::buffer(*f.data), [self, n](beast::error_code ec, size_t) {
|
||||
if (ec) {
|
||||
self->Remove();
|
||||
return;
|
||||
}
|
||||
self->impl_->BumpSent(n);
|
||||
self->queue_.pop_front();
|
||||
self->Write();
|
||||
});
|
||||
}
|
||||
|
||||
void Remove() {
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
impl_->ws_sessions.erase(this);
|
||||
}
|
||||
|
||||
websocket::stream<beast::tcp_stream> ws_;
|
||||
std::shared_ptr<WebServerImpl> impl_;
|
||||
beast::flat_buffer buffer_;
|
||||
std::deque<Frame> queue_;
|
||||
bool writing_ = false;
|
||||
std::atomic<uint32_t> acked_map_version_{0};
|
||||
// Ban do the gioi la TINH trong mo phong -- gui mot lan la du, khong can
|
||||
// co che version/ACK nhu ban do SLAM.
|
||||
std::atomic<bool> world_map_sent_{false};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HttpSession: phuc vu asset tinh va POST /api/*.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class HttpSession : public std::enable_shared_from_this<HttpSession>,
|
||||
public SessionBase {
|
||||
public:
|
||||
HttpSession(tcp::socket&& socket, std::shared_ptr<WebServerImpl> impl)
|
||||
: stream_(std::move(socket)), impl_(std::move(impl)) {}
|
||||
|
||||
~HttpSession() override { impl_->Unregister(this); }
|
||||
|
||||
void Run() {
|
||||
// Dang ky de Stop() dong duoc. Phai lam o day chu khong o constructor:
|
||||
// shared_from_this() chua dung duoc trong constructor.
|
||||
impl_->Register(this, std::weak_ptr<SessionBase>(
|
||||
std::static_pointer_cast<SessionBase>(shared_from_this())));
|
||||
asio::dispatch(stream_.get_executor(),
|
||||
[self = shared_from_this()] { self->Read(); });
|
||||
}
|
||||
|
||||
void Close() override {
|
||||
auto self = shared_from_this();
|
||||
asio::post(stream_.get_executor(), [self] {
|
||||
beast::error_code ec;
|
||||
self->stream_.socket().shutdown(tcp::socket::shutdown_both, ec);
|
||||
self->stream_.close();
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
void Read() {
|
||||
req_ = {};
|
||||
stream_.expires_after(std::chrono::seconds(30));
|
||||
auto self = shared_from_this();
|
||||
http::async_read(stream_, buffer_, req_,
|
||||
[self](beast::error_code ec, size_t) { self->OnRead(ec); });
|
||||
}
|
||||
|
||||
void OnRead(beast::error_code ec) {
|
||||
if (ec == http::error::end_of_stream) {
|
||||
Finish();
|
||||
return;
|
||||
}
|
||||
if (ec) return;
|
||||
|
||||
if (websocket::is_upgrade(req_)) {
|
||||
// Token cho WS di qua query string vi browser khong dat header tuy y
|
||||
// duoc tren WebSocket handshake.
|
||||
if (!impl_->cfg.auth_token.empty()) {
|
||||
const std::string target(req_.target());
|
||||
const std::string want = "token=" + impl_->cfg.auth_token;
|
||||
if (target.find(want) == std::string::npos) {
|
||||
impl_->BumpAuthFailure();
|
||||
Respond(http::status::unauthorized, "text/plain", "thieu hoac sai token\n");
|
||||
return;
|
||||
}
|
||||
}
|
||||
std::make_shared<WsSession>(stream_.release_socket(), impl_)->Run(std::move(req_));
|
||||
return;
|
||||
}
|
||||
|
||||
HandleRequest();
|
||||
}
|
||||
|
||||
void HandleRequest() {
|
||||
const std::string target(req_.target());
|
||||
|
||||
if (req_.method() == http::verb::post && target.rfind("/api/", 0) == 0) {
|
||||
HandleApi(target.substr(5));
|
||||
return;
|
||||
}
|
||||
|
||||
if (req_.method() == http::verb::get && target.rfind("/api/", 0) == 0) {
|
||||
HandleApiGet(target.substr(5));
|
||||
return;
|
||||
}
|
||||
|
||||
if (req_.method() != http::verb::get && req_.method() != http::verb::head) {
|
||||
Respond(http::status::method_not_allowed, "text/plain", "chi GET/POST\n");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string name;
|
||||
if (!SafeAssetPath(target, &name)) {
|
||||
Respond(http::status::bad_request, "text/plain", "duong dan khong hop le\n");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string body;
|
||||
const char* mime = nullptr;
|
||||
if (!impl_->LoadAsset(name, &body, &mime)) {
|
||||
Respond(http::status::not_found, "text/plain", "khong tim thay\n");
|
||||
return;
|
||||
}
|
||||
Respond(http::status::ok, mime, body);
|
||||
}
|
||||
|
||||
void HandleApi(const std::string& cmd) {
|
||||
const std::string body = req_.body();
|
||||
|
||||
if (impl_->CommandNeedsAuth(cmd, body)) {
|
||||
std::string provided;
|
||||
const auto it = req_.find("X-Auth-Token");
|
||||
if (it != req_.end()) provided = std::string(it->value());
|
||||
if (!impl_->AuthOk(provided)) {
|
||||
impl_->BumpAuthFailure();
|
||||
VSLAM_WARN("web: tu choi lenh khong co token: " << cmd);
|
||||
std::string out;
|
||||
WriteStatusJson(StatusResponse::Error(StatusCode::kUnauthenticated,
|
||||
"can X-Auth-Token"),
|
||||
&out);
|
||||
Respond(http::status::unauthorized, "application/json", out);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
StatusResponse st = StatusResponse::Error(StatusCode::kNotFound, "khong co handler");
|
||||
if (impl_->on_command) {
|
||||
// Handler chay TREN LUONG IO: phai tra ve ngay. Cach dung dung la day
|
||||
// vao hang doi lenh roi tra Ok -- luong web khong bao gio truc tiep sua
|
||||
// state cua estimator.
|
||||
st = impl_->on_command(cmd, body);
|
||||
}
|
||||
impl_->BumpCommand();
|
||||
|
||||
std::string out;
|
||||
WriteStatusJson(st, &out);
|
||||
Respond(st.ok() ? http::status::ok : http::status::bad_request,
|
||||
"application/json", out);
|
||||
}
|
||||
|
||||
void HandleApiGet(const std::string& cmd) {
|
||||
if (cmd == "status") {
|
||||
const WebServer::Stats s = [this] {
|
||||
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
||||
return impl_->stats;
|
||||
}();
|
||||
size_t clients = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
clients = impl_->ws_sessions.size();
|
||||
}
|
||||
std::ostringstream oss;
|
||||
oss << "{\"clients\":" << clients
|
||||
<< ",\"connections_total\":" << s.connections_total
|
||||
<< ",\"frames_sent\":" << s.frames_sent
|
||||
<< ",\"frames_dropped\":" << s.frames_dropped
|
||||
<< ",\"bytes_sent\":" << s.bytes_sent
|
||||
<< ",\"commands_handled\":" << s.commands_handled
|
||||
<< ",\"auth_failures\":" << s.auth_failures << "}";
|
||||
Respond(http::status::ok, "application/json", oss.str());
|
||||
return;
|
||||
}
|
||||
if (cmd == "world.bin") {
|
||||
std::string blob;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->world_mu);
|
||||
blob = impl_->world_blob;
|
||||
}
|
||||
if (blob.empty()) {
|
||||
Respond(http::status::not_found, "application/json",
|
||||
"{\"code\":2,\"message\":\"khong chay tu file .world\"}");
|
||||
return;
|
||||
}
|
||||
Respond(http::status::ok, "application/octet-stream", blob);
|
||||
return;
|
||||
}
|
||||
Respond(http::status::not_found, "application/json",
|
||||
"{\"code\":2,\"message\":\"khong co endpoint\"}");
|
||||
}
|
||||
|
||||
void Respond(http::status status, const char* mime, const std::string& body) {
|
||||
auto res = std::make_shared<http::response<http::string_body>>(status, req_.version());
|
||||
res->set(http::field::server, "vslam");
|
||||
res->set(http::field::content_type, mime);
|
||||
// UI la mot trang duy nhat trong LAN; khong cache de sua asset la thay ngay.
|
||||
res->set(http::field::cache_control, "no-store");
|
||||
res->keep_alive(req_.keep_alive());
|
||||
res->body() = body;
|
||||
res->prepare_payload();
|
||||
|
||||
auto self = shared_from_this();
|
||||
const bool keep = res->keep_alive();
|
||||
http::async_write(stream_, *res,
|
||||
[self, res, keep](beast::error_code ec, size_t) {
|
||||
if (ec || !keep) {
|
||||
self->Finish();
|
||||
return;
|
||||
}
|
||||
self->Read();
|
||||
});
|
||||
}
|
||||
|
||||
// Ket thuc binh thuong sau khi tra loi xong. Khac han Close() cong khai o
|
||||
// tren: cai do la dong CUONG BUC luc tat server.
|
||||
void Finish() {
|
||||
beast::error_code ec;
|
||||
stream_.socket().shutdown(tcp::socket::shutdown_send, ec);
|
||||
}
|
||||
|
||||
beast::tcp_stream stream_;
|
||||
std::shared_ptr<WebServerImpl> impl_;
|
||||
beast::flat_buffer buffer_;
|
||||
http::request<http::string_body> req_;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WebServer
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
WebServer::WebServer(WebConfig cfg, CommandHandler on_command, TeleopHandler on_teleop)
|
||||
: impl_(std::make_shared<WebServerImpl>(std::move(cfg), std::move(on_command),
|
||||
std::move(on_teleop))) {}
|
||||
|
||||
WebServer::~WebServer() { Stop(); }
|
||||
|
||||
StatusResponse WebServer::Start() {
|
||||
if (impl_->running.load()) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition, "da chay roi");
|
||||
}
|
||||
|
||||
if (impl_->cfg.auth_token.empty()) {
|
||||
VSLAM_WARN("web: KHONG co auth_token -- bat ky ai trong LAN deu go duoc "
|
||||
"e-stop. Dat system.web.auth_token truoc khi chay that.");
|
||||
}
|
||||
|
||||
beast::error_code ec;
|
||||
const auto addr = asio::ip::make_address(impl_->cfg.bind_address, ec);
|
||||
if (ec) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"bind_address khong hop le: " + ec.message());
|
||||
}
|
||||
|
||||
impl_->acceptor = std::make_unique<tcp::acceptor>(impl_->ioc);
|
||||
const tcp::endpoint ep(addr, impl_->cfg.port);
|
||||
|
||||
impl_->acceptor->open(ep.protocol(), ec);
|
||||
if (ec) return StatusResponse::Error(StatusCode::kInternal, "open: " + ec.message());
|
||||
|
||||
impl_->acceptor->set_option(asio::socket_base::reuse_address(true), ec);
|
||||
impl_->acceptor->bind(ep, ec);
|
||||
if (ec) {
|
||||
return StatusResponse::Error(StatusCode::kUnavailable,
|
||||
"bind cong " + std::to_string(impl_->cfg.port) + ": " +
|
||||
ec.message());
|
||||
}
|
||||
impl_->acceptor->listen(asio::socket_base::max_listen_connections, ec);
|
||||
if (ec) return StatusResponse::Error(StatusCode::kInternal, "listen: " + ec.message());
|
||||
|
||||
impl_->bound_port = impl_->acceptor->local_endpoint().port();
|
||||
impl_->running.store(true);
|
||||
|
||||
DoAccept();
|
||||
|
||||
const int n = std::max(1, impl_->cfg.io_threads);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
impl_->threads.emplace_back([impl = impl_] { impl->ioc.run(); });
|
||||
}
|
||||
|
||||
VSLAM_INFO("web: dang nghe tren " << impl_->cfg.bind_address << ":"
|
||||
<< impl_->bound_port);
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
void WebServer::DoAccept() {
|
||||
impl_->acceptor->async_accept(
|
||||
asio::make_strand(impl_->ioc),
|
||||
[this](beast::error_code ec, tcp::socket socket) {
|
||||
if (!impl_->running.load()) return;
|
||||
if (!ec) {
|
||||
std::make_shared<HttpSession>(std::move(socket), impl_)->Run();
|
||||
}
|
||||
DoAccept();
|
||||
});
|
||||
}
|
||||
|
||||
void WebServer::Stop() {
|
||||
if (!impl_ || !impl_->running.exchange(false)) return;
|
||||
|
||||
// THU TU O DAY LA QUAN TRONG, khong duoc doi.
|
||||
//
|
||||
// 1. Dung nhan ket noi moi.
|
||||
beast::error_code ec;
|
||||
if (impl_->acceptor) impl_->acceptor->close(ec);
|
||||
|
||||
// 2. Dong moi phien, va lam TRUOC khi dung io_context.
|
||||
//
|
||||
// Moi phien giu mot shared_ptr<WebServerImpl>, ma io_context lai la
|
||||
// thanh vien cua WebServerImpl. ioc.stop() KHONG huy handler dang cho --
|
||||
// chung nam lai trong hang doi cho toi khi io_context bi huy, ma
|
||||
// io_context khong the bi huy vi chinh chung dang giu no. Ket qua la ca
|
||||
// server (io_context, thread, session) ro vinh vien sau moi lan Stop().
|
||||
//
|
||||
// Dong socket lam cac async op dang cho hoan tat voi loi, handler chay,
|
||||
// session nha con tro, chu trinh dut.
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
for (const auto& kv : impl_->all_sessions) {
|
||||
if (auto s = kv.second.lock()) s->Close();
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Cho io_context can viec mot cach tu nhien. KHONG goi ioc.stop() o day:
|
||||
// stop() lam run() tra ve ngay va bo lai handler chua chay, dung lai
|
||||
// dung van de o tren.
|
||||
for (auto& t : impl_->threads) {
|
||||
if (t.joinable()) t.join();
|
||||
}
|
||||
impl_->threads.clear();
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
impl_->all_sessions.clear();
|
||||
impl_->ws_sessions.clear();
|
||||
}
|
||||
VSLAM_INFO("web: da dung");
|
||||
}
|
||||
|
||||
void WebServer::SetWorldMesh(std::string blob) {
|
||||
std::lock_guard<std::mutex> lk(impl_->world_mu);
|
||||
impl_->world_blob = std::move(blob);
|
||||
}
|
||||
|
||||
void WebServer::Publish(const WebSnapshot& snap) {
|
||||
// Khong co client thi KHONG serialize gi ca. Serialize mot cloud 4000 diem
|
||||
// va mot map cho khong ai xem la lang phi that o 10 Hz tren Jetson.
|
||||
std::vector<std::shared_ptr<WsSession>> targets;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
if (impl_->ws_sessions.empty()) return;
|
||||
targets.reserve(impl_->ws_sessions.size());
|
||||
for (const auto& kv : impl_->ws_sessions) {
|
||||
if (auto s = kv.second.lock()) targets.push_back(std::move(s));
|
||||
}
|
||||
if (targets.empty()) return;
|
||||
}
|
||||
|
||||
auto state = std::make_shared<std::string>();
|
||||
WriteStateJson(snap, state.get());
|
||||
for (const auto& s : targets) s->Send(state, /*binary=*/false, /*is_map=*/false);
|
||||
|
||||
if (snap.scan) {
|
||||
auto buf = std::make_shared<std::string>();
|
||||
EncodeScan(*snap.scan, snap.stamp, buf.get());
|
||||
for (const auto& s : targets) s->Send(buf, true, false);
|
||||
}
|
||||
|
||||
if (snap.cloud) {
|
||||
auto buf = std::make_shared<std::string>();
|
||||
EncodeCloud(*snap.cloud, snap.stamp, impl_->cfg.cloud_max_points,
|
||||
impl_->cfg.cloud_quant_m, buf.get());
|
||||
for (const auto& s : targets) s->Send(buf, true, false);
|
||||
}
|
||||
|
||||
if (!snap.trajectory.empty()) {
|
||||
auto buf = std::make_shared<std::string>();
|
||||
EncodePath(snap.trajectory, snap.stamp, impl_->cfg.path_min_step_m, buf.get());
|
||||
for (const auto& s : targets) s->Send(buf, true, false);
|
||||
}
|
||||
|
||||
// BAN DO THE GIOI -- khung nhin "Gazebo". Gui MOT lan cho moi client.
|
||||
//
|
||||
// Tach khoi ban do SLAM co y: hai thu tra loi hai cau hoi khac nhau, va
|
||||
// doi chieu chung chinh la ly do nguoi ta mo ca Gazebo lan RViz.
|
||||
if (snap.world_map) {
|
||||
std::shared_ptr<std::string> buf;
|
||||
for (const auto& s : targets) {
|
||||
if (s->world_map_sent()) continue;
|
||||
if (!buf) {
|
||||
buf = std::make_shared<std::string>();
|
||||
EncodeMapFull(*snap.world_map, snap.stamp, buf.get(), BinaryType::kWorldMap);
|
||||
}
|
||||
s->Send(buf, true, /*is_map=*/true);
|
||||
s->mark_world_map_sent();
|
||||
}
|
||||
}
|
||||
|
||||
// MAP chi gui cho client chua xac nhan phien ban nay. Ma hoa mot lan roi
|
||||
// dung chung -- 62 kB cho ban do lon nhat (do tren map_hospital.db).
|
||||
if (snap.map && snap.slam.map_version != 0) {
|
||||
std::shared_ptr<std::string> buf;
|
||||
for (const auto& s : targets) {
|
||||
if (s->acked_map_version() == snap.slam.map_version) continue;
|
||||
if (!buf) {
|
||||
buf = std::make_shared<std::string>();
|
||||
EncodeMapFull(*snap.map, snap.stamp, buf.get());
|
||||
}
|
||||
s->Send(buf, true, /*is_map=*/true);
|
||||
s->set_acked_map_version(snap.slam.map_version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
size_t WebServer::client_count() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
return impl_->ws_sessions.size();
|
||||
}
|
||||
|
||||
uint16_t WebServer::port() const { return impl_->bound_port; }
|
||||
|
||||
WebServer::Stats WebServer::stats() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
||||
return impl_->stats;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
840
libs/vslam_web/www/app.js
Normal file
840
libs/vslam_web/www/app.js
Normal 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
715
libs/vslam_web/www/app3d.js
Normal 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);
|
||||
}
|
||||
156
libs/vslam_web/www/index.html
Normal file
156
libs/vslam_web/www/index.html
Normal 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 · cuon de phong to · 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">−</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">−</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 · phim mui ten · Space = dung<br>+ − 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>
|
||||
168
libs/vslam_web/www/style.css
Normal file
168
libs/vslam_web/www/style.css
Normal 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; }
|
||||
7
libs/vslam_web/www/vendor/three.min.js
vendored
Normal file
7
libs/vslam_web/www/vendor/three.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user