Loading a polyhedral mesh from a file and saving it back out.
Overview
This console tutorial completes the PolyMesh series (112-114) by showing file input/output. It loads a polyhedral sphere from disk, reports how many vertices, edges, faces, and cells it contains, then writes an identical copy to a new file. No viewer is opened.
The technique
Persisting geometry means serializing both the element coordinates and the connectivity (which vertices form each face, which faces bound each cell). Easy3D provides a dedicated PolyMeshIO helper for this. The file extension selects the format: ".plm" is Easy3D's built-in ASCII polyhedral format (".pm" is the binary counterpart). load() returns std::shared_ptr<PolyMesh>, or nullptr if the file is missing or malformed — so the result must always be checked. save() returns true on success. The returned handle shares ownership with any other holder.
Easy3D API
- PolyMeshIO::load(file_name): reads a polyhedral mesh; returns shared ownership (nullptr on failure).
- PolyMeshIO::save(file_name, mesh): writes the mesh; returns bool.
- PolyMesh::n_vertices() / n_edges() / n_faces() / n_cells(): element counts for the four element types of a volumetric mesh.
- resource::directory(): locates Easy3D's bundled sample data (here "data/sphere.plm").
Running it
Console-only. It prints "mesh loaded." followed by the four element counts, then "mesh saved to './sphere-copy.plm'". A copy of the sphere is written to the current working directory. The shared mesh handle is released automatically at exit.
27#include <easy3d/core/poly_mesh.h>
28#include <easy3d/fileio/poly_mesh_io.h>
29#include <easy3d/util/resource.h>
30#include <easy3d/util/initializer.h>
73int main(
int argc,
char **argv) {
79 const std::string file_name = resource::directory() +
"/data/sphere.plm";
80 auto mesh = PolyMeshIO::load(file_name);
82 std::cerr <<
"failed to load model. Please make sure the file exists and format is correct" << std::endl;
86 std::cout <<
"mesh loaded. " << std::endl;
87 std::cout <<
"\tvertices: " << mesh->n_vertices() << std::endl;
88 std::cout <<
"\tedges: " << mesh->n_edges() << std::endl;
89 std::cout <<
"\tfaces: " << mesh->n_faces() << std::endl;
90 std::cout <<
"\tcells: " << mesh->n_cells() << std::endl;
98 const std::string save_file_name =
"./sphere-copy.plm";
99 if (PolyMeshIO::save(save_file_name, mesh.get()))
100 std::cout <<
"mesh saved to \'" << save_file_name <<
"\'" << std::endl;
102 std::cerr <<
"failed create the new file" << std::endl;
Definition collider.cpp:182
- See also
- PolyMesh, PolyMeshIO, Tutorial_112_PolyMesh, Tutorial_107_SurfaceMesh_IO