根据OpenSceneGraph 3.0 Beginners Guide上在Win32中关联OSG到一个窗口句柄这一部分实际测试了一下,效果如下。
关联Win32窗口句柄到OSG traits,然后到graphics context可以让继承OSG和win32 GUI控制成为可能。
核心是处理了WM_CREATE和WM_DESTROY消息,我把它做了c++的封装,如下:
void render(void*)
{
g_MapViewer.Run();
}
//定义
TMapViewer g_MapViewer;
TMapViewer::TMapViewer()
{
m_bFinished = true;
m_viewer = NULL;
}
TMapViewer::~TMapViewer()
{
}
void TMapViewer::Create(HWND hWnd)
{
osg::ref_ptr<osg::Referenced> windata = new osgViewer::GraphicsWindowWin32::WindowData(hWnd);
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
traits->x = 0;
traits->y = 0;
traits->width = 800;
traits->height = 600;
traits->windowDecoration = false;
traits->doubleBuffer = true;
traits->inheritedWindowData = windata;
osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setGraphicsContext(gc);
camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
camera->setClearColor(osg::Vec4f(0.2f, 0.2f, 0.4f, 1.0f));
camera->setProjectionMatrixAsPerspective(30.0f, (double)traits->width/(double)traits->height, 1.0, 1000.0);
m_viewer = new osgViewer::Viewer;
m_viewer->setCamera(camera.get());
m_viewer->setSceneData(osgDB::readNodeFile("F:\\OSG\\OpenSceneGraph-Data\\SmokeBox.osgt")); // 这里把模型是写死的
m_viewer->setKeyEventSetsDone(0);
m_viewer->setCameraManipulator(new osgGA::TrackballManipulator);
m_bFinished = false;
_beginthread(render, 0, NULL);
}
void TMapViewer::Destroy()
{
m_viewer->setDone(true);
while(!m_bFinished)
{
Sleep(10);
}
}
void TMapViewer::Run()
{
while(!m_viewer->done())
{
m_viewer->frame();
}
m_bFinished = true;
}
在此基础上即可搭建自己的应用了。我将把各种界面以widget的方式实现,测试完后将在下篇博客中分享。