summaryrefslogtreecommitdiff
path: root/src/QGLView.cc
blob: 4a17dd1a8f09729d0a0b2db690345d79d38e9ef7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*
 *  OpenSCAD (www.openscad.org)
 *  Copyright (C) 2009-2011 Clifford Wolf <clifford@clifford.at> and
 *                          Marius Kintel <marius@kintel.net>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  As a special exception, you have permission to link this program
 *  with the CGAL library and distribute executables, as long as you
 *  follow the requirements of the GNU GPL in regard to all of the
 *  software in the executable aside from CGAL.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include "QGLView.h"
#include "Preferences.h"
#include "renderer.h"
#include "rendersettings.h"
#include "linalg.h"

#include <QApplication>
#include <QWheelEvent>
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QMouseEvent>
#include <QMessageBox>
#include <QPushButton>
#include <QSettings>
#include <QTimer>
#include <QTextEdit>
#include <QVBoxLayout>
#include <QErrorMessage>
#include "OpenCSGWarningDialog.h"

#include "mathc99.h"
#include <stdio.h>

#ifdef ENABLE_OPENCSG
#  include <opencsg.h>
#endif

QGLView::QGLView(QWidget *parent) : QGLWidget(parent)
{
  init();
}

QGLView::QGLView(const QGLFormat & format, QWidget *parent) : QGLWidget(format, parent)
{
  init();
}

static bool running_under_wine = false;

void QGLView::init()
{
  this->object_rot << 35, 0, -25;

  this->mouse_drag_active = false;
  this->statusLabel = NULL;

  setMouseTracking(true);

// see paintGL() + issue160 + wine FAQ
#ifdef _WIN32
#include <windows.h>
  HMODULE hntdll = GetModuleHandle(L"ntdll.dll");
  if (hntdll)
    if ( (void *)GetProcAddress(hntdll, "wine_get_version") )
      running_under_wine = true;
#endif
}

void QGLView::initializeGL()
{
  GLenum err = glewInit();
  if (GLEW_OK != err) {
    fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
  }
	GLView::initializeGL();
}

std::string QGLView::getRendererInfo() const
{
  std::string glewinfo = glew_dump();
  std::string glextlist = glew_extensions_dump();
  return glewinfo + std::string("\nUsing QGLWidget\n\n") + glextlist;
}

#ifdef ENABLE_OPENCSG
void QGLView::display_opencsg_warning()
{
    if (Preferences::inst()->getValue("advanced/opencsg_show_warning").toBool()) {
      QTimer::singleShot(0, this, SLOT(display_opencsg_warning_dialog()));
    }
}

void QGLView::display_opencsg_warning_dialog()
{
  OpenCSGWarningDialog *dialog = new OpenCSGWarningDialog(this);

  QString message;
  if (this->is_opencsg_capable) {
    message += "Warning: You may experience OpenCSG rendering errors.\n\n";
  }
  else {
    message += "Warning: Missing OpenGL capabilities for OpenCSG - OpenCSG has been disabled.\n\n";
    dialog->enableOpenCSGBox->hide();
  }
  message += "It is highly recommended to use OpenSCAD on a system with "
    "OpenGL 2.0 or later.\n"
    "Your renderer information is as follows:\n";
  QString rendererinfo;
  rendererinfo.sprintf("GLEW version %s\n"
                       "%s (%s)\n"
                       "OpenGL version %s\n",
                       glewGetString(GLEW_VERSION),
                       glGetString(GL_RENDERER), glGetString(GL_VENDOR),
                       glGetString(GL_VERSION));
  message += rendererinfo;

  dialog->setText(message);
  dialog->enableOpenCSGBox->setChecked(Preferences::inst()->getValue("advanced/enable_opencsg_opengl1x").toBool());
  dialog->exec();

  opencsg_support = this->is_opencsg_capable && Preferences::inst()->getValue("advanced/enable_opencsg_opengl1x").toBool();
}
#endif

void QGLView::resizeGL(int w, int h)
{
  GLView::resizeGL(w,h);
  GLView::setupGimbalPerspective();
}

