利用Qt来显示OSG并且设置相机的位置

#pragma once
#include 
#include 
#include 

class OsgCanvas2 :public QOpenGLWidget {
public:
	OsgCanvas2(QWidget *parent);
	~OsgCanvas2();

private:
	void init();

	virtual void initializeGL();
	virtual void resizeGL(int w, int h);
	virtual void paintGL();
private:
	osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _graphicsContext;
	osg::ref_ptr<osgViewer::Viewer> _viewer;

	osg::ref_ptr<osg::Group> _root;
};


#include "OsgCanvas2.h"
#include 
#include 
#include 
#include 
#include 

OsgCanvas2::OsgCanvas2(QWidget *parent)
	:QOpenGLWidget(parent){
	init();
}

OsgCanvas2::~OsgCanvas2() {
}

void OsgCanvas2::init() {

	int w = width();
	int h = height();
	//创建显示窗口
	_graphicsContext = new osgViewer::GraphicsWindowEmbedded(0, 0, w, h);

	//读取模型,并且构建模型树
	_root = new osg::Group;
	osg::ref_ptr<osg::Node> cow = osgDB::readNodeFile("F:\\OSG_Qt5.10_64\\OpenSceneGraph-Data-3.0.0\\xyz.osgt");
	_root->addChild(cow);

	//创建相机
	osg::ref_ptr<osg::Camera> camera = new osg::Camera;
	//给相机设置显示窗口
	camera->setGraphicsContext(_graphicsContext);
	//设置视口大小
	camera->setViewport(new osg::Viewport(0, 0, w, h));
	//设置投影矩阵-透视投影
	/*
	para1-上下方向角度
	para2-宽度和高度的比值
	para3-近距离面
	para4-远距离面
	*/
	camera->setProjectionMatrixAsPerspective(30.0, w / (double)h, 1.0, 10000.0);
	//设置背景色
	camera->setClearColor(osg::Vec4(0.2, 0.2, 0.6, 0.5));

	_viewer = new osgViewer::Viewer;
#if 1//设置视点位置不能是漫游器同时使用,否则就会不起作用
	const osg::BoundingSphere bs = _root->getBound();
	osg::Vec3d eye = osg::Vec3(bs.center().x(), -bs.center().y()*10, bs.center().z());
	osg::Vec3d center = bs.center();
	osg::Vec3d up = osg::Vec3(0.0, 0.0, 1.0);
	//设置相机位置
	camera->setViewMatrixAsLookAt(eye, center, up);
#else
	_viewer->setCameraManipulator(new osgGA::TrackballManipulator);
#endif

	_viewer->setCamera(camera);
	

	_viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);
	_viewer->addEventHandler(new osgViewer::WindowSizeHandler);
	_viewer->setSceneData(_root);
}

void OsgCanvas2::initializeGL() {

}

void OsgCanvas2::resizeGL(int w, int h) {
	_graphicsContext->resized(0, 0, w, h);
}

void OsgCanvas2::paintGL() {
	_viewer->frame();
}

利用Qt来显示OSG并且设置相机的位置_第1张图片

你可能感兴趣的:(osg,qt)