]> git.sur5r.net Git - fstl/blob - src/loader.cpp
New upstream version 0.9.4
[fstl] / src / loader.cpp
1 #include <future>
2
3 #include "loader.h"
4 #include "vertex.h"
5
6 Loader::Loader(QObject* parent, const QString& filename, bool is_reload)
7     : QThread(parent), filename(filename), is_reload(is_reload)
8 {
9     // Nothing to do here
10 }
11
12 void Loader::run()
13 {
14     Mesh* mesh = load_stl();
15     if (mesh)
16     {
17         if (mesh->empty())
18         {
19             emit error_empty_mesh();
20             delete mesh;
21         }
22         else
23         {
24             emit got_mesh(mesh, is_reload);
25             emit loaded_file(filename);
26         }
27     }
28 }
29
30 ////////////////////////////////////////////////////////////////////////////////
31
32 void parallel_sort(Vertex* begin, Vertex* end, int threads)
33 {
34     if (threads < 2 || end - begin < 2)
35     {
36         std::sort(begin, end);
37     }
38     else
39     {
40         const auto mid = begin + (end - begin) / 2;
41         if (threads == 2)
42         {
43             auto future = std::async(parallel_sort, begin, mid, threads / 2);
44             std::sort(mid, end);
45             future.wait();
46         }
47         else
48         {
49             auto a = std::async(std::launch::async, parallel_sort, begin, mid, threads / 2);
50             auto b = std::async(std::launch::async, parallel_sort, mid, end, threads / 2);
51             a.wait();
52             b.wait();
53         }
54         std::inplace_merge(begin, mid, end);
55     }
56 }
57
58 Mesh* mesh_from_verts(uint32_t tri_count, QVector<Vertex>& verts)
59 {
60     // Save indicies as the second element in the array
61     // (so that we can reconstruct triangle order after sorting)
62     for (size_t i=0; i < tri_count*3; ++i)
63     {
64         verts[i].i = i;
65     }
66
67     // Check how many threads the hardware can safely support. This may return
68     // 0 if the property can't be read so we shoud check for that too.
69     auto threads = std::thread::hardware_concurrency();
70     if (threads == 0)
71     {
72         threads = 8;
73     }
74
75     // Sort the set of vertices (to deduplicate)
76     parallel_sort(verts.begin(), verts.end(), threads);
77
78     // This vector will store triangles as sets of 3 indices
79     std::vector<GLuint> indices(tri_count*3);
80
81     // Go through the sorted vertex list, deduplicating and creating
82     // an indexed geometry representation for the triangles.
83     // Unique vertices are moved so that they occupy the first vertex_count
84     // positions in the verts array.
85     size_t vertex_count = 0;
86     for (auto v : verts)
87     {
88         if (!vertex_count || v != verts[vertex_count-1])
89         {
90             verts[vertex_count++] = v;
91         }
92         indices[v.i] = vertex_count - 1;
93     }
94     verts.resize(vertex_count);
95
96     std::vector<GLfloat> flat_verts;
97     flat_verts.reserve(vertex_count*3);
98     for (auto v : verts)
99     {
100         flat_verts.push_back(v.x);
101         flat_verts.push_back(v.y);
102         flat_verts.push_back(v.z);
103     }
104
105     return new Mesh(std::move(flat_verts), std::move(indices));
106 }
107
108 ////////////////////////////////////////////////////////////////////////////////
109
110 Mesh* Loader::load_stl()
111 {
112     QFile file(filename);
113     if (!file.open(QIODevice::ReadOnly))
114     {
115         emit error_missing_file();
116         return NULL;
117     }
118
119     // First, try to read the stl as an ASCII file
120     if (file.read(5) == "solid")
121     {
122         file.readLine(); // skip solid name
123         const auto line = file.readLine().trimmed();
124         if (line.startsWith("facet") ||
125             line.startsWith("endsolid"))
126         {
127             file.seek(0);
128             return read_stl_ascii(file);
129         }
130         confusing_stl = true;
131     }
132     else
133     {
134         confusing_stl = false;
135     }
136
137     // Otherwise, skip the rest of the header material and read as binary
138     file.seek(0);
139     return read_stl_binary(file);
140 }
141
142 Mesh* Loader::read_stl_binary(QFile& file)
143 {
144     QDataStream data(&file);
145     data.setByteOrder(QDataStream::LittleEndian);
146     data.setFloatingPointPrecision(QDataStream::SinglePrecision);
147
148     // Load the triangle count from the .stl file
149     file.seek(80);
150     uint32_t tri_count;
151     data >> tri_count;
152
153     // Verify that the file is the right size
154     if (file.size() != 84 + tri_count*50)
155     {
156         emit error_bad_stl();
157         return NULL;
158     }
159
160     // Extract vertices into an array of xyz, unsigned pairs
161     QVector<Vertex> verts(tri_count*3);
162
163     // Dummy array, because readRawData is faster than skipRawData
164     std::unique_ptr<uint8_t> buffer(new uint8_t[tri_count * 50]);
165     data.readRawData((char*)buffer.get(), tri_count * 50);
166
167     // Store vertices in the array, processing one triangle at a time.
168     auto b = buffer.get() + 3 * sizeof(float);
169     for (auto v=verts.begin(); v != verts.end(); v += 3)
170     {
171         // Load vertex data from .stl file into vertices
172         for (unsigned i=0; i < 3; ++i)
173         {
174             memcpy(&v[i], b, 3*sizeof(float));
175             b += 3 * sizeof(float);
176         }
177
178         // Skip face attribute and next face's normal vector
179         b += 3 * sizeof(float) + sizeof(uint16_t);
180     }
181
182     if (confusing_stl)
183     {
184         emit warning_confusing_stl();
185     }
186
187     return mesh_from_verts(tri_count, verts);
188 }
189
190 Mesh* Loader::read_stl_ascii(QFile& file)
191 {
192     file.readLine();
193     uint32_t tri_count = 0;
194     QVector<Vertex> verts(tri_count*3);
195
196     bool okay = true;
197     while (!file.atEnd() && okay)
198     {
199         const auto line = file.readLine().simplified();
200         if (line.startsWith("endsolid"))
201         {
202             break;
203         }
204         else if (!line.startsWith("facet normal") ||
205                  !file.readLine().simplified().startsWith("outer loop"))
206         {
207             okay = false;
208             break;
209         }
210
211         for (int i=0; i < 3; ++i)
212         {
213             auto line = file.readLine().simplified().split(' ');
214             if (line[0] != "vertex")
215             {
216                 okay = false;
217                 break;
218             }
219             const float x = line[1].toFloat(&okay);
220             const float y = line[2].toFloat(&okay);
221             const float z = line[3].toFloat(&okay);
222             verts.push_back(Vertex(x, y, z));
223         }
224         if (!file.readLine().trimmed().startsWith("endloop") ||
225             !file.readLine().trimmed().startsWith("endfacet"))
226         {
227             okay = false;
228             break;
229         }
230         tri_count++;
231     }
232
233     if (okay)
234     {
235         return mesh_from_verts(tri_count, verts);
236     }
237     else
238     {
239         emit error_bad_stl();
240         return NULL;
241     }
242 }
243