// based on MSH writer from PyMesh // Copyright (c) 2015 Qingnan Zhou // Copyright (C) 2020 Vladimir Fonov // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "MshSaver.h" #include #include #include #include IGL_INLINE igl::MshSaver::MshSaver(const std::string& filename, bool binary) : m_binary(binary), m_num_nodes(0), m_num_elements(0) { if (!m_binary) { fout.open(filename.c_str(), std::fstream::out); } else { fout.open(filename.c_str(), std::fstream::binary); } if (!fout) { std::stringstream err_msg; err_msg << "Error opening " << filename << " to write msh file." << std::endl; throw std::ios_base::failure(err_msg.str()); } } IGL_INLINE igl::MshSaver::~MshSaver() { fout.close(); } IGL_INLINE void igl::MshSaver::save_mesh( const FloatVector& nodes, const IndexVector& elements, const IntVector& element_lengths, const IntVector& element_types, const IntVector& element_tags ) { save_header(); save_nodes(nodes); save_elements(elements, element_lengths, element_types, element_tags ); } IGL_INLINE void igl::MshSaver::save_header() { if (!m_binary) { fout << "$MeshFormat" << std::endl; fout << "2.2 0 " << sizeof(double) << std::endl; fout << "$EndMeshFormat" << std::endl; fout.precision(17); } else { fout << "$MeshFormat" << std::endl; fout << "2.2 1 " << sizeof(double) << std::endl; int one = 1; fout.write((char*)&one, sizeof(int)); fout << "\n$EndMeshFormat" << std::endl; } fout.flush(); } IGL_INLINE void igl::MshSaver::save_nodes(const FloatVector& nodes) { // Save nodes. // 3D hadrcoded m_num_nodes = nodes.size() / 3; fout << "$Nodes" << std::endl; fout << m_num_nodes << std::endl; if (!m_binary) { for (size_t i=0; i 0) { //int elem_type = el_type; //int tags = 0; if (!m_binary) { size_t el_ptr=0; for (size_t i=0;i( elements[el_ptr + e] )+1; fout.write((const char*)&_elem, sizeof(int)); } el_ptr+=elem_len; } } } } fout << "$EndElements" << std::endl; fout.flush(); } IGL_INLINE void igl::MshSaver::save_scalar_field(const std::string& fieldname, const FloatVector& field) { assert(field.size() == m_num_nodes); fout << "$NodeData" << std::endl; fout << "1" << std::endl; // num string tags. fout << "\"" << fieldname << "\"" << std::endl; fout << "1" << std::endl; // num real tags. fout << "0.0" << std::endl; // time value. fout << "3" << std::endl; // num int tags. fout << "0" << std::endl; // the time step fout << "1" << std::endl; // 1-component scalar field. fout << m_num_nodes << std::endl; // number of nodes if (m_binary) { for (size_t i=0; i