void QGLView::paintGL()
{
  glEnable(GL_LIGHTING);

  if (orthomode) GLView::setupGimbalOrtho(viewer_distance);
  else GLView::setupGimbalPerspective();

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  Color4f bgcol = RenderSettings::inst()->color(RenderSettings::BACKGROUND_COLOR);
  glClearColor(bgcol[0], bgcol[1], bgcol[2], 0.0);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

  glRotated(object_rot.x(), 1.0, 0.0, 0.0);
  glRotated(object_rot.y(), 0.0, 1.0, 0.0);
  glRotated(object_rot.z(), 0.0, 0.0, 1.0);

  // FIXME: Crosshairs and axes are lighted, this doesn't make sense and causes them
  // to change color based on view orientation.
  if (showcrosshairs)
  {
    glLineWidth(3);
    Color4f col = RenderSettings::inst()->color(RenderSettings::CROSSHAIR_COLOR);
    glColor3f(col[0], col[1], col[2]);
    glBegin(GL_LINES);
    for (double xf = -1; xf <= +1; xf += 2)
    for (double yf = -1; yf <= +1; yf += 2) {
      double vd = viewer_distance/20;
      glVertex3d(-xf*vd, -yf*vd, -vd);
      glVertex3d(+xf*vd, +yf*vd, +vd);
    }
    glEnd();
  }

  glTranslated(object_trans.x(), object_trans.y(), object_trans.z());

  // Large gray axis cross inline with the model
  // FIXME: This is always gray - adjust color to keep contrast with background
  if (showaxes)
  {
    glLineWidth(1);
    glColor3d(0.5, 0.5, 0.5);
    glBegin(GL_LINES);
    double l = viewer_distance/10;
    glVertex3d(-l, 0, 0);
    glVertex3d(+l, 0, 0);
    glVertex3d(0, -l, 0);
    glVertex3d(0, +l, 0);
    glVertex3d(0, 0, -l);
    glVertex3d(0, 0, +l);
    glEnd();
  }

  glDepthFunc(GL_LESS);
  glCullFace(GL_BACK);
  glDisable(GL_CULL_FACE);

  glLineWidth(2);
  glColor3d(1.0, 0.0, 0.0);

  if (this->renderer) {
#if defined(ENABLE_MDI) && defined(ENABLE_OPENCSG)
    // FIXME: This belongs in the OpenCSG renderer, but it doesn't know about this ID yet
    OpenCSG::setContext(this->opencsg_id);
#endif
    this->renderer->draw(showfaces, showedges);
  }

  // Small axis cross in the lower left corner
  if (showaxes)
  {
    glDepthFunc(GL_ALWAYS);

    GLView::setupGimbalOrtho(1000,true);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotated(object_rot.x(), 1.0, 0.0, 0.0);
    glRotated(object_rot.y(), 0.0, 1.0, 0.0);
    glRotated(object_rot.z(), 0.0, 0.0, 1.0);

    glLineWidth(1);
    glBegin(GL_LINES);
    glColor3d(1.0, 0.0, 0.0);
    glVertex3d(0, 0, 0); glVertex3d(10, 0, 0);
    glColor3d(0.0, 1.0, 0.0);
    glVertex3d(0, 0, 0); glVertex3d(0, 10, 0);
    glColor3d(0.0, 0.0, 1.0);
    glVertex3d(0, 0, 0); glVertex3d(0, 0, 10);
    glEnd();

    GLdouble mat_model[16];
    glGetDoublev(GL_MODELVIEW_MATRIX, mat_model);

    GLdouble mat_proj[16];
    glGetDoublev(GL_PROJECTION_MATRIX, mat_proj);

    GLint viewport[4];
    glGetIntegerv(GL_VIEWPORT, viewport);

    GLdouble xlabel_x, xlabel_y, xlabel_z;
    gluProject(12, 0, 0, mat_model, mat_proj, viewport, &xlabel_x, &xlabel_y, &xlabel_z);
    xlabel_x = round(xlabel_x); xlabel_y = round(xlabel_y);

    GLdouble ylabel_x, ylabel_y, ylabel_z;
    gluProject(0, 12, 0, mat_model, mat_proj, viewport, &ylabel_x, &ylabel_y, &ylabel_z);
    ylabel_x = round(ylabel_x); ylabel_y = round(ylabel_y);

    GLdouble zlabel_x, zlabel_y, zlabel_z;
    gluProject(0, 0, 12, mat_model, mat_proj, viewport, &zlabel_x, &zlabel_y, &zlabel_z);
    zlabel_x = round(zlabel_x); zlabel_y = round(zlabel_y);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glTranslated(-1, -1, 0);
    glScaled(2.0/viewport[2], 2.0/viewport[3], 1);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // FIXME: This was an attempt to keep contrast with background, but is suboptimal
    // (e.g. nearly invisible against a gray background).
//    int r,g,b;
//    r=g=b=0;
//    bgcol.getRgb(&r, &g, &b);
//    glColor3f((255.0f-r)/255.0f, (255.0f-g)/255.0f, (255.0f-b)/255.0f);
    glColor3f(0.0f, 0.0f, 0.0f);
    glBegin(GL_LINES);
    // X Label
    glVertex3d(xlabel_x-3, xlabel_y-3, 0); glVertex3d(xlabel_x+3, xlabel_y+3, 0);
    glVertex3d(xlabel_x-3, xlabel_y+3, 0); glVertex3d(xlabel_x+3, xlabel_y-3, 0);
    // Y Label
    glVertex3d(ylabel_x-3, ylabel_y-3, 0); glVertex3d(ylabel_x+3, ylabel_y+3, 0);
    glVertex3d(ylabel_x-3, ylabel_y+3, 0); glVertex3d(ylabel_x, ylabel_y, 0);
    // Z Label
    glVertex3d(zlabel_x-3, zlabel_y-3, 0); glVertex3d(zlabel_x+3, zlabel_y-3, 0);
    glVertex3d(zlabel_x-3, zlabel_y+3, 0); glVertex3d(zlabel_x+3, zlabel_y+3, 0);
    glVertex3d(zlabel_x-3, zlabel_y-3, 0); glVertex3d(zlabel_x+3, zlabel_y+3, 0);
    glEnd();

    //Restore perspective for next paint
    if(!orthomode)
      GLView::setupGimbalPerspective();
  }

  if (statusLabel) {
    QString msg;
    msg.sprintf("Viewport: translate = [ %.2f %.2f %.2f ], rotate = [ %.2f %.2f %.2f ], distance = %.2f",
      -object_trans.x(), -object_trans.y(), -object_trans.z(),
      fmodf(360 - object_rot.x() + 90, 360), fmodf(360 - object_rot.y(), 360), fmodf(360 - object_rot.z(), 360), viewer_distance);
    statusLabel->setText(msg);
  }

  if (running_under_wine) swapBuffers();
}

