OSGWidget.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. // Include own headers
  2. #include "OSGWidget.hpp"
  3. // Include modules
  4. #include "PickHandler.hpp"
  5. #include "TrackPointRenderer.hpp"
  6. #include "HudCallback.hpp"
  7. #include "resources.hpp"
  8. #include "MeshTools.hpp"
  9. // Include dependencies
  10. #include <osgViewer/Viewer>
  11. #include <osg/ShapeDrawable>
  12. #include <osg/Geode>
  13. #include <osgDB/ReadFile>
  14. #include <osg/Group>
  15. #include <osg/Switch>
  16. #include <osg/MatrixTransform>
  17. #include <osg/Matrix>
  18. #include <osgGA/TrackballManipulator>
  19. #include <osgUtil/LineSegmentIntersector>
  20. #include <osgUtil/IntersectionVisitor>
  21. #include <osgUtil/MeshOptimizers>
  22. #include <osg/PolygonMode>
  23. #include <osgDB/WriteFile>
  24. #include <osg/Material>
  25. #include <osg/StateSet>
  26. #include <cassert>
  27. #include <stdexcept>
  28. #include <vector>
  29. #include <QDebug>
  30. #include <QKeyEvent>
  31. #include <QPainter>
  32. #include <QWheelEvent>
  33. namespace osgWidget {
  34. void Viewer::setupThreading() {
  35. if (_threadingModel == SingleThreaded) {
  36. if (_threadsRunning) {
  37. stopThreading();
  38. }
  39. } else {
  40. if (!_threadsRunning) {
  41. startThreading();
  42. }
  43. }
  44. }
  45. }
  46. void OSGWidget::fixMaterialState(osg::ref_ptr<osg::Node> node, osg::Vec4* color) {
  47. osg::StateSet* stateSet = node->getOrCreateStateSet();
  48. osg::Material* material = new osg::Material;
  49. material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
  50. if (color) {
  51. material->setDiffuse(osg::Material::FRONT_AND_BACK, *color);
  52. }
  53. stateSet->setAttributeAndModes(material, osg::StateAttribute::ON);
  54. stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
  55. }
  56. OSGWidget::OSGWidget(QWidget* parent): QOpenGLWidget(parent),
  57. graphicsWindow_(new osgViewer::GraphicsWindowEmbedded(this->x(), this->y(), this->width(), this->height())),
  58. _viewer(new osgWidget::Viewer),
  59. selectionActive_(false),
  60. selectionFinished_(true)
  61. {
  62. this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  63. // Root node of the scene
  64. _root = new osg::Group;
  65. // Create the camera
  66. float aspectRatio = static_cast<float>(this->width()) / static_cast<float>(this->height());
  67. auto pixelRatio = this->devicePixelRatio();
  68. osg::Camera* camera = new osg::Camera;
  69. camera->setViewport(0, 0, this->width() * pixelRatio, this->height() * pixelRatio);
  70. camera->setClearColor(osg::Vec4(0.2f, 0.1875f, 0.375f, 1.0f));
  71. camera->setProjectionMatrixAsPerspective(30.0f, aspectRatio, 1.0f, 1000.0f);
  72. camera->setGraphicsContext(graphicsWindow_);
  73. // Create the viewer
  74. _view = new osgViewer::View;
  75. _view->setCamera(camera);
  76. _view->setSceneData(_root);
  77. // Create coordinate axes
  78. _coordinateAxes = new osg::Group;
  79. osg::Vec4 axesColor = osg::Vec4(0.7f, 0.7f, 0.7f, 1.0f);
  80. osg::ref_ptr<osg::MatrixTransform> xRotation = new osg::MatrixTransform;
  81. xRotation->setMatrix(osg::Matrix::rotate(osg::Vec3f(0.0f, 0.0f, 1.0f), osg::Vec3f(1.0f, 0.0f, 0.0f)));
  82. osg::ref_ptr<osg::Geode> xAxis = new osg::Geode;
  83. osg::ref_ptr<osg::ShapeDrawable> xAxisShape = new osg::ShapeDrawable();
  84. xAxisShape->setShape(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.0f), 0.05f, 100.0f));
  85. xAxisShape->setColor(axesColor);
  86. xAxis->addDrawable(xAxisShape.get());
  87. osg::ref_ptr<osg::ShapeDrawable> xConeShape = new osg::ShapeDrawable();
  88. xConeShape->setShape(new osg::Cone(osg::Vec3(0.0f, 0.0f, 50.0f), 0.2f, 1.0f));
  89. xConeShape->setColor(axesColor);
  90. xAxis->addDrawable(xConeShape.get());
  91. xRotation->addChild(xAxis.get());
  92. osg::ref_ptr<osg::MatrixTransform> yRotation = new osg::MatrixTransform;
  93. yRotation->setMatrix(osg::Matrix::rotate(osg::Vec3f(0.0f, 0.0f, 1.0f), osg::Vec3f(0.0f, 1.0f, 0.0f)));
  94. osg::ref_ptr<osg::Geode> yAxis = new osg::Geode;
  95. osg::ref_ptr<osg::ShapeDrawable> yAxisShape = new osg::ShapeDrawable();
  96. yAxisShape->setShape(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.0f), 0.05f, 100.0f));
  97. yAxisShape->setColor(axesColor);
  98. yAxis->addDrawable(yAxisShape.get());
  99. osg::ref_ptr<osg::ShapeDrawable> yConeShape = new osg::ShapeDrawable();
  100. yConeShape->setShape(new osg::Cone(osg::Vec3(0.0f, 0.0f, 50.0f), 0.2f, 1.0f));
  101. yConeShape->setColor(axesColor);
  102. yAxis->addDrawable(yConeShape.get());
  103. yRotation->addChild(yAxis.get());
  104. osg::ref_ptr<osg::Geode> zAxis = new osg::Geode;
  105. osg::ref_ptr<osg::ShapeDrawable> zAxisShape = new osg::ShapeDrawable();
  106. zAxisShape->setShape(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.0f), 0.05f, 100.0f));
  107. zAxisShape->setColor(axesColor);
  108. osg::ref_ptr<osg::ShapeDrawable> zConeShape = new osg::ShapeDrawable();
  109. zConeShape->setShape(new osg::Cone(osg::Vec3(0.0f, 0.0f, 50.0f), 0.2f, 1.0f));
  110. zConeShape->setColor(axesColor);
  111. zAxis->addDrawable(zConeShape.get());
  112. zAxis->addDrawable(zAxisShape.get());
  113. _coordinateAxes->addChild(xRotation.get());
  114. _coordinateAxes->addChild(yRotation.get());
  115. _coordinateAxes->addChild(zAxis.get());
  116. OSGWidget::fixMaterialState(_coordinateAxes);
  117. _root->addChild(_coordinateAxes);
  118. // Add axes preview
  119. osg::ref_ptr<osg::Camera> hudCamera = new osg::Camera;
  120. int width = 1024;
  121. int height = 1024;
  122. hudCamera->setProjectionMatrixAsOrtho(0, width, 0, height, 1, 100);
  123. hudCamera->setRenderOrder(osg::Camera::POST_RENDER);
  124. hudCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
  125. hudCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
  126. osg::ref_ptr<osg::Group> axesPreview = createAxesPreview();
  127. osg::MatrixTransform* pTM = new osg::MatrixTransform;
  128. pTM->addChild(axesPreview.get());
  129. axesPreview->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
  130. pTM->setMatrix(osg::Matrix::scale(osg::Vec3(width/12, width/12, width/12)) * osg::Matrix::translate(osg::Vec3(width/20, width/20, 1)));
  131. pTM->setUpdateCallback(new HudCallback(camera));
  132. hudCamera->addChild(pTM);
  133. hudCamera->setViewMatrixAsLookAt(osg::Vec3(0, 0, 1), osg::Vec3(0, 0, 0), osg::Vec3(0, 1, 0)); // opengl default camera position
  134. _root->addChild(hudCamera.release());
  135. // Attach a manipulator (it's usually done for us when we use viewer.run())
  136. osg::ref_ptr<osgGA::TrackballManipulator> tm = new osgGA::TrackballManipulator;
  137. tm->setAllowThrow(false);
  138. _view->setCameraManipulator(tm);
  139. _viewer->addView(_view);
  140. _viewer->setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);
  141. _viewer->realize();
  142. _picker = new PickHandler(this, _root);
  143. _root->addChild(_picker->getPickerRoot());
  144. _view->addEventHandler(_picker);
  145. // This ensures that the widget will receive keyboard events. This focus
  146. // policy is not set by default. The default, Qt::NoFocus, will result in
  147. // keyboard events that are ignored.
  148. this->setFocusPolicy(Qt::StrongFocus);
  149. this->setMinimumSize(100, 100);
  150. // Ensures that the widget receives mouse move events even though no
  151. // mouse button has been pressed. We require this in order to let the
  152. // graphics window switch viewports properly.
  153. this->setMouseTracking(true);
  154. _pointRoot = new osg::Group;
  155. _root->addChild(_pointRoot.get());
  156. _pointRenderer = new TrackPointRenderer(this, _pointRoot);
  157. }
  158. OSGWidget::~OSGWidget() {
  159. }
  160. void OSGWidget::renderBaseMesh(const osg::ref_ptr<osg::Vec3Array> vertices, const osg::ref_ptr<osg::Vec3Array> normals) {
  161. _root->removeChild(_mesh);
  162. _mesh = new osg::Geode;
  163. osg::ref_ptr<osg::Geometry> meshGeometry = new osg::Geometry;
  164. meshGeometry->setVertexArray(vertices.get());
  165. meshGeometry->setNormalArray(normals.get(), osg::Array::BIND_PER_VERTEX);
  166. meshGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, vertices->getNumElements()));
  167. osgUtil::optimizeMesh(meshGeometry.get());
  168. _mesh->addDrawable(meshGeometry.get());
  169. OSGWidget::fixMaterialState(_mesh);
  170. _root->addChild(_mesh);
  171. _picker->updateRenderer();
  172. }
  173. osg::ref_ptr<osg::Geode> OSGWidget::getMesh() {
  174. return _mesh;
  175. }
  176. PickHandler* OSGWidget::getPicker() {
  177. return _picker;
  178. }
  179. TrackPointRenderer* OSGWidget::getPointRenderer() {
  180. return _pointRenderer;
  181. }
  182. void OSGWidget::loadSteamvrThread() {
  183. if (!_steamvrLoaded) {
  184. std::vector<Lib3MF::sPosition> verticesBuffer;
  185. std::vector<Lib3MF::sTriangle> triangleBuffer;
  186. for (unsigned int i = 0; i < sizeof(steamvrthread_VERTICES) / sizeof(float); i += 3) {
  187. Lib3MF::sPosition vertex = {steamvrthread_VERTICES[i], steamvrthread_VERTICES[i + 1], steamvrthread_VERTICES[i + 2]};
  188. verticesBuffer.push_back(vertex);
  189. }
  190. for (unsigned int i = 0; i < sizeof(steamvrthread_TRIANGLES) / sizeof(unsigned int); i += 3) {
  191. Lib3MF::sTriangle triangle = {steamvrthread_TRIANGLES[i], steamvrthread_TRIANGLES[i + 1], steamvrthread_TRIANGLES[i + 2]};
  192. triangleBuffer.push_back(triangle);
  193. }
  194. osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
  195. osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array;
  196. MeshTools::calculateNormals(verticesBuffer, triangleBuffer, vertices, normals);
  197. _steamvrThreadMesh = new osg::Geometry;
  198. _steamvrThreadMesh->setVertexArray(vertices.get());
  199. _steamvrThreadMesh->setNormalArray(normals.get(), osg::Array::BIND_PER_VERTEX);
  200. _steamvrThreadMesh->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, vertices->getNumElements()));
  201. osgUtil::optimizeMesh(_steamvrThreadMesh.get());
  202. _steamvrLoaded = true;
  203. }
  204. }
  205. void OSGWidget::clear() {
  206. _root->removeChild(_mesh);
  207. }
  208. void OSGWidget::paintEvent(QPaintEvent*) {
  209. this->makeCurrent();
  210. QPainter painter(this);
  211. painter.setRenderHint(QPainter::Antialiasing);
  212. this->paintGL();
  213. painter.end();
  214. this->doneCurrent();
  215. }
  216. void OSGWidget::paintGL() {
  217. _viewer->frame();
  218. }
  219. void OSGWidget::resizeGL(int width, int height) {
  220. auto pixelRatio = this->devicePixelRatio();
  221. this->getEventQueue()->windowResize(this->x(), this->y(), width * pixelRatio, height * pixelRatio);
  222. graphicsWindow_->resized(this->x(), this->y(), width * pixelRatio, height * pixelRatio);
  223. this->onResize(width, height);
  224. }
  225. void OSGWidget::keyPressEvent(QKeyEvent* event) {
  226. QString keyString = event->text();
  227. const char* keyData = keyString.toLocal8Bit().data();
  228. if (event->key() == Qt::Key_H) {
  229. this->onHome();
  230. return;
  231. }
  232. this->getEventQueue()->keyPress(osgGA::GUIEventAdapter::KeySymbol(*keyData));
  233. }
  234. void OSGWidget::keyReleaseEvent(QKeyEvent* event) {
  235. QString keyString = event->text();
  236. const char* keyData = keyString.toLocal8Bit().data();
  237. this->getEventQueue()->keyRelease(osgGA::GUIEventAdapter::KeySymbol(*keyData));
  238. }
  239. void OSGWidget::mouseMoveEvent(QMouseEvent* event) {
  240. auto pixelRatio = this->devicePixelRatio();
  241. this->getEventQueue()->mouseMotion(static_cast<float>(event->position().x() * pixelRatio), static_cast<float>(event->position().y() * pixelRatio));
  242. }
  243. void OSGWidget::mousePressEvent(QMouseEvent* event) {
  244. unsigned int button = 0;
  245. switch(event->button()) {
  246. case Qt::LeftButton:
  247. button = 1;
  248. break;
  249. case Qt::MiddleButton:
  250. button = 2;
  251. break;
  252. case Qt::RightButton:
  253. button = 3;
  254. break;
  255. default:
  256. break;
  257. }
  258. auto pixelRatio = this->devicePixelRatio();
  259. this->getEventQueue()->mouseButtonPress(static_cast<float>(event->position().x() * pixelRatio), static_cast<float>(event->position().y() * pixelRatio), button);
  260. }
  261. void OSGWidget::mouseReleaseEvent(QMouseEvent* event) {
  262. unsigned int button = 0;
  263. switch(event->button()) {
  264. case Qt::LeftButton:
  265. button = 1;
  266. break;
  267. case Qt::MiddleButton:
  268. button = 2;
  269. break;
  270. case Qt::RightButton:
  271. button = 3;
  272. break;
  273. default:
  274. break;
  275. }
  276. auto pixelRatio = this->devicePixelRatio();
  277. this->getEventQueue()->mouseButtonRelease(static_cast<float>(event->position().x() * pixelRatio), static_cast<float>(event->position().y() * pixelRatio), button);
  278. }
  279. void OSGWidget::wheelEvent(QWheelEvent* event) {
  280. event->accept();
  281. int delta = event->angleDelta().y();
  282. osgGA::GUIEventAdapter::ScrollingMotion motion = delta > 0 ? osgGA::GUIEventAdapter::SCROLL_UP : osgGA::GUIEventAdapter::SCROLL_DOWN;
  283. this->getEventQueue()->mouseScroll(motion);
  284. }
  285. bool OSGWidget::event(QEvent* event) {
  286. bool handled = QOpenGLWidget::event(event);
  287. // This ensures that the OSG widget is always going to be repainted after the
  288. // user performed some interaction. Doing this in the event handler ensures
  289. // that we don't forget about some event and prevents duplicate code.
  290. switch(event->type()) {
  291. case QEvent::KeyPress:
  292. case QEvent::KeyRelease:
  293. case QEvent::MouseButtonDblClick:
  294. case QEvent::MouseButtonPress:
  295. case QEvent::MouseButtonRelease:
  296. case QEvent::MouseMove:
  297. case QEvent::Wheel:
  298. this->update();
  299. break;
  300. case QEvent::Resize:
  301. this->onResize(this->width(), this->height());
  302. break;
  303. default:
  304. break;
  305. }
  306. return handled;
  307. }
  308. void OSGWidget::onHome() {
  309. osgViewer::ViewerBase::Views views;
  310. _viewer->getViews( views );
  311. for(std::size_t i = 0; i < views.size(); i++) {
  312. osgViewer::View* view = views.at(i);
  313. view->home();
  314. }
  315. }
  316. void OSGWidget::onResize(int width, int height) {
  317. std::vector<osg::Camera*> cameras;
  318. _viewer->getCameras(cameras);
  319. assert(cameras.size() == 1);
  320. auto pixelRatio = this->devicePixelRatio();
  321. cameras[0]->setViewport(0, 0, width * pixelRatio, height * pixelRatio);
  322. }
  323. osgGA::EventQueue* OSGWidget::getEventQueue() const {
  324. osgGA::EventQueue* eventQueue = graphicsWindow_->getEventQueue();
  325. if (eventQueue) {
  326. return eventQueue;
  327. } else {
  328. throw std::runtime_error("Unable to obtain valid event queue");
  329. }
  330. }
  331. osg::ref_ptr<osg::Group> OSGWidget::createAxesPreview() {
  332. osg::ref_ptr<osg::Group> axesPreview = new osg::Group;
  333. osg::Vec4 red = osg::Vec4(1.0f, 0.0f, 0.0f, 1.0f);
  334. osg::Vec4 green = osg::Vec4(0.0f, 1.0f, 0.0f, 1.0f);
  335. osg::Vec4 blue = osg::Vec4(0.0f, 0.0f, 1.0f, 1.0f);
  336. osg::ref_ptr<osg::MatrixTransform> xRotation = new osg::MatrixTransform;
  337. xRotation->setMatrix(osg::Matrix::rotate(osg::Vec3f(0.0f, 0.0f, 1.0f), osg::Vec3f(1.0f, 0.0f, 0.0f)));
  338. osg::ref_ptr<osg::Geode> xAxis = new osg::Geode;
  339. osg::ref_ptr<osg::ShapeDrawable> xAxisShape = new osg::ShapeDrawable();
  340. xAxisShape->setShape(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.5f), 0.01f, 1.0f));
  341. xAxisShape->setColor(red);
  342. xAxis->addDrawable(xAxisShape.get());
  343. osg::ref_ptr<osg::ShapeDrawable> xConeShape = new osg::ShapeDrawable();
  344. xConeShape->setShape(new osg::Cone(osg::Vec3(0.0f, 0.0f, 1.0f), 0.05f, 0.2f));
  345. xConeShape->setColor(red);
  346. xAxis->addDrawable(xConeShape.get());
  347. xRotation->addChild(xAxis.get());
  348. osg::ref_ptr<osg::MatrixTransform> yRotation = new osg::MatrixTransform;
  349. yRotation->setMatrix(osg::Matrix::rotate(osg::Vec3f(0.0f, 0.0f, 1.0f), osg::Vec3f(0.0f, 1.0f, 0.0f)));
  350. osg::ref_ptr<osg::Geode> yAxis = new osg::Geode;
  351. osg::ref_ptr<osg::ShapeDrawable> yAxisShape = new osg::ShapeDrawable();
  352. yAxisShape->setShape(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.5f), 0.01f, 1.0f));
  353. yAxisShape->setColor(green);
  354. yAxis->addDrawable(yAxisShape.get());
  355. osg::ref_ptr<osg::ShapeDrawable> yConeShape = new osg::ShapeDrawable();
  356. yConeShape->setShape(new osg::Cone(osg::Vec3(0.0f, 0.0f, 1.0f), 0.05f, 0.2f));
  357. yConeShape->setColor(green);
  358. yAxis->addDrawable(yConeShape.get());
  359. yRotation->addChild(yAxis.get());
  360. osg::ref_ptr<osg::Geode> zAxis = new osg::Geode;
  361. osg::ref_ptr<osg::ShapeDrawable> zAxisShape = new osg::ShapeDrawable();
  362. zAxisShape->setShape(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.5f), 0.01f, 1.0f));
  363. zAxisShape->setColor(blue);
  364. osg::ref_ptr<osg::ShapeDrawable> zConeShape = new osg::ShapeDrawable();
  365. zConeShape->setShape(new osg::Cone(osg::Vec3(0.0f, 0.0f, 1.0f), 0.05f, 0.2f));
  366. zConeShape->setColor(blue);
  367. zAxis->addDrawable(zConeShape.get());
  368. zAxis->addDrawable(zAxisShape.get());
  369. axesPreview->addChild(xRotation.get());
  370. axesPreview->addChild(yRotation.get());
  371. axesPreview->addChild(zAxis.get());
  372. OSGWidget::fixMaterialState(axesPreview);
  373. return axesPreview;
  374. }