Coverage Report

Created: 2026-11-12 07:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/assimp/code/AssetLib/Ply/PlyExporter.cpp
Line
Count
Source
1
/*
2
Open Asset Import Library (assimp)
3
----------------------------------------------------------------------
4
5
Copyright (c) 2006-2026, assimp team
6
7
All rights reserved.
8
9
Redistribution and use of this software in source and binary forms,
10
with or without modification, are permitted provided that the
11
following conditions are met:
12
13
* Redistributions of source code must retain the above
14
  copyright notice, this list of conditions and the
15
  following disclaimer.
16
17
* Redistributions in binary form must reproduce the above
18
  copyright notice, this list of conditions and the
19
  following disclaimer in the documentation and/or other
20
  materials provided with the distribution.
21
22
* Neither the name of the assimp team, nor the names of its
23
  contributors may be used to endorse or promote products
24
  derived from this software without specific prior
25
  written permission of the assimp team.
26
27
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38
39
----------------------------------------------------------------------
40
*/
41
#if !defined(ASSIMP_BUILD_NO_EXPORT) && !defined(ASSIMP_BUILD_NO_PLY_EXPORTER)
42
43
#include "PlyExporter.h"
44
#include <memory>
45
#include <cmath>
46
#include <assimp/Exceptional.h>
47
#include <assimp/scene.h>
48
#include <assimp/version.h>
49
#include <assimp/IOSystem.hpp>
50
#include <assimp/Exporter.hpp>
51
#include <assimp/qnan.h>
52
53
namespace Assimp {
54
55
// make sure type_of returns consistent output across different platforms
56
// also consider using: typeid(VAR).name()
57
template <typename T> const char* type_of(T&) { return "unknown"; }
58
9.45k
template<> const char* type_of(float&) { return "float"; }
59
0
template<> const char* type_of(double&) { return "double"; }
60
61
// ------------------------------------------------------------------------------------------------
62
// Worker function for exporting a scene to PLY. Prototyped and registered in Exporter.cpp
63
4.72k
void ExportScenePly(const char* pFile,IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* /*pProperties*/) {
64
    // invoke the exporter
65
4.72k
    PlyExporter exporter(pFile, pScene);
66
67
4.72k
    if (exporter.mOutput.fail()) {
68
0
        throw DeadlyExportError("output data creation failed. Most likely the file became too large: " + std::string(pFile));
69
0
    }
70
71
    // we're still here - export successfully completed. Write the file.
72
4.72k
    std::unique_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt"));
73
4.72k
    if (outfile == nullptr) {
74
0
        throw DeadlyExportError("could not open output .ply file: " + std::string(pFile));
75
0
    }
76
77
4.72k
    outfile->Write( exporter.mOutput.str().c_str(), static_cast<size_t>(exporter.mOutput.tellp()),1);
78
4.72k
}
79
80
4.72k
void ExportScenePlyBinary(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* /*pProperties*/) {
81
    // invoke the exporter
82
4.72k
    PlyExporter exporter(pFile, pScene, true);
83
84
    // we're still here - export successfully completed. Write the file.
85
4.72k
    std::unique_ptr<IOStream> outfile(pIOSystem->Open(pFile, "wb"));
86
4.72k
    if (outfile == nullptr) {
87
0
        throw DeadlyExportError("could not open output .ply file: " + std::string(pFile));
88
0
    }
89
90
4.72k
    outfile->Write(exporter.mOutput.str().c_str(), static_cast<size_t>(exporter.mOutput.tellp()), 1);
91
4.72k
}
92
93
1.03M
#define PLY_EXPORT_HAS_NORMALS 0x1
94
1.02M
#define PLY_EXPORT_HAS_TANGENTS_BITANGENTS 0x2
95
2.03M
#define PLY_EXPORT_HAS_TEXCOORDS 0x4
96
1.01M
#define PLY_EXPORT_HAS_COLORS (PLY_EXPORT_HAS_TEXCOORDS << AI_MAX_NUMBER_OF_TEXTURECOORDS)
97
98
// ------------------------------------------------------------------------------------------------
99
PlyExporter::PlyExporter(const char* _filename, const aiScene* pScene, bool binary) : 
100
9.45k
        filename(_filename), endl("\n") {
101
    // make sure that all formatting happens using the standard, C locale and not the user's current locale
102
9.45k
    const std::locale& l = std::locale("C");
103
9.45k
    mOutput.imbue(l);
104
9.45k
    mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION);
105
106
9.45k
    unsigned int faces = 0u, vertices = 0u, components = 0u;
107
21.0k
    for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
108
11.5k
        const aiMesh& m = *pScene->mMeshes[i];
109
11.5k
        faces += m.mNumFaces;
110
11.5k
        vertices += m.mNumVertices;
111
112
11.5k
        if (m.HasNormals()) {
113
10.2k
            components |= PLY_EXPORT_HAS_NORMALS;
114
10.2k
        }
115
11.5k
        if (m.HasTangentsAndBitangents()) {
116
3.90k
            components |= PLY_EXPORT_HAS_TANGENTS_BITANGENTS;
117
3.90k
        }
118
16.0k
        for (unsigned int t = 0; m.HasTextureCoords(t); ++t) {
119
4.47k
            components |= PLY_EXPORT_HAS_TEXCOORDS << t;
120
4.47k
        }
121
13.4k
        for (unsigned int t = 0; m.HasVertexColors(t); ++t) {
122
1.88k
            components |= PLY_EXPORT_HAS_COLORS << t;
123
1.88k
        }
124
11.5k
    }