void QGLView::keyPressEvent(QKeyEvent *event)
{
  if (event->key() == Qt::Key_Plus) {
    viewer_distance *= 0.9;
    updateGL();
    return;
  }
  if (event->key() == Qt::Key_Minus) {
    viewer_distance /= 0.9;
    updateGL();
    return;
  }
}

void QGLView::wheelEvent(QWheelEvent *event)
{
  viewer_distance *= pow(0.9, event->delta() / 120.0);
  updateGL();
}

void QGLView::mousePressEvent(QMouseEvent *event)
{
  mouse_drag_active = true;
  last_mouse = event->globalPos();
}

void QGLView::normalizeAngle(GLdouble& angle)
{
  while(angle < 0)
    angle += 360;
  while(angle > 360)
    angle -= 360;
}

void QGLView::mouseMoveEvent(QMouseEvent *event)
{
  QPoint this_mouse = event->globalPos();
  double dx = (this_mouse.x()-last_mouse.x()) * 0.7;
  double dy = (this_mouse.y()-last_mouse.y()) * 0.7;
  if (mouse_drag_active) {
    if (event->buttons() & Qt::LeftButton
#ifdef Q_WS_MAC
        && !(event->modifiers() & Qt::MetaModifier)
#endif
      ) {
      // Left button rotates in xz, Shift-left rotates in xy
      // On Mac, Ctrl-Left is handled as right button on other platforms
      object_rot.x() += dy;
      if ((QApplication::keyboardModifiers() & Qt::ShiftModifier) != 0)
        object_rot.y() += dx;
      else
        object_rot.z() += dx;

      normalizeAngle(object_rot.x());
      normalizeAngle(object_rot.y());
      normalizeAngle(object_rot.z());
    } else {
      // Right button pans in the xz plane
      // Middle button pans in the xy plane
      // Shift-right and Shift-middle zooms
      if ((QApplication::keyboardModifiers() & Qt::ShiftModifier) != 0) {
        viewer_distance += (GLdouble)dy;
      } else {

      double mx = +(dx) * viewer_distance/1000;
      double mz = -(dy) * viewer_distance/1000;

      double my = 0;
#if (QT_VERSION < QT_VERSION_CHECK(4, 7, 0))
      if (event->buttons() & Qt::MidButton) {
#else
      if (event->buttons() & Qt::MiddleButton) {
#endif
        my = mz;
        mz = 0;
        // actually lock the x-position
        // (turns out to be easier to use than xy panning)
        mx = 0;
      }

      Matrix3d aax, aay, aaz, tm3;
      aax = Eigen::AngleAxisd(-(object_rot.x()/180) * M_PI, Vector3d::UnitX());
      aay = Eigen::AngleAxisd(-(object_rot.y()/180) * M_PI, Vector3d::UnitY());
      aaz = Eigen::AngleAxisd(-(object_rot.z()/180) * M_PI, Vector3d::UnitZ());
      tm3 = Matrix3d::Identity();
      tm3 = aaz * (aay * (aax * tm3));

      Matrix4d tm;
      tm = Matrix4d::Identity();
      for (int i=0;i<3;i++) for (int j=0;j<3;j++) tm(j,i)=tm3(j,i);

      Matrix4d vec;
      vec <<
        0,  0,  0,  mx,
        0,  0,  0,  my,
        0,  0,  0,  mz,
        0,  0,  0,  1
      ;
      tm = tm * vec;
      object_trans.x() += tm(0,3);
      object_trans.y() += tm(1,3);
      object_trans.z() += tm(2,3);
      }
    }
    updateGL();
    emit doAnimateUpdate();
  }
  last_mouse = this_mouse;
}

void QGLView::mouseReleaseEvent(QMouseEvent*)
{
  mouse_drag_active = false;
  releaseMouse();
}

bool QGLView::save(const char *filename)
{
  QImage img = grabFrameBuffer();
  return img.save(filename, "PNG");
}

contact: Jan Huwald // Impressum