QtWidgetNode.cc 14.6 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
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
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Author$                                                      *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/
49

50
#include <ACG/GL/acg_glew.hh>
51
#include "QtWidgetNode.hh"
Jan Möbius's avatar
Jan Möbius committed
52
#include <ACG/Geometry/Types/PlaneT.hh>
Martin Schultz's avatar
Martin Schultz committed
53
#include <ACG/Utils/ImageConversion.hh>
Jan Möbius's avatar
Jan Möbius committed
54
55

#include <QApplication>
56
#include <QGLWidget>
Jan Möbius's avatar
Jan Möbius committed
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


//== NAMESPACES ===============================================================


namespace ACG {
namespace SceneGraph {



//== IMPLEMENTATION ==========================================================
bool QtWidgetNode::NodeEventFilter::eventFilter(QObject *_obj, QEvent *_event)
{
  bool repaint = false;
  //repaint, if layout was changed or paint requested
  if (_event->type() == QEvent::LayoutRequest || _event->type() == QEvent::Paint)
    repaint = true;

  //repaint only, if initial geometry was created
  repaint = repaint && node_->planeCreated_;

  bool result = QObject::eventFilter(_obj, _event);


  if (repaint)
  {
    //check if geometry needs an update
    if( (node_->oldWidgetWidth_ != node_->widget_->width()) || (node_->oldWidgetHeight_ != node_->widget_->height()))
        node_->updateGeometry();

    //create new widget texture
    node_->createTexture();
    node_->setDirty(true);
  }
  return result;
}
//----------------------------------------------------------------------------

QtWidgetNode::QtWidgetNode(QWidget* _widget, BaseNode *_parent, std::string _name)
:BaseNode(_parent, _name),
 ef_(new NodeEventFilter(this)),
 vbo_(0),
 texID_(0),
 widget_(_widget),
 oldWidgetWidth_(0),
 oldWidgetHeight_(0),
 planeCreated_(false),
 state_(0),
 anisotropicSupport_(false)
{
  vertexDecl_.addElement(GL_FLOAT, 3, ACG::VERTEX_USAGE_POSITION);
  vertexDecl_.addElement(GL_FLOAT, 3, ACG::VERTEX_USAGE_NORMAL);
  vertexDecl_.addElement(GL_FLOAT, 2, ACG::VERTEX_USAGE_TEXCOORD);
  setWidget(_widget);
  plane_.position = ACG::Vec3d(0.0,0.0,0.0);
  plane_.xDirection = ACG::Vec3d(1.0,0.0,0.0);
  plane_.yDirection = ACG::Vec3d(0.0,1.0,0.0);
}

//----------------------------------------------------------------------------

QtWidgetNode::~QtWidgetNode()
{
  if ( vbo_)
    GLState::deleteBuffers(1,&vbo_);

  if (texID_)
    glDeleteTextures(1,&texID_);


}

//----------------------------------------------------------------------------

void QtWidgetNode::setWidget(QWidget* _w)
{
  if (widget_)
    widget_->removeEventFilter(ef_);

  widget_ = _w;
  if(!widget_)
  {
    oldWidgetWidth_ = oldWidgetHeight_ = 0;
    planeCreated_ = false;
    setDirty(true);
    return;
  }

  widget_->adjustSize();
  widget_->installEventFilter(ef_);
  if (planeCreated_)
  {
    updateGeometry();
    createTexture();
  }
  setDirty(true);

}

//----------------------------------------------------------------------------

void QtWidgetNode::boundingBox(ACG::Vec3d& _bbMin, ACG::Vec3d& _bbMax)
{
  ACG::Vec3d pos = plane_.position - plane_.xDirection * 0.5 - plane_.yDirection * 0.5;

  //add a little offset in normal direction
  ACG::Vec3d pos0 = ACG::Vec3d( pos + plane_.normal * 0.1 );
  ACG::Vec3d pos1 = ACG::Vec3d( pos - plane_.normal * 0.1 );

  ACG::Vec3d xDird = ACG::Vec3d( plane_.xDirection );
  ACG::Vec3d yDird = ACG::Vec3d( plane_.yDirection );

  _bbMin.minimize( pos0 );
  _bbMin.minimize( pos0 + xDird);
  _bbMin.minimize( pos0 + yDird);
  _bbMin.minimize( pos0 + xDird + yDird);
  _bbMax.maximize( pos1 );
  _bbMax.maximize( pos1 + xDird);
  _bbMax.maximize( pos1 + yDird);
  _bbMax.maximize( pos1 + xDird + yDird);
}

//----------------------------------------------------------------------------

ACG::SceneGraph::DrawModes::DrawMode
QtWidgetNode::availableDrawModes() const
{
  return ( ACG::SceneGraph::DrawModes::POINTS |
             ACG::SceneGraph::DrawModes::SOLID_FLAT_SHADED );
}


//----------------------------------------------------------------------------

void QtWidgetNode::uploadPlane()
{

  const ACG::Vec3d outerCorner = plane_.xDirection + plane_.yDirection;

  // Array of coordinates for the plane
  // Interleaved with normals

  // 4 vertices with 3 pos, 3 normal, 2 texcoords
  const size_t buffersize = 4*8;
  float vboData_[buffersize] = { 0.0,0.0,0.0,
      (float)plane_.normal[0],(float)plane_.normal[1],(float)plane_.normal[2],
      0.0,0.0,
      (float)plane_.xDirection[0],(float)plane_.xDirection[1],(float)plane_.xDirection[2],
      (float)plane_.normal[0],(float)plane_.normal[1],(float)plane_.normal[2],
      1.0,0.0,
      (float)outerCorner[0],(float)outerCorner[1],(float)outerCorner[2],
      (float)plane_.normal[0],(float)plane_.normal[1],(float)plane_.normal[2],
      1.0,1.0,
      (float)plane_.yDirection[0],(float)plane_.yDirection[1],(float)plane_.yDirection[2],
      (float)plane_.normal[0],(float)plane_.normal[1],(float)plane_.normal[2],
      0.0,1.0};

  // Create buffer for vertex coordinates if necessary
  if ( ! vbo_ ) {
Martin Schultz's avatar
Martin Schultz committed
216
    glGenBuffers(1, &vbo_);
Jan Möbius's avatar
Jan Möbius committed
217
218
  }
  // Bind buffer
Martin Schultz's avatar
Martin Schultz committed
219
  glBindBuffer(GL_ARRAY_BUFFER_ARB, vbo_);
Jan Möbius's avatar
Jan Möbius committed
220
221

  // Upload to buffer
Martin Schultz's avatar
Martin Schultz committed
222
  glBufferData(GL_ARRAY_BUFFER_ARB, buffersize * sizeof(float), &vboData_[0], GL_STATIC_DRAW_ARB);
Jan Möbius's avatar
Jan Möbius committed
223

Martin Schultz's avatar
Martin Schultz committed
224
  glBindBuffer(GL_ARRAY_BUFFER_ARB, 0);
Jan Möbius's avatar
Jan Möbius committed
225
226
227
228
229
230
231
}
//----------------------------------------------------------------

void QtWidgetNode::createTexture()
{
  //grab texture from qt
  widget_->removeEventFilter(ef_);
232
  QPixmap pix = widget_->grab();
Jan Möbius's avatar
Jan Möbius committed
233
234
235
  widget_->installEventFilter(ef_);

  QImage image = pix.toImage();
Martin Schultz's avatar
Martin Schultz committed
236
  image = ACG::Util::convertToGLFormat(image);// QGLWidget::convertToGLFormat( image );
Jan Möbius's avatar
Jan Möbius committed
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

  // generate texture
  if (!texID_)
  {
    glGenTextures( 1, &texID_ );
    anisotropicSupport_ = ACG::checkExtensionSupported("GL_EXT_texture_filter_anisotropic");
  }
  glBindTexture( GL_TEXTURE_2D, texID_ );

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

  if (anisotropicSupport_)
  {
    GLfloat anisotropyValue;
    glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &anisotropyValue);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropyValue);
  }

  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width(), image.height(), 0, GL_RGBA,
      GL_UNSIGNED_BYTE, image.bits());
  glGenerateMipmap(GL_TEXTURE_2D);
}
//----------------------------------------------------------------