125
126
9.45k
    mOutput << "ply" << endl;
127
9.45k
    if (binary) {
128
#if (defined AI_BUILD_BIG_ENDIAN)
129
        mOutput << "format binary_big_endian 1.0" << endl;
130
#else
131
4.72k
        mOutput << "format binary_little_endian 1.0" << endl;
132
4.72k
#endif
133
4.72k
    }
134
4.72k
    else {
135
4.72k
        mOutput << "format ascii 1.0" << endl;
136
4.72k
    }
137
9.45k
    mOutput << "comment File produced by Open Asset Import Library (https://www.assimp.org)" << endl;
138
9.45k
    mOutput << "comment (assimp v" << aiGetVersionMajor() << '.' << aiGetVersionMinor() << '.'
139
9.45k
        << aiGetVersionRevision() << ")" << endl;
140
141
    // Look through materials for a diffuse texture, and add it if found
142
19.7k
    for ( unsigned int i = 0; i < pScene->mNumMaterials; ++i ) {
143
10.2k
        const aiMaterial* const mat = pScene->mMaterials[i];
144
10.2k
        aiString s;
145
10.2k
        if ( AI_SUCCESS == mat->Get( AI_MATKEY_TEXTURE_DIFFUSE( 0 ), s ) ) {
146
2.22k
            mOutput << "comment TextureFile " << s.data << endl;
147
2.22k
        }
148
10.2k
    }
149
150
9.45k
    ai_real tmp = 0.0;
151
9.45k
    const char * typeName = type_of(tmp);
152
153
9.45k
    mOutput << "element vertex " << vertices << endl;
154
9.45k
    mOutput << "property " << typeName << " x" << endl;
155
9.45k
    mOutput << "property " << typeName << " y" << endl;
156
9.45k
    mOutput << "property " << typeName << " z" << endl;
157
158
9.45k
    if(components & PLY_EXPORT_HAS_NORMALS) {
159
7.54k
        mOutput << "property " << typeName << " nx" << endl;
160
7.54k
        mOutput << "property " << typeName << " ny" << endl;
161
7.54k
        mOutput << "property " << typeName << " nz" << endl;
162
7.54k
    }
163
164
    // write texcoords first, just in case an importer does not support tangents
165
    // bitangents and just skips over the rest of the line upon encountering
166
    // unknown fields (Ply leaves pretty much every vertex component open,
167
    // but in reality most importers only know about vertex positions, normals
168
    // and texture coordinates).
