Loading...
Searching...
No Matches
OBJsurfaceFormat.C
Go to the documentation of this file.
1/*---------------------------------------------------------------------------*\
2 ========= |
3 \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4 \\ / O peration |
5 \\ / A nd | www.openfoam.com
6 \\/ M anipulation |
7-------------------------------------------------------------------------------
8 Copyright (C) 2011-2016 OpenFOAM Foundation
9 Copyright (C) 2016-2025 OpenCFD Ltd.
10-------------------------------------------------------------------------------
11License
12 This file is part of OpenFOAM.
13
14 OpenFOAM is free software: you can redistribute it and/or modify it
15 under the terms of the GNU General Public License as published by
16 the Free Software Foundation, either version 3 of the License, or
17 (at your option) any later version.
18
19 OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
20 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
21 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 for more details.
23
24 You should have received a copy of the GNU General Public License
25 along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
26
27\*---------------------------------------------------------------------------*/
28
29#include "OBJsurfaceFormat.H"
30#include "clock.H"
31#include "Fstream.H"
32#include "stringOps.H"
33#include "faceTraits.H"
34
35// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
36
37template<class Face>
39(
40 const fileName& filename
41)
42{
43 read(filename);
44}
45
46
47// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
48
49template<class Face>
51(
52 const fileName& filename
53)
54{
55 // Clear everything
56 this->clear();
57
58 IFstream is(filename);
59 if (!is.good())
60 {
62 << "Cannot read file " << filename << nl
63 << exit(FatalError);
64 }
65
66 // Assume that the groups are not intermixed
67 // Place faces without a group in zone0.
68 // zoneId = -1 to signal uninitialized
69 label zoneId = -1;
70 bool sorted = true;
71
72 DynamicList<point> dynPoints;
73 DynamicList<label> dynVerts;
74
75 DynamicList<label> dynElemId; // unused
76 DynamicList<Face> dynFaces;
77
78 DynamicList<word> dynNames;
79 DynamicList<label> dynZones;
80 DynamicList<label> dynSizes;
81
82 HashTable<label> groupLookup;
83
84 while (is.good())
85 {
86 string line = this->getLineNoComment(is);
87
88 // Line continuations
89 while (line.removeEnd('\\'))
90 {
91 line += this->getLineNoComment(is);
92 }
93
94 const auto tokens = stringOps::splitSpace(line);
95
96 // Require command and some arguments
97 if (tokens.size() < 2)
98 {
99 continue;
100 }
101
102 const word cmd = word::validate(tokens[0]);
103
104 if (cmd == "v")
105 {
106 // Vertex
107 // v x y z
108
109 dynPoints.append
110 (
111 point
112 (
113 readScalar(tokens[1]),
114 readScalar(tokens[2]),
115 readScalar(tokens[3])
116 )
117 );
118 }
119 else if (cmd == "g")
120 {
121 // Grouping
122 // g name
123
124 const word groupName = word::validate(tokens[1]);
125 const auto iterGroup = groupLookup.cfind(groupName);
126
127 if (iterGroup.good())
128 {
129 if (zoneId != *iterGroup)
130 {
131 sorted = false; // Group appeared out of order
132 }
133 zoneId = *iterGroup;
134 }
135 else
136 {
137 zoneId = dynSizes.size();
138 groupLookup.insert(groupName, zoneId);
139 dynNames.append(groupName);
140 dynSizes.append(0);
141 }
142 }
143 else if (cmd == "f")
144 {
145 // Face
146 // f v1 v2 v3 ...
147 // OR
148 // f v1/vt1 v2/vt2 v3/vt3 ...
149
150 // Ensure it has as valid grouping
151 if (zoneId < 0)
152 {
153 zoneId = 0;
154 groupLookup.insert("zone0", 0);
155 dynNames.append("zone0");
156 dynSizes.append(0);
157 }
158
159 dynVerts.clear();
160
161 bool first = true;
162 for (const auto& tok : tokens)
163 {
164 if (first)
165 {
166 // skip initial "f" or "l"
167 first = false;
168 continue;
169 }
170
171 std::string vrtSpec(tok.str());
172
173 if
174 (
175 const auto slash = vrtSpec.find('/');
176 slash != std::string::npos
177 )
178 {
179 vrtSpec.erase(slash);
180 }
181
182 label vertId = readLabel(vrtSpec);
183
184 dynVerts.push_back(vertId - 1);
185 }
186
187 const labelUList& f = dynVerts;
188
189 if (faceTraits<Face>::isTri() && f.size() > 3)
190 {
191 // simple face triangulation about f[0]
192 // points may be incomplete
193 for (label fp1 = 1; fp1 < f.size() - 1; fp1++)
194 {
195 const label fp2 = f.fcIndex(fp1);
196
197 dynFaces.append(Face{f[0], f[fp1], f[fp2]});
198 dynZones.append(zoneId);
199 dynSizes[zoneId]++;
200 }
201 }
202 else if (f.size() >= 3)
203 {
204 dynFaces.append(Face(f));
205 dynZones.append(zoneId);
206 dynSizes[zoneId]++;
207 }
208 }
209 }
210
211
212 // Transfer to normal lists
213 this->storedPoints().transfer(dynPoints);
214
215 this->sortFacesAndStore(dynFaces, dynZones, dynElemId, sorted);
216
217 // Add zones (retaining empty ones)
218 this->addZones(dynSizes, dynNames);
219 this->addZonesToFaces(); // for labelledTri
220
221 return true;
222}
223
224
225template<class Face>
227(
228 const fileName& filename,
229 const MeshedSurfaceProxy<Face>& surf,
230 IOstreamOption streamOpt,
231 const dictionary&
232)
233{
234 // ASCII only, allow output compression
235 streamOpt.format(IOstreamOption::ASCII);
236
237 const UList<point>& pointLst = surf.points();
238 const UList<Face>& faceLst = surf.surfFaces();
239 const UList<label>& faceMap = surf.faceMap();
240
241 // for no zones, suppress the group name
242 const surfZoneList zones
243 (
244 surf.surfZones().empty()
245 ? surfaceFormatsCore::oneZone(faceLst, "")
246 : surf.surfZones()
247 );
248
249 const bool useFaceMap = (surf.useFaceMap() && zones.size() > 1);
250
251 OFstream os(filename, streamOpt);
252 if (!os.good())
253 {
255 << "Cannot write file " << filename << nl
256 << exit(FatalError);
257 }
258
259
260 os << "# Wavefront OBJ file written " << clock::dateTime().c_str() << nl
261 << "o " << os.name().stem() << nl
262 << nl
263 << "# points : " << pointLst.size() << nl
264 << "# faces : " << faceLst.size() << nl
265 << "# zones : " << zones.size() << nl;
266
267 // Print zone names as comment
268 forAll(zones, zonei)
269 {
270 os << "# " << zonei << " " << zones[zonei].name()
271 << " (nFaces: " << zones[zonei].size() << ")" << nl;
272 }
273
274 os << nl
275 << "# <points count=\"" << pointLst.size() << "\">" << nl;
276
277 // Write vertex coords
278 for (const point& pt : pointLst)
279 {
280 os << "v " << pt.x() << ' ' << pt.y() << ' ' << pt.z() << nl;
281 }
282
283 os << "# </points>" << nl
284 << nl
285 << "# <faces count=\"" << faceLst.size() << "\">" << nl;
286
287
288 label faceIndex = 0;
289
290 for (const surfZone& zone : zones)
291 {
292 if (zone.name().size())
293 {
294 os << "g " << zone.name() << nl;
295 }
296
297 for (label nLocal = zone.size(); nLocal--; ++faceIndex)
298 {
299 const label facei =
300 (useFaceMap ? faceMap[faceIndex] : faceIndex);
301
302 const Face& f = faceLst[facei];
303
304 os << 'f';
305 for (const label verti : f)
306 {
307 os << ' ' << (verti + 1);
308 }
309 os << nl;
310 }
311 }
312 os << "# </faces>" << nl;
313}
314
315
316// ************************************************************************* //
A 1D vector of objects of type <T> that resizes itself as necessary to accept the new objects.
Definition DynamicList.H:68
void clear() noexcept
Clear the addressed list, i.e. set the size to zero.
void append(const T &val)
Copy append an element to the end of this list.
void push_back(const T &val)
Copy append an element to the end of this list.
A HashTable similar to std::unordered_map.
Definition HashTable.H:124
const_iterator cfind(const Key &key) const
Find and return an const_iterator set at the hashed entry.
Definition HashTableI.H:113
bool insert(const Key &key, const T &obj)
Copy insert a new entry, not overwriting existing entries.
Definition HashTableI.H:152
void transfer(HashTable< T, Key, Hash > &rhs)
Transfer contents into this table.
Definition HashTable.C:794
Input from file stream as an ISstream, normally using std::ifstream for the actual input.
Definition IFstream.H:55
A simple container for options an IOstream can normally have.
streamFormat format() const noexcept
Get the current stream format.
@ ASCII
"ascii" (normal default)
bool good() const noexcept
True if next operation might succeed.
Definition IOstream.H:281
A proxy for writing MeshedSurface, UnsortedMeshedSurface and surfMesh to various file formats.
const UList< surfZone > & surfZones() const noexcept
Const access to the surface zones.
const UList< Face > & surfFaces() const noexcept
Return const access to the faces.
const labelUList & faceMap() const noexcept
Const access to the faceMap, zero-sized when unused.
const pointField & points() const noexcept
Return const access to the points.
bool useFaceMap() const noexcept
Can/should use faceMap?
pointField & storedPoints()
Non-const access to global points.
virtual void addZones(const UList< surfZone > &, const bool cullEmpty=false)
Add surface zones.
void sortFacesAndStore(DynamicList< Face > &unsortedFaces, DynamicList< label > &zoneIds, DynamicList< label > &elemIds, bool sorted)
Sort faces by zones and store sorted faces.
bool addZonesToFaces()
Propagate zone information on face regions.
Output to file stream as an OSstream, normally using std::ofstream for the actual output.
Definition OFstream.H:75
A 1D vector of objects of type <T>, where the size of the vector is known and can be used for subscri...
Definition UList.H:89
T & first()
Access first element of the list, position [0].
Definition UList.H:957
void size(const label n)
Older name for setAddressableSize.
Definition UList.H:118
static std::string dateTime()
The current wall-clock date/time (in local time) as a string in ISO-8601 format (yyyy-mm-ddThh:mm:ss)...
Definition clock.C:53
A list of keyword definitions, which are a keyword followed by a number of values (eg,...
Definition dictionary.H:133
static bool isTri()
Face-type only handles triangles. Not true in general.
Definition faceTraits.H:51
static void write(const fileName &filename, const MeshedSurfaceProxy< Face > &surf, IOstreamOption streamOpt=IOstreamOption(), const dictionary &=dictionary::null)
Write surface mesh components (by proxy) in OBJ format.
OBJsurfaceFormat(const fileName &filename)
Construct from file name.
virtual bool read(const fileName &filename) override
Read from file.
static string getLineNoComment(ISstream &is, const char comment='#')
Read non-empty and non-comment line.
static List< surfZone > oneZone(const Container &container, const word &name="zone0")
Return a surfZone list with a single entry, the size of which corresponds to that of the container.
A class for handling file names.
Definition fileName.H:75
A line primitive.
Definition line.H:180
A surface zone on a MeshedSurface.
Definition surfZone.H:55
A class for handling words, derived from Foam::string.
Definition word.H:66
static word validate(const std::string &s, const bool prefix=false)
Construct validated word (no invalid characters).
Definition word.C:39
const word & name() const noexcept
The zone name.
Base class for mesh zones.
Definition zone.H:63
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
Definition error.H:600
OBJstream os(runTime.globalPath()/outputName)
surface1 clear()
Foam::SubStrings splitSpace(const std::string &str, std::string::size_type pos=0)
Split string into sub-strings at whitespace (TAB, NL, VT, FF, CR, SPC).
Pair< int > faceMap(const label facePi, const face &faceP, const label faceNi, const face &faceN)
List< surfZone > surfZoneList
List of surfZone.
label readLabel(const char *buf)
Parse entire buffer as a label, skipping leading/trailing whitespace.
Definition label.H:63
vector point
Point is a vector.
Definition point.H:37
error FatalError
Error stream (stdout output on all processes), with additional 'FOAM FATAL ERROR' header text and sta...
errorManipArg< error, int > exit(error &err, const int errNo=1)
Definition errorManip.H:125
UList< label > labelUList
A UList of labels.
Definition UList.H:75
constexpr char nl
The newline '\n' character (0x0a).
Definition Ostream.H:50
labelList f(nPoints)
#define forAll(list, i)
Loop across all elements in list.
Definition stdFoam.H:299