Debian Codegraph @

avogadro/rendering/arrowgeometry.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "arrowgeometry.h"
7
8 #include "avogadrogl.h"
9 #include "bufferobject.h"
10 #include "camera.h"
11 #include "packedvertex.h"
12 #include "scene.h"
13 #include "shader.h"
14 #include "shaderprogram.h"
15 #include "vertexarrayobject.h"
16 #include "visitor.h"
17
18 #include <avogadro/core/matrix.h>
19 #include <avogadro/core/vector.h>
20
21 #include <Eigen/Geometry>
22
23 #include <cmath>
24 #include <iostream>
25 #include <limits>
26
27 namespace {
28 // Use the mesh shaders for proper lighting
29 #include "mesh_fs.h"
30 #include "mesh_vs.h"
31
32 const float M_PI_F = 3.14159265358979323846f;
33 } // namespace
34
35 using Avogadro::FloatType;
36 using Avogadro::UCharType;
37 using Avogadro::Vector3f;
38 using Avogadro::Vector3ub;
39 using Avogadro::Vector4ub;
40 using Avogadro::Rendering::PackedVertex;
41 using Avogadro::Rendering::ShaderProgram;
42
43 using std::cout;
44 using std::endl;
45
46 namespace Avogadro::Rendering {
47
48 class ArrowGeometry::Private
49 {
50 public:
51 Private() : numberOfVertices(0), numberOfIndices(0) {}
52
53 BufferObject vbo;
54 BufferObject ibo;
55 VertexArrayObject vao;
56
57 inline static Shader* vertexShader = nullptr;
58 inline static Shader* fragmentShader = nullptr;
59 inline static ShaderProgram* program = nullptr;
60
61 Core::Array<PackedVertex> meshVertices;
62 Core::Array<unsigned int> meshIndices;
63
64 size_t numberOfVertices;
65 size_t numberOfIndices;
66 };
67
68 ArrowGeometry::ArrowGeometry()
69 : m_color(0, 255, 0), m_radiusScale(1.0f), m_dirty(false), d(new Private)
70 {
71 }
72
73 ArrowGeometry::ArrowGeometry(const ArrowGeometry& other)
74 : Drawable(other), m_arrows(other.m_arrows), m_color(other.m_color),
75 m_radiusScale(other.m_radiusScale), m_dirty(true), d(new Private)
76 {
77 }
78
79 ArrowGeometry::~ArrowGeometry()
80 {
81 delete d;
82 }
83
84 void ArrowGeometry::accept(Visitor& visitor)
85 {
86 visitor.visit(*this);
87 }
88
89 namespace {
90
91 /**
92 * Generate arrow geometry (cylinder shaft + cone head) for a single arrow.
93 * Adapted from overlayaxes plugin.
94 *
95 * @param origin Start point of the arrow
96 * @param target End point of the arrow (tip of arrowhead)
97 * @param color The arrow color
98 * @param radiusScale Scale factor for arrow radii (1.0 = default)
99 * @param vertices Output vertex array
100 * @param indices Output index array
101 * @param baseOffset Starting index offset for this arrow's vertices
102 */
103 void generateArrowGeometry(const Vector3f& origin, const Vector3f& target,
104 const Vector4ub& color, float radiusScale,
105 Core::Array<PackedVertex>& vertices,
106 Core::Array<unsigned int>& indices,
107 unsigned int baseOffset)
108 {
109 Vector3f arrowVec = target - origin;
110 float totalLength = arrowVec.norm();
111 if (totalLength < 1e-6f)
112 return;
113
114 Vector3f axis = arrowVec.normalized();
115
116 // Number of angular samples for cylinder/cone
117 const unsigned int res = 12;
118 const auto resf = static_cast<float>(res);
119
120 // Proportions: 80% cylinder, 20% cone head
121 const float cylLength = totalLength * 0.8f;
122 const float coneLength = totalLength * 0.2f;
123
124 // Radii proportional to arrow length, with optional scale factor
125 const float cylRadius = totalLength * 0.02f * radiusScale;
126 const float coneRadius = totalLength * 0.05f * radiusScale;
127
128 // Key vectors
129 const Vector3f cylEnd = origin + axis * cylLength;
130 const Vector3f radialUnit = axis.unitOrthogonal();
131
132 // Index offsets within this arrow's vertex set
133 const unsigned int coneBaseOffset = 0;
134 const unsigned int coneBaseRadialsOffset = coneBaseOffset + 1;
135 const unsigned int coneSideRadialsOffset = coneBaseRadialsOffset + res;
136 const unsigned int coneTipsOffset = coneSideRadialsOffset + res;
137 const unsigned int cylBaseRadialsOffset = coneTipsOffset + res;
138 const unsigned int cylTopRadialsOffset = cylBaseRadialsOffset + res;
139 const unsigned int numVertices = cylTopRadialsOffset + res;
140
141 // Allocate temporary vertex/normal arrays
142 Core::Array<Vector3f> verts(numVertices);
143 Core::Array<Vector3f> norms(numVertices);
144
145 // Cone base center point
146 verts[coneBaseOffset] = cylEnd;
147 norms[coneBaseOffset] = -axis;
148
149 // Create radial transform for stepping around the circle
150 Eigen::Affine3f xform(Eigen::AngleAxisf(2.f * M_PI_F / resf, axis));
151 Vector3f radial = radialUnit;
152
153 // Build vertex list
154 for (unsigned int i = 0; i < res; ++i) {
155 Vector3f coneRadial = cylEnd + (radial * coneRadius);
156
157 // Cone side normal calculation
158 Vector3f coneVec = axis * coneLength;
159 Vector3f coneSideNormal = -(coneVec.cross(radial * coneRadius))
160 .cross(coneVec - radial * coneRadius)
161 .normalized();
162
163 // Cone base radials (facing back)
164 verts[coneBaseRadialsOffset + i] = coneRadial;
165 norms[coneBaseRadialsOffset + i] = -axis;
166
167 // Cone side radials
168 verts[coneSideRadialsOffset + i] = coneRadial;
169 norms[coneSideRadialsOffset + i] = coneSideNormal;
170
171 // Cylinder vertices
172 Vector3f cylRadial = radial * cylRadius;
173 verts[cylBaseRadialsOffset + i] = origin + cylRadial;
174 norms[cylBaseRadialsOffset + i] = radial;
175
176 verts[cylTopRadialsOffset + i] = cylEnd + cylRadial;
177 norms[cylTopRadialsOffset + i] = radial;
178
179 radial = xform * radial;
180 }
181
182 // Cone tip normals (average of adjacent side normals)
183 for (unsigned int i = 0; i < res; ++i) {
184 unsigned int ind1 = coneSideRadialsOffset + i;
185 unsigned int ind2 = coneSideRadialsOffset + ((i + 1) % res);
186 verts[coneTipsOffset + i] = target;
187 norms[coneTipsOffset + i] = (norms[ind1] + norms[ind2]).normalized();
188 }
189
190 // Add vertices to output array
191 size_t vertexStart = vertices.size();
192 for (unsigned int i = 0; i < numVertices; ++i) {
193 vertices.push_back(PackedVertex(color, norms[i], verts[i]));
194 }
195
196 // Build triangle indices
197 for (unsigned int i = 0; i < res; ++i) {
198 unsigned int i2 = (i + 1) % res;
199
200 // Cone sides
201 indices.push_back(baseOffset + coneTipsOffset + i);
202 indices.push_back(baseOffset + coneSideRadialsOffset + i);
203 indices.push_back(baseOffset + coneSideRadialsOffset + i2);
204
205 // Cone base
206 indices.push_back(baseOffset + coneBaseRadialsOffset + i);
207 indices.push_back(baseOffset + coneBaseOffset);
208 indices.push_back(baseOffset + coneBaseRadialsOffset + i2);
209
210 // Cylinder side quad (2 triangles)
211 indices.push_back(baseOffset + cylTopRadialsOffset + i);
212 indices.push_back(baseOffset + cylBaseRadialsOffset + i);
213 indices.push_back(baseOffset + cylTopRadialsOffset + i2);
214
215 indices.push_back(baseOffset + cylBaseRadialsOffset + i);
216 indices.push_back(baseOffset + cylTopRadialsOffset + i2);
217 indices.push_back(baseOffset + cylBaseRadialsOffset + i2);
218 }
219 }
220
221 } // anonymous namespace
222
223 void ArrowGeometry::update()
224 {
225 if (m_arrows.empty())
226 return;
227
228 // Build and link the shader if it has not been used yet.
229 // Must be done before VAO setup since we need the program for attribute
230 // setup.
231 if (d->vertexShader == nullptr) {
232 d->vertexShader = new Shader;
233 d->vertexShader->setType(Shader::Vertex);
234 d->vertexShader->setSource(mesh_vs);
235
236 d->fragmentShader = new Shader;
237 d->fragmentShader->setType(Shader::Fragment);
238 d->fragmentShader->setSource(mesh_fs);
239
240 if (!d->vertexShader->compile())
241 cout << d->vertexShader->error() << endl;
242 if (!d->fragmentShader->compile())
243 cout << d->fragmentShader->error() << endl;
244
245 if (d->program == nullptr)
246 d->program = new ShaderProgram;
247 d->program->attachShader(*d->vertexShader);
248 d->program->attachShader(*d->fragmentShader);
249 if (!d->program->link())
250 cout << d->program->error() << endl;
251 }
252
253 // Rebuild mesh geometry if dirty
254 if (!d->vbo.ready() || m_dirty) {
255 d->meshVertices.clear();
256 d->meshIndices.clear();
257
258 // Number of vertices per arrow (see generateArrowGeometry)
259 const unsigned int res = 12;
260 const unsigned int vertsPerArrow = 1 + res * 5; // cone base + 5 rings
261
262 // Reserve space for all arrows
263 d->meshVertices.reserve(m_arrows.size() * vertsPerArrow);
264 d->meshIndices.reserve(m_arrows.size() * res * 4 * 3); // 4 tris * 3 indices
265
266 unsigned int baseOffset = 0;
267 for (const auto& arrow : m_arrows) {
268 Vector4ub color4(arrow.color[0], arrow.color[1], arrow.color[2], 255);
269 generateArrowGeometry(arrow.start, arrow.end, color4, m_radiusScale,
270 d->meshVertices, d->meshIndices, baseOffset);
271 baseOffset = static_cast<unsigned int>(d->meshVertices.size());
272 }
273
274 // Upload to GPU
275 if (!d->meshVertices.empty()) {
276 d->vbo.upload(d->meshVertices, BufferObject::ArrayBuffer);
277 d->ibo.upload(d->meshIndices, BufferObject::ElementArrayBuffer);
278
279 // Set up VAO with vertex attribute bindings (OpenGL 4.0 core profile)
280 d->vao.bind();
281 d->vbo.bind();
282 d->ibo.bind();
283
284 ShaderProgram* program = d->program;
285 if (!program->enableAttributeArray("vertex"))
286 cout << program->error() << endl;
287 if (!program->useAttributeArray("vertex", PackedVertex::vertexOffset(),
288 sizeof(PackedVertex), FloatType, 3,
289 ShaderProgram::NoNormalize)) {
290 cout << program->error() << endl;
291 }
292 if (!program->enableAttributeArray("color"))
293 cout << program->error() << endl;
294 if (!program->useAttributeArray("color", PackedVertex::colorOffset(),
295 sizeof(PackedVertex), UCharType, 4,
296 ShaderProgram::Normalize)) {
297 cout << program->error() << endl;
298 }
299 if (!program->enableAttributeArray("normal"))
300 cout << program->error() << endl;
301 if (!program->useAttributeArray("normal", PackedVertex::normalOffset(),
302 sizeof(PackedVertex), FloatType, 3,
303 ShaderProgram::NoNormalize)) {
304 cout << program->error() << endl;
305 }
306
307 d->vao.release();
308 }
309 // update these even if empty (i.e. avoid stale data)
310 d->numberOfVertices = d->meshVertices.size();
311 d->numberOfIndices = d->meshIndices.size();
312
313 m_dirty = false;
314 }
315 }
316
317 void ArrowGeometry::render(const Camera& camera)
318 {
319 if (m_arrows.empty())
320 return;
321
322 // Prepare the VBOs, IBOs, VAO, and shader program if necessary.
323 update();
324
325 if (d->numberOfVertices == 0 || d->numberOfIndices == 0)
326 return;
327
328 ShaderProgram* program = d->program;
329
330 if (!program->bind())
331 cout << program->error() << endl;
332
333 // Bind the VAO (captures all vertex attribute state)
334 d->vao.bind();
335
336 // Set up our uniforms (model-view and projection matrices right now).
337 if (!program->setUniformValue("modelView", camera.modelView().matrix())) {
338 cout << program->error() << endl;
339 }
340 if (!program->setUniformValue("projection", camera.projection().matrix())) {
341 cout << program->error() << endl;
342 }
343 Matrix3f normalMatrix = camera.modelView().linear().inverse().transpose();
344 if (!program->setUniformValue("normalMatrix", normalMatrix))
345 cout << program->error() << endl;
346
347 // Render using the shader and VAO.
348 glDrawRangeElements(GL_TRIANGLES, 0,
349 static_cast<GLuint>(d->numberOfVertices - 1),
350 static_cast<GLsizei>(d->numberOfIndices), GL_UNSIGNED_INT,
351 reinterpret_cast<const GLvoid*>(0));
352
353 d->vao.release();
354 program->release();
355 }
356
357 void ArrowGeometry::clear()
358 {
359 m_arrows.clear();
360 d->meshVertices.clear();
361 d->meshIndices.clear();
362 m_dirty = true;
363 }
364
365 void ArrowGeometry::addSingleArrow(const Vector3f& pos1, const Vector3f& pos2,
366 const Vector3ub& color)
367 {
368 m_arrows.push_back(Arrow(pos1, pos2, color));
369 m_dirty = true;
370 }
371
372 void ArrowGeometry::addSingleArrow(const Vector3f& pos1, const Vector3f& pos2)
373 {
374 addSingleArrow(pos1, pos2, m_color);
375 }
376
377 } // namespace Avogadro::Rendering