169
12.1k
    for (unsigned int n = PLY_EXPORT_HAS_TEXCOORDS, c = 0; (components & n) && c != AI_MAX_NUMBER_OF_TEXTURECOORDS; n <<= 1, ++c) {
170
2.69k
        if (!c) {
171
2.65k
            mOutput << "property " << "uchar" << " red" << endl;
172
2.65k
            mOutput << "property " << "uchar" << " green" << endl;
173
2.65k
            mOutput << "property " << "uchar" << " blue" << endl;
174
2.65k
            mOutput << "property " << "uchar" << " alpha" << endl;
175
2.65k
        } else {
176
44
            mOutput << "property " << "uchar" << " red" << c << endl;
177
44
            mOutput << "property " << "uchar" << " green" << c << endl;
178
44
            mOutput << "property " << "uchar" << " blue" << c << endl;
179
44
            mOutput << "property " << "uchar" << " alpha" << c << endl;
180
44
        }
181
2.69k
    }
182
183
9.45k
    if(components & PLY_EXPORT_HAS_TANGENTS_BITANGENTS) {
184
2.58k
        mOutput << "property " << typeName << " tx" << endl;
185
2.58k
        mOutput << "property " << typeName << " ty" << endl;
186
2.58k
        mOutput << "property " << typeName << " tz" << endl;
187
2.58k
        mOutput << "property " << typeName << " bx" << endl;
188
2.58k
        mOutput << "property " << typeName << " by" << endl;
189
2.58k
        mOutput << "property " << typeName << " bz" << endl;
190
2.58k
    }
191
192
9.45k
    mOutput << "element face " << faces << endl;
193
194
    // uchar seems to be the most common type for the number of indices per polygon and int seems to be most common for the vertex indices.
195
    // For instance, MeshLab fails to load meshes in which both types are uint. Houdini seems to have problems as well.
196
    // Obviously, using uchar will not work for meshes with polygons with more than 255 indices, but how realistic is this case?
197
9.45k
    mOutput << "property list uchar int vertex_index" << endl;
198
199
9.45k
    mOutput << "end_header" << endl;
200
201
21.0k
    for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
202
11.5k
        if (binary) {
203
5.77k
            WriteMeshVertsBinary(pScene->mMeshes[i], components);
204
5.77k
        } else {
205
5.77k
            WriteMeshVerts(pScene->mMeshes[i], components);
206
5.77k
        }
207
11.5k
    }
208
21.0k
    for (unsigned int i = 0, ofs = 0; i < pScene->mNumMeshes; ++i) {
209
11.5k
        if (binary) {
210
5.77k
            WriteMeshIndicesBinary(pScene->mMeshes[i], ofs);
211
5.77k
        } else {
212
5.77k
            WriteMeshIndices(pScene->mMeshes[i], ofs);
213
5.77k
        }
214
11.5k
        ofs += pScene->mMeshes[i]->mNumVertices;
215
11.5k
    }
