Files
cse5543_homework/lab3/writeGrid2DOFF.cpp
2026-03-31 10:26:51 -04:00

108 lines
3.1 KiB
C++

// Functions to write grid2DPoints3D as a Geomview .off file.
#include "writeGrid2DOFF.h"
#include <fstream>
#include <iostream>
#include <stdexcept>
void WRITE_GRID2D_OFF::WriteHeader(std::ostream& file) const {
file << Header() << "\n";
}
void WRITE_GRID2D_OFF::WriteComment(std::ostream& file,
const std::string& msg) const
{
file << "# " << msg << "\n";
}
void WRITE_GRID2D_OFF::WriteNumElements(std::ostream& file,
const GRID2D_POINTS3D& grid2D) const
{
file << grid2D.NumPoints() << " "
<< grid2D.NumQuadrilaterals() << " 0\n";
}
void WRITE_GRID2D_OFF::WritePointCoordinates(std::ostream& file,
const GRID2D_POINTS3D& grid2D) const
{
for (int irow = 0; irow < grid2D.NumRows(); irow++) {
for (int jcol = 0; jcol < grid2D.NumCols(); jcol++) {
auto c = grid2D.Coord(irow, jcol);
file << c[0] << " " << c[1] << " " << c[2] << "\n";
}
}
}
void WRITE_GRID2D_OFF::WriteQuadrilaterals(std::ostream& file,
const GRID2D_POINTS3D& grid2D) const
{
if (grid2D.NumRows() < 2 || grid2D.NumCols() < 2) {
// Nothing to write.
return;
}
for (int irow = 0; irow < grid2D.NumRows() - 1; irow++) {
for (int icol = 0; icol < grid2D.NumCols() - 1; icol++) {
int iv0 = grid2D.PointIndex(irow, icol);
int iv1 = iv0 + 1;
int iv2 = iv1 + grid2D.NumCols();
int iv3 = iv0 + grid2D.NumCols();
file << "4 " << iv0 << " " << iv1
<< " " << iv2 << " " << iv3 << "\n";
}
}
}
void WRITE_GRID2D_OFF::Write(std::ostream& file,
const GRID2D_POINTS3D& grid2D,
const std::vector<std::string>& comment_list) const
{
WriteHeader(file);
for (const auto& comment : comment_list) {
WriteComment(file, comment);
}
WriteNumElements(file, grid2D);
WritePointCoordinates(file, grid2D);
file << "\n";
WriteQuadrilaterals(file, grid2D);
}
void WRITE_GRID2D_OFF::OpenAndWrite(
const std::string& filename,
const GRID2D_POINTS3D& grid2D,
const std::vector<std::string>& comment_list) const
{
try {
std::ofstream outfile(filename);
if (!outfile.is_open()) {
std::cerr << "Cannot open output file " << filename << ".\n";
throw std::runtime_error(
"Cannot open output file " + filename + " for writing.");
}
Write(outfile, grid2D, comment_list);
}
catch (const std::out_of_range& e) {
std::cerr << "Error writing file " << filename
<< ".\n " << e.what() << "\n";
throw;
}
catch (const std::runtime_error& e) {
std::cerr << "Error writing file " << filename
<< ".\n " << e.what() << "\n";
throw;
}
catch (const std::exception& e) {
std::cerr << "Error writing file " << filename
<< ".\n " << e.what() << "\n";
throw;
}
}