OSGWidget.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // Include own headers
  2. #include "OSGWidget.hpp"
  3. // Include modules
  4. #include "PickHandler.hpp"
  5. #include "TrackPointRenderer.hpp"
  6. // Include dependencies
  7. #include <osgViewer/Viewer>
  8. #include <osg/ShapeDrawable>
  9. #include <osg/Geode>
  10. #include <osgDB/ReadFile>
  11. #include <osg/Group>
  12. #include <osg/Switch>
  13. #include <osg/MatrixTransform>
  14. #include <osg/Matrix>
  15. #include <osgGA/TrackballManipulator>
  16. #include <osgUtil/LineSegmentIntersector>
  17. #include <osgUtil/IntersectionVisitor>
  18. #include <osgUtil/MeshOptimizers>
  19. #include <osg/PolygonMode>
  20. #include <osgDB/WriteFile>
  21. #include <osg/Material>
  22. #include <osg/StateSet>
  23. #include <cassert>
  24. #include <stdexcept>
  25. #include <vector>
  26. #include <QDebug>
  27. #include <QKeyEvent>
  28. #include <QPainter>
  29. #include <QWheelEvent>
  30. namespace osgWidget {
  31. void Viewer::setupThreading() {
  32. if (_threadingModel == SingleThreaded) {
  33. if (_threadsRunning) {
  34. stopThreading();
  35. }
  36. } else {
  37. if (!_threadsRunning) {
  38. startThreading();
  39. }
  40. }
  41. }
  42. }
  43. void OSGWidget::fixMaterialState(osg::ref_ptr<osg::Node> node) {
  44. osg::StateSet* stateSet = node->getOrCreateStateSet();
  45. osg::Material* material = new osg::Material;
  46. material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
  47. stateSet->setAttributeAndModes(material, osg::StateAttribute::ON);
  48. stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
  49. }
  50. OSGWidget::OSGWidget(QWidget* parent): QOpenGLWidget(parent),
  51. graphicsWindow_(new osgViewer::GraphicsWindowEmbedded(this->x(), this->y(), this->width(), this->height())),
  52. _viewer(new osgWidget::Viewer),
  53. selectionActive_(false),
  54. selectionFinished_(true)
  55. {
  56. this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  57. // Root node of the scene
  58. _root = new osg::Group;
  59. // Create the camera
  60. float aspectRatio = static_cast<float>(this->width()) / static_cast<float>(this->height());
  61. auto pixelRatio = this->devicePixelRatio();
  62. osg::Camera* camera = new osg::Camera;
  63. camera->setViewport(0, 0, this->width() * pixelRatio, this->height() * pixelRatio);
  64. camera->setClearColor(osg::Vec4(0.2f, 0.1875f, 0.375f, 1.0f));
  65. camera->setProjectionMatrixAsPerspective(30.0f, aspectRatio, 1.0f, 1000.0f);
  66. camera->setGraphicsContext(graphicsWindow_);
  67. // Create the viewer
  68. _view = new osgViewer::View;
  69. _view->setCamera(camera);
  70. _view->setSceneData(_root);
  71. // Create coordinate axes
  72. _coordinateAxes = new osg::Geode;
  73. osg::ref_ptr<osg::ShapeDrawable> zAxis = new osg::ShapeDrawable();
  74. zAxis->setShape(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.0f), 0.1f, 100.0f));
  75. zAxis->setColor(osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f));
  76. _coordinateAxes->addDrawable(zAxis.get());
  77. OSGWidget::fixMaterialState(_coordinateAxes);
  78. _root->addChild(_coordinateAxes);
  79. _mesh = new osg::Geode;
  80. // Attach a manipulator (it's usually done for us when we use viewer.run())
  81. osg::ref_ptr<osgGA::TrackballManipulator> tm = new osgGA::TrackballManipulator;
  82. tm->setAllowThrow(false);
  83. _view->setCameraManipulator(tm);
  84. _viewer->addView(_view);
  85. _viewer->setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);
  86. _viewer->realize();
  87. _picker = new PickHandler(this, _root);
  88. _root->addChild(_picker->getPickerRoot());
  89. _view->addEventHandler(_picker);
  90. // This ensures that the widget will receive keyboard events. This focus
  91. // policy is not set by default. The default, Qt::NoFocus, will result in
  92. // keyboard events that are ignored.
  93. this->setFocusPolicy(Qt::StrongFocus);
  94. this->setMinimumSize(100, 100);
  95. // Ensures that the widget receives mouse move events even though no
  96. // mouse button has been pressed. We require this in order to let the
  97. // graphics window switch viewports properly.
  98. this->setMouseTracking(true);
  99. _pointRoot = new osg::Group;
  100. _root->addChild(_pointRoot.get());
  101. _pointRenderer = new TrackPointRenderer(this, _pointRoot);
  102. }
  103. OSGWidget::~OSGWidget() {
  104. }
  105. void OSGWidget::renderBaseMesh(const osg::ref_ptr<osg::Vec3Array> vertices, const osg::ref_ptr<osg::Vec3Array> normals) {
  106. _root->removeChild(_mesh);
  107. osg::ref_ptr<osg::Geometry> meshGeometry = new osg::Geometry;
  108. meshGeometry->setVertexArray(vertices.get());
  109. meshGeometry->setNormalArray(normals.get(), osg::Array::BIND_PER_VERTEX);
  110. meshGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, vertices->getNumElements()));
  111. osgUtil::optimizeMesh(meshGeometry.get());
  112. _mesh->addDrawable(meshGeometry.get());
  113. OSGWidget::fixMaterialState(_mesh);
  114. _root->addChild(_mesh);
  115. _picker->updateRenderer();
  116. }
  117. osg::ref_ptr<osg::Geode> OSGWidget::getMesh() {
  118. return _mesh;
  119. }
  120. PickHandler* OSGWidget::getPicker() {
  121. return _picker;
  122. }
  123. TrackPointRenderer* OSGWidget::getPointRenderer() {
  124. return _pointRenderer;
  125. }
  126. void OSGWidget::paintEvent(QPaintEvent*) {
  127. this->makeCurrent();
  128. QPainter painter(this);
  129. painter.setRenderHint(QPainter::Antialiasing);
  130. this->paintGL();
  131. painter.end();
  132. this->doneCurrent();
  133. }
  134. void OSGWidget::paintGL() {
  135. _viewer->frame();
  136. }
  137. void OSGWidget::resizeGL(int width, int height) {
  138. auto pixelRatio = this->devicePixelRatio();
  139. this->getEventQueue()->windowResize(this->x(), this->y(), width * pixelRatio, height * pixelRatio);
  140. graphicsWindow_->resized(this->x(), this->y(), width * pixelRatio, height * pixelRatio);
  141. this->onResize(width, height);
  142. }
  143. void OSGWidget::keyPressEvent(QKeyEvent* event) {
  144. QString keyString = event->text();
  145. const char* keyData = keyString.toLocal8Bit().data();
  146. if (event->key() == Qt::Key_H) {
  147. this->onHome();
  148. return;
  149. }
  150. this->getEventQueue()->keyPress(osgGA::GUIEventAdapter::KeySymbol(*keyData));
  151. }
  152. void OSGWidget::keyReleaseEvent(QKeyEvent* event) {
  153. QString keyString = event->text();
  154. const char* keyData = keyString.toLocal8Bit().data();
  155. this->getEventQueue()->keyRelease(osgGA::GUIEventAdapter::KeySymbol(*keyData));
  156. }
  157. void OSGWidget::mouseMoveEvent(QMouseEvent* event) {
  158. auto pixelRatio = this->devicePixelRatio();
  159. this->getEventQueue()->mouseMotion(static_cast<float>(event->position().x() * pixelRatio), static_cast<float>(event->position().y() * pixelRatio));
  160. }
  161. void OSGWidget::mousePressEvent(QMouseEvent* event) {
  162. unsigned int button = 0;
  163. switch(event->button()) {
  164. case Qt::LeftButton:
  165. button = 1;
  166. break;
  167. case Qt::MiddleButton:
  168. button = 2;
  169. break;
  170. case Qt::RightButton:
  171. button = 3;
  172. break;
  173. default:
  174. break;
  175. }
  176. auto pixelRatio = this->devicePixelRatio();
  177. this->getEventQueue()->mouseButtonPress(static_cast<float>(event->position().x() * pixelRatio), static_cast<float>(event->position().y() * pixelRatio), button);
  178. }
  179. void OSGWidget::mouseReleaseEvent(QMouseEvent* event) {
  180. unsigned int button = 0;
  181. switch(event->button()) {
  182. case Qt::LeftButton:
  183. button = 1;
  184. break;
  185. case Qt::MiddleButton:
  186. button = 2;
  187. break;
  188. case Qt::RightButton:
  189. button = 3;
  190. break;
  191. default:
  192. break;
  193. }
  194. auto pixelRatio = this->devicePixelRatio();
  195. this->getEventQueue()->mouseButtonRelease(static_cast<float>(event->position().x() * pixelRatio), static_cast<float>(event->position().y() * pixelRatio), button);
  196. }
  197. void OSGWidget::wheelEvent(QWheelEvent* event) {
  198. event->accept();
  199. int delta = event->angleDelta().y();
  200. osgGA::GUIEventAdapter::ScrollingMotion motion = delta > 0 ? osgGA::GUIEventAdapter::SCROLL_UP : osgGA::GUIEventAdapter::SCROLL_DOWN;
  201. this->getEventQueue()->mouseScroll(motion);
  202. }
  203. bool OSGWidget::event(QEvent* event) {
  204. bool handled = QOpenGLWidget::event(event);
  205. // This ensures that the OSG widget is always going to be repainted after the
  206. // user performed some interaction. Doing this in the event handler ensures
  207. // that we don't forget about some event and prevents duplicate code.
  208. switch(event->type()) {
  209. case QEvent::KeyPress:
  210. case QEvent::KeyRelease:
  211. case QEvent::MouseButtonDblClick:
  212. case QEvent::MouseButtonPress:
  213. case QEvent::MouseButtonRelease:
  214. case QEvent::MouseMove:
  215. case QEvent::Wheel:
  216. this->update();
  217. break;
  218. case QEvent::Resize:
  219. this->onResize(this->width(), this->height());
  220. break;
  221. default:
  222. break;
  223. }
  224. return handled;
  225. }
  226. void OSGWidget::onHome() {
  227. osgViewer::ViewerBase::Views views;
  228. _viewer->getViews( views );
  229. for(std::size_t i = 0; i < views.size(); i++) {
  230. osgViewer::View* view = views.at(i);
  231. view->home();
  232. }
  233. }
  234. void OSGWidget::onResize(int width, int height) {
  235. std::vector<osg::Camera*> cameras;
  236. _viewer->getCameras(cameras);
  237. assert(cameras.size() == 1);
  238. auto pixelRatio = this->devicePixelRatio();
  239. cameras[0]->setViewport(0, 0, width * pixelRatio, height * pixelRatio);
  240. }
  241. osgGA::EventQueue* OSGWidget::getEventQueue() const {
  242. osgGA::EventQueue* eventQueue = graphicsWindow_->getEventQueue();
  243. if (eventQueue) {
  244. return eventQueue;
  245. } else {
  246. throw std::runtime_error("Unable to obtain valid event queue");
  247. }
  248. }