216
9.45k
}
217
218
// ------------------------------------------------------------------------------------------------
219
5.77k
void PlyExporter::WriteMeshVerts(const aiMesh* m, unsigned int components) {
220
5.77k
    static constexpr ai_real inf = std::numeric_limits<ai_real>::infinity();
221
222
    // If a component (for instance normal vectors) is present in at least one mesh in the scene,
223
    // then default values are written for meshes that do not contain this component.
224
510k
    for (unsigned int i = 0; i < m->mNumVertices; ++i) {
225
505k
        mOutput <<
226
505k
            m->mVertices[i].x << " " <<
227
505k
            m->mVertices[i].y << " " <<
228
505k
            m->mVertices[i].z;
229
505k
        if(components & PLY_EXPORT_HAS_NORMALS) {
230
503k
            if (m->HasNormals() && is_not_qnan(m->mNormals[i].x) && std::fabs(m->mNormals[i].x) != inf) {
231
486k
                mOutput <<
232
486k
                    " " << m->mNormals[i].x <<
233
486k
                    " " << m->mNormals[i].y <<
234
486k
                    " " << m->mNormals[i].z;
235
486k
            } else {
236
17.5k
                mOutput << " 0.0 0.0 0.0";
237
17.5k
            }
238
503k
        }
239
240
767k
        for (unsigned int n = PLY_EXPORT_HAS_TEXCOORDS, c = 0; (components & n) && c != AI_MAX_NUMBER_OF_TEXTURECOORDS; n <<= 1, ++c) {
241
261k
            if (m->HasTextureCoords(c)) {
242
245k
                if (m->mNumUVComponents[c] == 3) {
243
1.02k
                    mOutput <<
244
1.02k
                        " " << m->mTextureCoords[c][i].x <<
245
1.02k
                        " " << m->mTextureCoords[c][i].y <<
246
1.02k
                        " " << m->mTextureCoords[c][i].z;
247
244k
                } else if (m->mNumUVComponents[c] == 2) {
248
244k
                    mOutput <<
249
244k
                        " " << m->mTextureCoords[c][i].x <<
250
244k
                        " " << m->mTextureCoords[c][i].y;
251
244k
                } else {
252
0
                    throw DeadlyExportError("Invalid number of texture coordinates detected: " + std::to_string(m->mNumUVComponents[c]));
253
0
                }
254
245k
            } else {
255
16.0k
                mOutput << " -1.0 -1.0";
256
16.0k
            }
257
261k
        }
258
259
535k
        for (unsigned int n = PLY_EXPORT_HAS_COLORS, c = 0; (components & n) && c != AI_MAX_NUMBER_OF_COLOR_SETS; n <<= 1, ++c) {
260
30.0k
            if (m->HasVertexColors(c)) {
261
28.4k
                mOutput <<
262
28.4k
                    " " << (int)(m->mColors[c][i].r * 255) <<
263
28.4k
                    " " << (int)(m->mColors[c][i].g * 255) <<
264
28.4k
                    " " << (int)(m->mColors[c][i].b * 255) <<
265
28.4k
                    " " << (int)(m->mColors[c][i].a * 255);
266
28.4k
            } else {
267
1.60k
                mOutput << " 0 0 0";
268
1.60k
            }
269
30.0k
        }
270
271
505k
        if(components & PLY_EXPORT_HAS_TANGENTS_BITANGENTS) {
272
249k
            if (m->HasTangentsAndBitangents()) {
273
233k
                mOutput <<
274
233k
                    " " << m->mTangents[i].x <<
275
233k
                    " " << m->mTangents[i].y <<
276
233k
                    " " << m->mTangents[i].z <<
277
233k
                    " " << m->mBitangents[i].x <<
278
233k
                    " " << m->mBitangents[i].y <<
279
233k
                    " " << m->mBitangents[i].z;
280
233k
            } else {
281
16.1k
                mOutput << " 0.0 0.0 0.0 0.0 0.0 0.0";
282
16.1k
            }
283
249k
        }
284
285
505k
        mOutput << endl;
286
505k
    }
287
5.77k
}
288
289
// ------------------------------------------------------------------------------------------------
290
5.77k
void PlyExporter::WriteMeshVertsBinary(const aiMesh* m, unsigned int components) {
291
    // If a component (for instance normal vectors) is present in at least one mesh in the scene,
292
    // then default values are written for meshes that do not contain this component.
293
5.77k
    aiVector3D defaultNormal(0, 0, 0);
294
5.77k
    aiVector2D defaultUV(-1, -1);
295
5.77k
    aiColor4D defaultColor(-1, -1, -1, -1);
296
510k
    for (unsigned int i = 0; i < m->mNumVertices; ++i) {
297
505k
        mOutput.write(reinterpret_cast<const char*>(&m->mVertices[i].x), 12);
298
505k
        if (components & PLY_EXPORT_HAS_NORMALS) {
299
503k
            if (m->HasNormals()) {
300
498k
                mOutput.write(reinterpret_cast<const char*>(&m->mNormals[i].x), 12);
301
498k
            } else {
302
5.86k
                mOutput.write(reinterpret_cast<const char*>(&defaultNormal.x), 12);
303
5.86k
            }
304
503k
        }
305
306
767k
        for (unsigned int n = PLY_EXPORT_HAS_TEXCOORDS, c = 0; (components & n) && c != AI_MAX_NUMBER_OF_TEXTURECOORDS; n <<= 1, ++c) {
307
261k
            if (m->HasTextureCoords(c)) {
308
245k
                mOutput.write(reinterpret_cast<const char*>(&m->mTextureCoords[c][i].x), 8);
309
245k
            } else {
310
16.0k
                mOutput.write(reinterpret_cast<const char*>(&defaultUV.x), 8);
311
16.0k
            }
312
261k
        }
313
314
535k
        for (unsigned int n = PLY_EXPORT_HAS_COLORS, c = 0; (components & n) && c != AI_MAX_NUMBER_OF_COLOR_SETS; n <<= 1, ++c) {
315
30.0k
            if (m->HasVertexColors(c)) {
316
28.4k
                unsigned char rgba[4] = {
317
28.4k
                    static_cast<unsigned char>(m->mColors[c][i].r * 255),
318
28.4k
                    static_cast<unsigned char>(m->mColors[c][i].g * 255),
319
28.4k
                    static_cast<unsigned char>(m->mColors[c][i].b * 255),
320
28.4k
                    static_cast<unsigned char>(m->mColors[c][i].a * 255)
321
28.4k
                };
322
28.4k
                mOutput.write(reinterpret_cast<const char*>(&rgba), 4);
323
28.4k
            } else {
324
1.60k
                unsigned char rgba[4] = {
325
1.60k
                    static_cast<unsigned char>(defaultColor.r * 255),
326
1.60k
                    static_cast<unsigned char>(defaultColor.g * 255),
327
1.60k
                    static_cast<unsigned char>(defaultColor.b * 255),
328
1.60k
                    static_cast<unsigned char>(defaultColor.a * 255)
329
1.60k
                };
330
1.60k
                mOutput.write(reinterpret_cast<const char*>(&rgba), 4);
331
1.60k
            }
332
30.0k
        }
333
334
505k
        if (components & PLY_EXPORT_HAS_TANGENTS_BITANGENTS) {
335
249k
            if (m->HasTangentsAndBitangents()) {
336
233k
                mOutput.write(reinterpret_cast<const char*>(&m->mTangents[i].x), 12);
337
233k
                mOutput.write(reinterpret_cast<const char*>(&m->mBitangents[i].x), 12);
338
233k
            } else {
339
16.1k
                mOutput.write(reinterpret_cast<const char*>(&defaultNormal.x), 12);
340
16.1k
                mOutput.write(reinterpret_cast<const char*>(&defaultNormal.x), 12);
341
16.1k
            }
342
249k
        }
343
505k
    }
344
5.77k
}
345
346
// ------------------------------------------------------------------------------------------------
347
5.77k
void PlyExporter::WriteMeshIndices(const aiMesh* m, unsigned int offset) {
348
660k
    for (unsigned int i = 0; i < m->mNumFaces; ++i) {
349
654k
        const aiFace& f = m->mFaces[i];
350
654k
        mOutput << f.mNumIndices;
351
2.50M
        for(unsigned int c = 0; c < f.mNumIndices; ++c) {
352
1.84M
            mOutput << " " << (f.mIndices[c] + offset);
353
1.84M
        }
354
654k
        mOutput << endl;
355
654k
    }
356
5.77k
}
357
358
// ------------------------------------------------------------------------------------------------
359
// Generic method in case we want to use different data types for the indices or make this configurable.
360
template<typename NumIndicesType, typename IndexType>
361
5.77k
void WriteMeshIndicesBinary_Generic(const aiMesh* m, unsigned int offset, std::ostringstream& output) {
362
660k
    for (unsigned int i = 0; i < m->mNumFaces; ++i) {
363
654k
        const aiFace& f = m->mFaces[i];
364
654k
        NumIndicesType numIndices = static_cast<NumIndicesType>(f.mNumIndices);
365
654k
        output.write(reinterpret_cast<const char*>(&numIndices), sizeof(NumIndicesType));
366
2.50M
        for (unsigned int c = 0; c < f.mNumIndices; ++c) {
367
1.84M
            IndexType index = f.mIndices[c] + offset;
368
1.84M
            output.write(reinterpret_cast<const char*>(&index), sizeof(IndexType));
369
1.84M
        }
370
654k
    }
371
5.77k
}
372
373
// ------------------------------------------------------------------------------------------------
374
5.77k
void PlyExporter::WriteMeshIndicesBinary(const aiMesh* m, unsigned int offset) {
375
5.77k
    WriteMeshIndicesBinary_Generic<unsigned char, int>(m, offset, mOutput);
376
5.77k
}
377
378
} // end of namespace Assimp
379
380
#endif // !defined(ASSIMP_BUILD_NO_EXPORT) && !defined(ASSIMP_BUILD_NO_PLY_EXPORTER)