meshgeometry.cpp 14.8 KB
Newer Older
schultezub's avatar
schultezub committed
1
2
// ================================================================================================
// 
schultezub's avatar
schultezub committed
3
// This file is part of the CAMPVis Software Framework.
schultezub's avatar
schultezub committed
4
// 
5
// If not explicitly stated otherwise: Copyright (C) 2012-2014, all rights reserved,
schultezub's avatar
schultezub committed
6
//      Christian Schulte zu Berge <christian.szb@in.tum.de>
schultezub's avatar
schultezub committed
7
//      Chair for Computer Aided Medical Procedures
8
9
//      Technische Universitaet Muenchen
//      Boltzmannstr. 3, 85748 Garching b. Muenchen, Germany
10
// 
schultezub's avatar
schultezub committed
11
// For a full list of authors and contributors, please refer to the file "AUTHORS.txt".
schultezub's avatar
schultezub committed
12
// 
13
14
15
16
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 
// except in compliance with the License. You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
schultezub's avatar
schultezub committed
17
// 
18
19
20
21
// Unless required by applicable law or agreed to in writing, software distributed under the 
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
// either express or implied. See the License for the specific language governing permissions 
// and limitations under the License.
schultezub's avatar
schultezub committed
22
23
24
25
26
// 
// ================================================================================================

#include "meshgeometry.h"

27
28
29
30
#include "cgt/assert.h"
#include "cgt/logmanager.h"
#include "cgt/buffer.h"
#include "cgt/vertexarrayobject.h"
schultezub's avatar
schultezub committed
31

32
33
34
35
#include <algorithm>
#include <list>
#include <utility>

schultezub's avatar
schultezub committed
36
namespace campvis {
schultezub's avatar
schultezub committed
37

schultezub's avatar
schultezub committed
38
    const std::string MeshGeometry::loggerCat_ = "CAMPVis.core.datastructures.MeshGeometry";
schultezub's avatar
schultezub committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

    MeshGeometry::MeshGeometry(const std::vector<FaceGeometry>& faces)
        : GeometryData()
        , _faces(faces)
    {
    }

    MeshGeometry::~MeshGeometry() {

    }

    MeshGeometry* MeshGeometry::clone() const {
        return new MeshGeometry(_faces);
    }

54
55
56
57
58
    size_t MeshGeometry::getLocalMemoryFootprint() const {
        size_t sum = 0;
        for (std::vector<FaceGeometry>::const_iterator it = _faces.begin(); it != _faces.end(); ++it)
            sum += it->getLocalMemoryFootprint();

59
60
61
62
        for (size_t i = 0; i < NUM_BUFFERS; ++i) {
            if (_buffers[i] != nullptr)
                sum += sizeof(tgt::BufferObject);
        }
63
64
65
66

        return sizeof(*this) + sum;
    }

schultezub's avatar
schultezub committed
67
68
69
70
71
72
73
74
75
    size_t MeshGeometry::size() const {
        return _faces.size();
    }