void QtWidgetNode::createGeometry(GLState& _state)
{
  // compute the widgetsize in world space
  oldWidgetWidth_ = widget_->width();
  oldWidgetHeight_= widget_->height();;
  ACG::Vec3d projPos = ACG::Vec3d(widget_->width(),widget_->height(),0.0);
  ACG::Vec3d projNullPos = ACG::Vec3d(0.0,0.0,0.0);

  //unproject the 2D coordinates
  projPos = _state.unproject(projPos);
  projNullPos = _state.unproject(projNullPos);


  // create plane
  const ACG::Vec3d xDirection = Vec3d(projPos[0]-projNullPos[0],0.0,0.0);
  const ACG::Vec3d yDirection = Vec3d(0.0,projPos[1]-projNullPos[1],0.0);

  plane_.setPlane(ACG::Vec3d(0.0,0.0,0.0),xDirection,yDirection);

  //update plane
  uploadPlane();
}
//----------------------------------------------------------------

void QtWidgetNode::updateGeometry()
{
  double widthRatio = widget_->width() / (double)oldWidgetWidth_;
  double heightRatio = widget_->height() / (double)oldWidgetHeight_;

  oldWidgetWidth_ = widget_->width();
  oldWidgetHeight_ = widget_->height();

  plane_.setPlane(plane_.position,plane_.xDirection*widthRatio,plane_.yDirection*heightRatio);

  uploadPlane();
}

