Loading...
Searching...
No Matches
foamGltfScene.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) 2021-2022 OpenCFD Ltd.
9-------------------------------------------------------------------------------
10License
11 This file is part of OpenFOAM.
12
13 OpenFOAM is free software: you can redistribute it and/or modify it
14 under the terms of the GNU General Public License as published by
15 the Free Software Foundation, either version 3 of the License, or
16 (at your option) any later version.
17
18 OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
19 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
20 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
21 for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
25
26\*---------------------------------------------------------------------------*/
28#include "foamGltfScene.H"
29#include "OFstream.H"
30#include "OSspecific.H"
31
32// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
33
35:
36 objects_(),
37 meshes_(),
38 bufferViews_(),
39 accessors_(),
40 animations_(),
41 bytes_(0)
42{}
43
44
45// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
46
47Foam::glTF::mesh& Foam::glTF::scene::getMesh(label meshi)
48{
49 const label lastMeshi = (meshes_.size() - 1);
50
51 if (meshi < 0)
52 {
53 meshi = (lastMeshi < 0 ? static_cast<label>(0) : lastMeshi);
54 }
55
56 if (meshi > lastMeshi)
57 {
59 << "Mesh " << meshi << " out of range: " << lastMeshi
61 }
62
63 return meshes_[meshi];
64}
65
66
68(
69 const vectorField& fld,
70 const word& name,
71 const label meshi,
72 const scalarField& alpha
73)
74{
75 auto& gmesh = getMesh(meshi);
76
77 auto& bv = bufferViews_.create(name);
78 bv.byteOffset() = bytes_;
79 bv.byteLength() = fld.size()*3*sizeof(float); // 3 components
80 bv.target() = key(targetTypes::ARRAY_BUFFER);
81 bytes_ += bv.byteLength();
82
83 auto& acc = accessors_.create(name);
84 acc.bufferViewId() = bv.id();
85 acc.set(fld, false); // no min-max
86
87 auto& obj = objects_.create(name);
88
89 if (alpha.empty())
90 {
91 obj.addData(fld);
92 }
93 else
94 {
95 bv.byteLength() += fld.size()*sizeof(float);
96 bytes_ += fld.size()*sizeof(float);
97
98 acc.type() = "VEC4";
99
100 // Support uniform alpha vs full alpha field
101 tmp<scalarField> talpha(alpha);
102
103 if (alpha.size() == 1 && alpha.size() < fld.size())
104 {
105 talpha = tmp<scalarField>::New(fld.size(), alpha[0]);
106 }
107
108 obj.addData(fld, talpha());
109 }
111 gmesh.addColour(acc.id());
112
113 return acc.id();
114}
115
116
118{
119 animations_.create(name);
120 return animations_.size() - 1;
121}
122
123
125(
126 const label animationi,
127 const label inputId,
128 const label outputId,
129 const label meshId,
130 const string& interpolation
131)
132{
133 if (animationi > animations_.size() - 1)
134 {
136 << "Animation " << animationi << " out of range "
137 << (animations_.size() - 1)
138 << abort(FatalError);
139 }
140
141 const label nodeId = meshId + 1; // offset by 1 for parent node
142
143 // Note
144 // using 1 mesh per node +1 parent node => meshes_.size() nodes in total
145 if (nodeId > meshes_.size())
146 {
148 << "Node " << nodeId << " out of range " << meshes_.size()
149 << abort(FatalError);
150 }
151
152 animations_[animationi].addTranslation
153 (
154 inputId,
155 outputId,
156 nodeId,
158 );
159}
160
161
162void Foam::glTF::scene::write(const fileName& outputFile)
163{
164 fileName jsonFile(outputFile);
165 jsonFile.replace_ext("gltf");
166
167 // Note: called on master only
168
169 if (!isDir(jsonFile.path()))
170 {
171 mkDir(jsonFile.path());
173
174 OFstream os(jsonFile);
175 write(os);
176}
177
178
180{
181 fileName binFile(os.name());
182 binFile.replace_ext("bin");
183
184 // Write binary file
185 // Note: using stdStream
186 OFstream bin(binFile, IOstreamOption::BINARY);
187 auto& osbin = bin.stdStream();
188
189 label totalBytes = 0;
190 for (const auto& object : objects_.data())
191 {
192 for (const auto& data : object.data())
193 {
194 osbin.write
195 (
196 reinterpret_cast<const char*>(&data),
197 sizeof(float)
198 );
199
200 totalBytes += sizeof(float);
201 }
202 }
203
204 // Write json file
205 os << "{" << nl << incrIndent;
206
207 os << indent << "\"asset\" : {" << nl << incrIndent
208 << indent << "\"generator\" : \"OpenFOAM - www.openfoam.com\"," << nl
209 << indent << "\"version\" : \"2.0\"" << nl << decrIndent
210 << indent << "}," << nl;
211
212 os << indent << "\"extras\" : {" << nl << incrIndent
213 /* << content */
214 << decrIndent
215 << indent << "}," << nl;
216
217 os << indent << "\"scene\": 0," << nl;
218
219 os << indent << "\"scenes\": [{" << nl << incrIndent
220 << indent << "\"nodes\" : [0]" << nl << decrIndent
221 << indent << "}]," << nl;
222
223 os << indent << "\"buffers\" : [{" << nl << incrIndent
224 << indent << "\"uri\" : " << string(fileName::name(binFile))
225 << "," << nl
226 << indent << "\"byteLength\" : " << totalBytes << nl << decrIndent
227 << indent << "}]," << nl;
228
229 os << indent << "\"nodes\" : [" << nl << incrIndent
230 << indent << "{" << nl << incrIndent
231 << indent << "\"children\" : [" << nl << incrIndent;
232
233 // List of child node indices
234 os << indent;
235 forAll(meshes_, meshi)
236 {
237 const label nodeId = meshi + 1;
238
239 os << nodeId;
240
241 if (meshi != meshes_.size() - 1) os << ", ";
242
243 if ((meshi+1) % 10 == 0) os << nl << indent;
244 }
245
246 os << decrIndent << nl << indent << "]," << nl
247 << indent << "\"name\" : \"parent\"" << nl << decrIndent
248 << indent << "}," << nl;
249
250 // List of child meshes
251 forAll(meshes_, meshi)
252 {
253 os << indent << "{" << nl << incrIndent
254 << indent << "\"mesh\" : " << meshi << nl << decrIndent
255 << indent << "}";
256
257 if (meshi != meshes_.size() - 1) os << ",";
258
259 os << nl;
260 }
261
262 os << decrIndent << indent << "]";
263
264 meshes_.write(os, "meshes");
265
266 bufferViews_.write(os, "bufferViews");
267
268 accessors_.write(os, "accessors");
269
270 animations_.write(os, "animations");
271
272 os << nl;
273
274 os << decrIndent << "}" << endl;
275}
276
277
278// ************************************************************************* //
Functions used by OpenFOAM that are specific to POSIX compliant operating systems and need to be repl...
Info<< nl;Info<< "Write faMesh in vtk format:"<< nl;{ vtk::uindirectPatchWriter writer(aMesh.patch(), fileName(aMesh.time().globalPath()/vtkBaseFileName));writer.writeGeometry();globalIndex procAddr(aMesh.nFaces());labelList cellIDs;if(UPstream::master()) { cellIDs.resize(procAddr.totalSize());for(const labelRange &range :procAddr.ranges()) { auto slice=cellIDs.slice(range);slice=identity(range);} } writer.beginCellData(4);writer.writeProcIDs();writer.write("cellID", cellIDs);writer.write("area", aMesh.S().field());writer.write("normal", aMesh.faceAreaNormals());writer.beginPointData(1);writer.write("normal", aMesh.pointAreaNormals());Info<< " "<< writer.output().name()<< nl;}{ vtk::lineWriter writer(aMesh.points(), aMesh.edges(), fileName(aMesh.time().globalPath()/(vtkBaseFileName+"-edges")));writer.writeGeometry();writer.beginCellData(4);writer.writeProcIDs();{ Field< scalar > fld(faMeshTools::flattenEdgeField(aMesh.magLe(), true))
Output to file stream as an OSstream, normally using std::ofstream for the actual output.
Definition OFstream.H:75
virtual const std::ostream & stdStream() const override
Const access to underlying std::ostream.
Definition OFstream.C:125
An Ostream is an abstract base class for all output systems (streams, files, token lists,...
Definition Ostream.H:59
virtual bool write(const token &tok)=0
Write token to stream or otherwise handle it.
A class for handling file names.
Definition fileName.H:75
fileName & replace_ext(const word &ending)
Remove extension (if any) and append a new one.
Definition fileNameI.H:230
word name() const
Return basename (part beyond last /), including its extension.
Definition fileNameI.H:205
static std::string path(const std::string &str)
Return directory path name (part before last /).
Definition fileNameI.H:169
static std::string name(const std::string &str)
Return basename (part beyond last /), including its extension.
Definition fileNameI.H:192
scene()
Default construct.
void write(const fileName &outputFile)
Write to file pair (.gltf, .bin).
label addColourToMesh(const vectorField &fld, const word &name, const label meshId, const scalarField &alpha=scalarField::null())
Add a colour field to the mesh, optionally with an alpha channel.
label createAnimation(const word &name)
Returns index of last animation.
void addToAnimation(const label animationi, const label inputId, const label outputId, const label meshId, const string &interpolation="LINEAR")
Add to existing animation.
Abstract base class for volume field interpolation.
A class for handling character strings derived from std::string.
Definition string.H:76
A class for managing temporary objects.
Definition tmp.H:75
static tmp< T > New(Args &&... args)
Construct tmp with forwarding arguments.
Definition tmp.H:215
A class for handling words, derived from Foam::string.
Definition word.H:66
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
Definition error.H:600
OBJstream os(runTime.globalPath()/outputName)
constexpr auto key(const Type &t) noexcept
Helper function to return the enum value.
@ ARRAY_BUFFER
vertex attributes
bool mkDir(const fileName &pathName, mode_t mode=0777)
Make a directory and return an error if it could not be created.
Definition POSIX.C:616
Field< scalar > scalarField
Specialisation of Field<T> for scalar.
Ostream & incrIndent(Ostream &os)
Increment the indent level.
Definition Ostream.H:490
Ostream & endl(Ostream &os)
Add newline and flush stream.
Definition Ostream.H:519
Ostream & indent(Ostream &os)
Indent stream.
Definition Ostream.H:481
errorManip< error > abort(error &err)
Definition errorManip.H:139
Field< vector > vectorField
Specialisation of Field<T> for vector.
error FatalError
Error stream (stdout output on all processes), with additional 'FOAM FATAL ERROR' header text and sta...
word name(const expressions::valueTypeCode typeCode)
A word representation of a valueTypeCode. Empty for expressions::valueTypeCode::INVALID.
Definition exprTraits.C:127
Ostream & decrIndent(Ostream &os)
Decrement the indent level.
Definition Ostream.H:499
bool isDir(const fileName &name, const bool followLink=true)
Does the name exist as a DIRECTORY in the file system?
Definition POSIX.C:862
constexpr char nl
The newline '\n' character (0x0a).
Definition Ostream.H:50
runTime write()
volScalarField & alpha
#define forAll(list, i)
Loop across all elements in list.
Definition stdFoam.H:299