    const std::vector<FaceGeometry>& MeshGeometry::getFaces() const {
        return _faces;
    }


76
    void MeshGeometry::render(GLenum mode) const {
77
78
79
        if (_faces.empty())
            return;

schultezub's avatar
schultezub committed
80
        createGLBuffers();
81
        if (_buffersDirty) {
schultezub's avatar
schultezub committed
82
83
84
85
86
87
            LERROR("Cannot render without initialized OpenGL buffers.");
            return;
        }

        tgt::VertexArrayObject vao;
        if (_verticesBuffer)
88
            vao.setVertexAttributePointer(0, _verticesBuffer);
schultezub's avatar
schultezub committed
89
        if (_texCoordsBuffer)
90
            vao.setVertexAttributePointer(1, _texCoordsBuffer);
schultezub's avatar
schultezub committed
91
        if (_colorsBuffer)
92
            vao.setVertexAttributePointer(2, _colorsBuffer);
schultezub's avatar
schultezub committed
93
        if (_normalsBuffer)
94
            vao.setVertexAttributePointer(3, _normalsBuffer);
95
96
        if (_pickingBuffer)
            vao.setVertexAttributePointer(4, _pickingBuffer);
schultezub's avatar
schultezub committed
97
98
        LGL_ERROR;

99
        GLint startIndex = 0;
schultezub's avatar
schultezub committed
100
        for (std::vector<FaceGeometry>::const_iterator it = _faces.begin(); it != _faces.end(); ++it) {
101
            GLsizei numVertices = static_cast<GLsizei>(it->getVertices().size());
schultezub's avatar
schultezub committed
102
            if (numVertices > 2)
103
                glDrawArrays(mode, startIndex, numVertices);
schultezub's avatar
schultezub committed
104
105
106
107
108
109
110
            else
                glDrawArrays(GL_LINES, startIndex, numVertices);
            startIndex += numVertices;
        }
        LGL_ERROR;
    }

111
    void MeshGeometry::createGLBuffers() const {
112
113
        if (_buffersDirty) {
            deleteBuffers();
114

schultezub's avatar
schultezub committed
115
116
117
            bool createTexCoordsBuffer = true;
            bool createColorsBuffer = true;
            bool createNormalsBuffer = true;
118
            bool createPickingBuffer = true;
schultezub's avatar
schultezub committed
119
120
121
122
123
124
125
126
127

            size_t totalVertices = 0;
            // Check which buffers are to create. Meanwhile calculate the total number of vertices:
            for (std::vector<FaceGeometry>::const_iterator it = _faces.begin(); it != _faces.end(); ++it) {
                totalVertices += it->getVertices().size();

                createTexCoordsBuffer &= !(it->getTextureCoordinates().empty());
                createColorsBuffer &= !(it->getColors().empty());
                createNormalsBuffer &= !(it->getNormals().empty());
128
                createPickingBuffer &= !(it->getPickingInformation().empty());
schultezub's avatar
schultezub committed
129

schultezub's avatar
schultezub committed
130
#ifdef CAMPVIS_DEBUG
schultezub's avatar
schultezub committed
131
                if (!createTexCoordsBuffer && !(it->getTextureCoordinates().empty()))
132
                    LWARNING("Presence of texture coordinates in faces not consistent, not generating texture coordinates VBO!");
schultezub's avatar
schultezub committed
133
                if (!createColorsBuffer && !(it->getColors().empty()))
134
                    LWARNING("Presence of colors in faces not consistent, not generating colors VBO!");
schultezub's avatar
schultezub committed
135
                if (!createNormalsBuffer && !(it->getNormals().empty()))
136
                    LWARNING("Presence of normals in faces not consistent, not generating normals VBO!");
137
138
                if (!createPickingBuffer && !(it->getPickingInformation().empty()))
                    LWARNING("Presence of picking information in faces not consistent, not generating normals VBO!");
schultezub's avatar
schultezub committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#endif
            }

            try {
                // Now, create all necessary VBOs and reserve data
                _verticesBuffer = new tgt::BufferObject(tgt::BufferObject::ARRAY_BUFFER, tgt::BufferObject::USAGE_STATIC_DRAW);
                _verticesBuffer->data(0, totalVertices * sizeof(tgt::vec3), tgt::BufferObject::FLOAT, 3);

                if (createTexCoordsBuffer) {
                    _texCoordsBuffer = new tgt::BufferObject(tgt::BufferObject::ARRAY_BUFFER, tgt::BufferObject::USAGE_STATIC_DRAW);
                    _texCoordsBuffer->data(0, totalVertices * sizeof(tgt::vec3), tgt::BufferObject::FLOAT, 3);
                }
                if (createColorsBuffer) {
                    _colorsBuffer = new tgt::BufferObject(tgt::BufferObject::ARRAY_BUFFER, tgt::BufferObject::USAGE_STATIC_DRAW);
                    _colorsBuffer->data(0, totalVertices * sizeof(tgt::vec4), tgt::BufferObject::FLOAT, 4);
                }
                if (createNormalsBuffer) {
                    _normalsBuffer = new tgt::BufferObject(tgt::BufferObject::ARRAY_BUFFER, tgt::BufferObject::USAGE_STATIC_DRAW);
                    _normalsBuffer->data(0, totalVertices * sizeof(tgt::vec3), tgt::BufferObject::FLOAT, 3);
                }
159
160
161
162
                if (createPickingBuffer) {
                    _pickingBuffer = new tgt::BufferObject(tgt::BufferObject::ARRAY_BUFFER, tgt::BufferObject::USAGE_STATIC_DRAW);
                    _pickingBuffer->data(0, totalVertices * sizeof(tgt::vec4), tgt::BufferObject::FLOAT, 4);
                }
schultezub's avatar
schultezub committed
163
164
165
166
167

                // Now start filling the VBOs with data, one face at a time...
                size_t startIndex = 0;
                for (std::vector<FaceGeometry>::const_iterator it = _faces.begin(); it != _faces.end(); ++it) {
                    size_t numVertices = it->getVertices().size();
168
169
                    if (numVertices == 0)
                        continue;
schultezub's avatar
schultezub committed
170
171
172
173
174
175

                    _verticesBuffer->subdata(startIndex * sizeof(tgt::vec3), &(it->getVertices().front()), numVertices * sizeof(tgt::vec3));

                    if (createTexCoordsBuffer)
                        _texCoordsBuffer->subdata(startIndex * sizeof(tgt::vec3), &(it->getTextureCoordinates().front()), numVertices * sizeof(tgt::vec3));
                    if (createColorsBuffer)
176
                        _colorsBuffer->subdata(startIndex * sizeof(tgt::vec4), &(it->getColors().front()), numVertices * sizeof(tgt::vec4));
schultezub's avatar
schultezub committed
177
                    if (createNormalsBuffer)
178
                        _normalsBuffer->subdata(startIndex * sizeof(tgt::vec3), &(it->getNormals().front()), numVertices * sizeof(tgt::vec3));
179
180
                    if (createPickingBuffer)
                        _pickingBuffer->subdata(startIndex * sizeof(tgt::vec4), &(it->getPickingInformation().front()), numVertices * sizeof(tgt::vec4));
schultezub's avatar
schultezub committed
181
182
183
184
185
186
187
                
                    startIndex += numVertices;
                }

            }
            catch (tgt::Exception& e) {
                LERROR("Error creating OpenGL Buffer objects: " << e.what());
188
                _buffersDirty = true;
schultezub's avatar
schultezub committed
189
190
191
192
                return;
            }

            LGL_ERROR;
193
            _buffersDirty = false;
schultezub's avatar
schultezub committed
194
195
196
        }
    }

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
    namespace {
        float distanceToPlane(const tgt::vec3& vertex, float p, const tgt::vec3& pNormal, float epsilon) {
            float distance = tgt::dot(pNormal, vertex) - p;
            if (std::abs(distance) <= epsilon)
                return 0;
            else
                return distance;
        }