//----------------------------------------------------------------

void QtWidgetNode::mouseEvent(GLState&  _state , QMouseEvent*  _event )
{
  if (BaseNode::hidden() || !BaseNode::pickingEnabled() || !widget_)
      return;

  ACG::Vec3d eventPos = ACG::Vec3d(_event->pos().x(),_state.viewport_height()-_event->pos().y(),0.0);

  //compute 2d event position in world space
  ACG::Vec3d unprojEventPos = _state.unproject(eventPos);

  // get intersection position
  ACG::Vec3d intersecPos;
  double distance;

  ACG::Vec3d pos = plane_.position;
  ACG::Geometry::Planed intersectPlane(pos,plane_.normal);

  ACG::Vec3d rayDir = (unprojEventPos - _state.eye()).normalize();
  if (!intersectPlane.intersect_ray(_state.eye(),_state.eye()+rayDir,intersecPos,distance))
    return;//no intersection was found


  ACG::Vec3d topLeftCorner = pos - 0.5*plane_.xDirection - 0.5*plane_.yDirection;
  ACG::Vec3d toInter = intersecPos - topLeftCorner;
  ACG::Vec3d xDir = plane_.xDirection;
  ACG::Vec3d yDir = plane_.yDirection;
  double sX = (xDir | toInter)/xDir.sqrnorm();
  double sY = (yDir | toInter)/yDir.sqrnorm();

  if (sX < 0.0 || sX > 1.0 || sY < 0.0 || sY > 1.0)
      return;


  QPoint widgetEventPos(sX * widget_->width(), sY * widget_->height());

  //Search for the widget where the event should be sent
  QWidget *childWidget = widget_->childAt(widgetEventPos);
  if (!childWidget)
    return;

  //compute event pos in child space
  widgetEventPos -= childWidget->pos();

  //send event
  QMouseEvent event(_event->type(),widgetEventPos,_event->button(),_event->buttons(),_event->modifiers());
  QApplication::sendEvent(childWidget,&event);

  //update widget
  QEvent paintEvent(QEvent::Paint);
  QApplication::sendEvent(widget_,&paintEvent);
}
//----------------------------------------------------------------------------

void QtWidgetNode::mouseEvent(QMouseEvent*  _event )
{
  if (!state_)
      return;
  mouseEvent(*state_,_event);
}
//----------------------------------------------------------------------------

void QtWidgetNode::getRenderObjects(ACG::IRenderer* _renderer, ACG::GLState&  _state , const ACG::SceneGraph::DrawModes::DrawMode&  _drawMode , const ACG::SceneGraph::Material* _mat) {

  // init base render object
  state_ = &_state;
  if (!widget_)
    return;

  ACG::RenderObject ro;

  ro.initFromState(&_state);
  ro.debugName = (std::string("QtWidgetNode: ")+name()).c_str();

  if (!planeCreated_)
  {
    //one initial creation of the plane
    createGeometry(_state);
    //texture updates will be done via QWidget events (see eventfilter)
    createTexture();
    planeCreated_ = true;
  }


  ACG::Vec3d pos = plane_.position - plane_.xDirection*0.5 - plane_.yDirection*0.5;
  _state.push_modelview_matrix();
  _state.translate(pos[0], pos[1], pos[2]);
  ro.modelview = _state.modelview();
  _state.pop_modelview_matrix();

  // Render with depth test enabled
  ro.depthTest = true;

  // Set the buffers for rendering
  ro.vertexBuffer = vbo_;
  ro.vertexDecl   = &vertexDecl_;

  // Set Texture
  RenderObject::Texture texture;
  texture.id = texID_;
  texture.type = GL_TEXTURE_2D;
  texture.shadow = false;
  ro.addTexture(texture);

  // Set shading
  ro.shaderDesc.vertexColors = false;
  ro.shaderDesc.shadeMode = SG_SHADE_UNLIT;

  ACG::SceneGraph::Material localMaterial;

  localMaterial.baseColor(ACG::Vec4f(1.0, 1.0, 1.0, 1.0 ));
  localMaterial.ambientColor(ACG::Vec4f(0.0, 0.0, 0.0, 1.0 ));
  localMaterial.diffuseColor(ACG::Vec4f(0.0, 0.0, 0.0, 1.0 ));
  localMaterial.specularColor(ACG::Vec4f(0.0, 0.0, 0.0, 1.0 ));
  ro.setMaterial(&localMaterial);


  ro.glDrawArrays(GL_QUADS, 0, 4);
  _renderer->addRenderObject(&ro);
}

//=============================================================================
} // namespace SceneGraph
} // namespace ACG
//=============================================================================