17#include <unordered_map>
25 size_t operator()(
const Eigen::Vector3f& v)
const {
27 for (
int i = 0; i < 3; ++i) {
30 std::memcpy(&bits, &v[i],
sizeof(
float));
31 h ^= std::hash<uint32_t>{}(bits) + 0x9e3779b9 + (h << 6) + (h >> 2);
39 bool operator()(
const Eigen::Vector3f& a,
const Eigen::Vector3f& b)
const {
40 return a.isApprox(b, 1e-7f);
45int32_t deduplicateVertex(
46 const Eigen::Vector3f& v,
47 std::unordered_map<Eigen::Vector3f, int32_t, Vector3fHash, Vector3fEqual>& vertexMap,
48 std::vector<Eigen::Vector3f>& vertices) {
49 auto it = vertexMap.find(v);
50 if (it != vertexMap.end()) {
53 const auto idx =
static_cast<int32_t
>(vertices.size());
55 vertices.push_back(v);
62bool isBinaryStl(
const filesystem::path& filepath) {
63 std::ifstream file(filepath, std::ios::binary | std::ios::ate);
64 if (!file.is_open()) {
68 const auto fileSize = file.tellg();
75 uint32_t numTriangles = 0;
76 file.read(
reinterpret_cast<char*
>(&numTriangles),
sizeof(uint32_t));
79 const auto expectedSize =
80 static_cast<std::streamoff
>(84) +
static_cast<std::streamoff
>(numTriangles) * 50;
81 return fileSize == expectedSize;
84std::optional<Mesh> loadBinaryStl(
const filesystem::path& filepath) {
85 std::ifstream file(filepath, std::ios::binary);
86 if (!file.is_open()) {
93 uint32_t numTriangles = 0;
94 file.read(
reinterpret_cast<char*
>(&numTriangles),
sizeof(uint32_t));
95 if (!file.good() || numTriangles == 0) {
100 std::unordered_map<Eigen::Vector3f, int32_t, Vector3fHash, Vector3fEqual> vertexMap;
102 for (uint32_t i = 0; i < numTriangles; ++i) {
104 std::array<float, 3>
normal{};
105 file.read(
reinterpret_cast<char*
>(
normal.data()),
sizeof(
float) * 3);
108 std::array<Eigen::Vector3f, 3> v;
110 std::array<float, 3> coords{};
111 file.read(
reinterpret_cast<char*
>(coords.data()),
sizeof(
float) * 3);
112 j = Eigen::Vector3f(coords[0], coords[1], coords[2]);
116 uint16_t attrByteCount = 0;
117 file.read(
reinterpret_cast<char*
>(&attrByteCount),
sizeof(uint16_t));
124 Eigen::Vector3i face;
125 for (
int j = 0; j < 3; ++j) {
126 face[j] = deduplicateVertex(v[j], vertexMap, mesh.vertices);
128 mesh.faces.push_back(face);
131 mesh.updateNormals();
135std::optional<Mesh> loadAsciiStl(
const filesystem::path& filepath) {
136 std::ifstream file(filepath);
137 if (!file.is_open()) {
142 std::unordered_map<Eigen::Vector3f, int32_t, Vector3fHash, Vector3fEqual> vertexMap;
146 while (std::getline(file, line)) {
147 std::istringstream iss(line);
150 if (token ==
"vertex") {
152 std::array<Eigen::Vector3f, 3> v;
153 float x = NAN, y = NAN, z = NAN;
155 v[0] = Eigen::Vector3f(x, y, z);
157 for (
int j = 1; j < 3; ++j) {
158 if (!std::getline(file, line)) {
161 std::istringstream viss(line);
164 v[j] = Eigen::Vector3f(x, y, z);
167 Eigen::Vector3i face;
168 for (
int j = 0; j < 3; ++j) {
169 face[j] = deduplicateVertex(v[j], vertexMap, mesh.vertices);
171 mesh.faces.push_back(face);
175 if (mesh.faces.empty()) {
179 mesh.updateNormals();
186 const float hx = dimX * 0.5f;
187 const float hy = dimY * 0.5f;
188 const float hz = dimZ * 0.5f;
232 const float halfLen = length * 0.5f;
235 mesh.
vertices.emplace_back(0.0f, 0.0f, -halfLen);
237 mesh.
vertices.emplace_back(0.0f, 0.0f, halfLen);
240 for (
int i = 0; i < segments; ++i) {
241 const float angle =
twopi<float>() *
static_cast<float>(i) /
static_cast<float>(segments);
242 const float x = radius * std::cos(angle);
243 const float y = radius * std::sin(angle);
244 mesh.
vertices.emplace_back(x, y, -halfLen);
246 for (
int i = 0; i < segments; ++i) {
247 const float angle =
twopi<float>() *
static_cast<float>(i) /
static_cast<float>(segments);
248 const float x = radius * std::cos(angle);
249 const float y = radius * std::sin(angle);
250 mesh.
vertices.emplace_back(x, y, halfLen);
253 const int bottomRingStart = 2;
254 const int topRingStart = 2 + segments;
256 for (
int i = 0; i < segments; ++i) {
257 const int next = (i + 1) % segments;
260 mesh.
faces.emplace_back(0, bottomRingStart + next, bottomRingStart + i);
263 mesh.
faces.emplace_back(1, topRingStart + i, topRingStart + next);
266 const int b0 = bottomRingStart + i;
267 const int b1 = bottomRingStart + next;
268 const int t0 = topRingStart + i;
269 const int t1 = topRingStart + next;
270 mesh.
faces.emplace_back(b0, b1, t1);
271 mesh.
faces.emplace_back(b0, t1, t0);
282 mesh.
vertices.emplace_back(0.0f, 0.0f, radius);
285 for (
int lat = 1; lat < latSegments; ++lat) {
286 const float phi =
pi<float>() *
static_cast<float>(lat) /
static_cast<float>(latSegments);
287 const float sinPhi = std::sin(phi);
288 const float cosPhi = std::cos(phi);
290 for (
int lon = 0; lon < lonSegments; ++lon) {
292 twopi<float>() *
static_cast<float>(lon) /
static_cast<float>(lonSegments);
293 const float x = radius * sinPhi * std::cos(theta);
294 const float y = radius * sinPhi * std::sin(theta);
295 const float z = radius * cosPhi;
296 mesh.
vertices.emplace_back(x, y, z);
301 const auto bottomPole =
static_cast<int32_t
>(mesh.
vertices.size());
302 mesh.
vertices.emplace_back(0.0f, 0.0f, -radius);
305 for (
int lon = 0; lon < lonSegments; ++lon) {
306 const int next = (lon + 1) % lonSegments;
307 mesh.
faces.emplace_back(0, 1 + lon, 1 + next);
311 for (
int lat = 0; lat < latSegments - 2; ++lat) {
312 const int ringStart = 1 + lat * lonSegments;
313 const int nextRingStart = 1 + (lat + 1) * lonSegments;
314 for (
int lon = 0; lon < lonSegments; ++lon) {
315 const int next = (lon + 1) % lonSegments;
316 const int a = ringStart + lon;
317 const int b = ringStart + next;
318 const int c = nextRingStart + next;
319 const int d = nextRingStart + lon;
320 mesh.
faces.emplace_back(a, d, c);
321 mesh.
faces.emplace_back(a, c, b);
326 const int lastRingStart = 1 + (latSegments - 2) * lonSegments;
327 for (
int lon = 0; lon < lonSegments; ++lon) {
328 const int next = (lon + 1) % lonSegments;
329 mesh.
faces.emplace_back(lastRingStart + lon, bottomPole, lastRingStart + next);
336std::optional<Mesh>
loadStlMesh(
const filesystem::path& filepath) {
337 if (!filesystem::exists(filepath)) {
338 MT_LOGW(
"STL file not found: {}", filepath.string());
342 if (isBinaryStl(filepath)) {
343 return loadBinaryStl(filepath);
345 return loadAsciiStl(filepath);
348std::optional<Mesh>
loadObjMesh(
const filesystem::path& filepath) {
349 if (!filesystem::exists(filepath)) {
350 MT_LOGW(
"OBJ file not found: {}", filepath.string());
354 std::ifstream file(filepath);
355 if (!file.is_open()) {
356 MT_LOGW(
"Failed to open OBJ file: {}", filepath.string());
363 while (std::getline(file, line)) {
364 if (line.empty() || line[0] ==
'#') {
368 std::istringstream iss(line);
373 float x = NAN, y = NAN, z = NAN;
375 mesh.
vertices.emplace_back(x, y, z);
376 }
else if (token ==
"f") {
382 std::vector<int32_t> faceIndices;
383 std::string vertexToken;
384 while (iss >> vertexToken) {
386 const auto slashPos = vertexToken.find(
'/');
387 const std::string indexStr =
388 (slashPos != std::string::npos) ? vertexToken.substr(0, slashPos) : vertexToken;
389 const int idx = std::stoi(indexStr);
391 const int32_t resolvedIdx =
392 (idx > 0) ? (idx - 1) :
static_cast<int32_t
>(mesh.
vertices.size()) + idx;
393 faceIndices.push_back(resolvedIdx);
397 if (faceIndices.size() >= 3) {
398 for (
size_t i = 2; i < faceIndices.size(); ++i) {
399 mesh.
faces.emplace_back(
400 faceIndices[0], faceIndices[
static_cast<int32_t
>(i) - 1], faceIndices[i]);
407 MT_LOGW(
"OBJ file contains no geometry: {}", filepath.string());
416 const std::string& filename,
417 const filesystem::path& urdfDir) {
419 const std::string fileScheme =
"file://";
420 if (filename.substr(0, fileScheme.size()) == fileScheme) {
421 const filesystem::path resolved(filename.substr(fileScheme.size()));
422 if (filesystem::exists(resolved)) {
425 MT_LOGW(
"Mesh file not found: {}", resolved.string());
430 const std::string packageScheme =
"package://";
431 if (filename.substr(0, packageScheme.size()) == packageScheme) {
433 const auto pathStart = filename.find(
'/', packageScheme.size());
434 if (pathStart == std::string::npos) {
435 MT_LOGW(
"Invalid package:// URI: {}", filename);
438 const std::string relativePath = filename.substr(pathStart + 1);
441 filesystem::path resolved = urdfDir / relativePath;
442 if (filesystem::exists(resolved)) {
448 resolved = urdfDir.parent_path() / relativePath;
449 if (filesystem::exists(resolved)) {
453 MT_LOGW(
"Could not resolve package:// mesh path: {}", filename);
458 const filesystem::path path(filename);
459 if (path.is_absolute()) {
460 if (filesystem::exists(path)) {
463 MT_LOGW(
"Mesh file not found: {}", path.string());
468 const filesystem::path resolved = urdfDir / path;
469 if (filesystem::exists(resolved)) {
473 MT_LOGW(
"Mesh file not found: {}", resolved.string());
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
Mesh generateCylinderMesh(float radius, float length, int segments)
Generates a cylinder mesh centered at the origin with the Z axis as its axis.
Mesh generateSphereMesh(float radius, int latSegments, int lonSegments)
Generates a UV sphere mesh centered at the origin.
Mesh generateBoxMesh(float dimX, float dimY, float dimZ)
Generates a box mesh with the given dimensions centered at the origin.
std::optional< filesystem::path > resolveMeshPath(const std::string &filename, const filesystem::path &urdfDir)
Resolves a mesh filename from a URDF visual element to a filesystem path.
std::optional< Mesh > loadStlMesh(const filesystem::path &filepath)
Loads a mesh from an STL file (binary or ASCII).
constexpr T twopi() noexcept
Returns 2 * pi.
constexpr T pi() noexcept
Returns the mathematical constant pi.
std::optional< Mesh > loadObjMesh(const filesystem::path &filepath)
Loads a mesh from a Wavefront OBJ file (vertices and triangular/polygon faces).
void updateNormals()
Compute vertex normals by averaging connected face normals.
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.