        struct VertexComparerEquals {
            VertexComparerEquals(const std::vector<FaceGeometry>& ref, float epsilon)
                : _ref(ref)
                , _epsilon(epsilon)
            {

            };

            bool operator() (const std::pair<size_t, size_t>& left, const std::pair<size_t, size_t>& right) const {
                return (tgt::distance(_ref[left.first].getVertices()[left.second], _ref[right.first].getVertices()[right.second]) < _epsilon);
            };

            const tgt::vec3& operator() (const std::pair<size_t, size_t>& index) const {
                return _ref[index.first].getVertices()[index.second];
            }

            const std::vector<FaceGeometry>& _ref;
            float _epsilon;
        };
    }

    MeshGeometry MeshGeometry::clipAgainstPlane(float p, const tgt::vec3& normal, bool close /*= true*/, float epsilon /*= 1e-8f*/) const {
        std::vector<FaceGeometry> tmp;
        for (std::vector<FaceGeometry>::const_iterator it = _faces.begin(); it != _faces.end(); ++it) {
            FaceGeometry f = it->clipAgainstPlane(p, normal, epsilon);
            if (f.size() > 0)
                tmp.push_back(f);
        }

        if (close) {
            typedef std::pair<size_t, size_t> Vertex;
            std::list< std::pair<Vertex, Vertex> > unsortedEdges;
            std::list< Vertex > sortedVertices;

            // find all edges lying on clip plane
            for (size_t i = 0; i < tmp.size(); ++i) {
                const FaceGeometry& f = tmp[i];
                for (size_t j = 0; j < f.size(); ++j) {
                    if (    distanceToPlane(f.getVertices()[j], p, normal, epsilon) == 0
                         && distanceToPlane(f.getVertices()[(j+1) % f.size()], p, normal, epsilon) == 0)
                    {
                        unsortedEdges.push_back(std::make_pair(std::make_pair(i, j), std::make_pair(i, (j+1) % f.size())));
                        ++j;
                    }
                }
            }

            if (! unsortedEdges.empty()) {
                // sort edges into sortedVertices list
                VertexComparerEquals vce(tmp, epsilon);
                sortedVertices.push_back(unsortedEdges.front().second);
                unsortedEdges.pop_front();
                while (! unsortedEdges.empty()) {
                    bool didWork = false;

                    // look for the edge that has one vertex in common with the last added sorted vertex
                    for (std::list< std::pair<Vertex, Vertex> >::iterator it = unsortedEdges.begin(); it != unsortedEdges.end(); ++it) {
                        if (vce(sortedVertices.back(), it->first)) {
                            sortedVertices.push_back(it->second);
                            unsortedEdges.erase(it);
                            didWork = true;
                            break;
                        }
                        if (vce(sortedVertices.back(), it->second)) {
                            sortedVertices.push_back(it->first);
                            unsortedEdges.erase(it);
                            didWork = true;
                            break;
                        }
                    }

                    // emergency break...
                    if (! didWork)
                        break;
                }

                if (sortedVertices.size() > 2) {
                    // make face ccw
                    tgt::vec3 closingFaceNormal = tgt::normalize(tgt::cross(vce(sortedVertices.front()), vce(*(++sortedVertices.begin()))));

                    if (tgt::dot(normal, closingFaceNormal) < 0)
                        std::reverse(sortedVertices.begin(), sortedVertices.end());
                }

                // build face
                std::vector<tgt::vec3> verts, texCoords, norms;
                std::vector<tgt::vec4> cols;
293
                std::vector<tgt::col4> picks;
294
295
296
297
298
299
300
301
302

                for (std::list< Vertex >::iterator it = sortedVertices.begin(); it != sortedVertices.end(); ++it) {
                    verts.push_back(tmp[it->first].getVertices()[it->second]);
                    if (! tmp[it->first].getTextureCoordinates().empty())
                        texCoords.push_back(tmp[it->first].getTextureCoordinates()[it->second]);
                    if (! tmp[it->first].getColors().empty())
                        cols.push_back(tmp[it->first].getColors()[it->second]);
                    if (! tmp[it->first].getNormals().empty())
                        norms.push_back(tmp[it->first].getNormals()[it->second]);
303
304
                    if (! tmp[it->first].getPickingInformation().empty())
                        picks.push_back(tmp[it->first].getPickingInformation()[it->second]);
305
306
                }
                tmp.push_back(FaceGeometry(verts, texCoords, cols, norms));
307
                tmp.back().setPickingInformation(picks);
308
309
310
311
            }
        }

        return MeshGeometry(tmp);
schultezub's avatar
schultezub committed
312
313
    }

314
315
316
317
318
319
320
321
    tgt::Bounds MeshGeometry::getWorldBounds() const {
        tgt::Bounds toReturn;
        for (size_t i = 0; i < _faces.size(); ++i)
            for (std::vector<tgt::vec3>::const_iterator it = _faces[i].getVertices().begin(); it != _faces[i].getVertices().end(); ++it)
                toReturn.addPoint(*it);
        return toReturn;
    }

322
323
324
325
326
327
328
329
    bool MeshGeometry::hasTextureCoordinates() const {
        bool toReturn = true;
        for (size_t i = 0; i < _faces.size(); ++i) {
            toReturn &= _faces[i].hasTextureCoordinates();
        }
        return toReturn;
    }

330
331
332
333
334
335
336
337
    bool MeshGeometry::hasPickingInformation() const {
        bool toReturn = true;
        for (size_t i = 0; i < _faces.size(); ++i) {
            toReturn &= _faces[i].hasPickingInformation();
        }
        return toReturn;
    }

338
339
340
341
342
343
    void MeshGeometry::applyTransformationToVertices(const tgt::mat4& t) {
        for (size_t i = 0; i < _faces.size(); ++i) {
            _faces[i].applyTransformationToVertices(t);
        }
    }

schultezub's avatar
schultezub committed
344
}