二、添加OSG类
#pragma once
#include
#include
#include
#include
class osgFrame
{
public:
osgFrame(HWND hWnd);
~osgFrame();
void InitOSG(); //初始化OSG
void InitSceneGraph(); //初始化场景
void InitCamera(); //初始化相机
void PreFrameUpdate(); //帧渲染之前更新
void PostFrameUpdate(); //帧渲染之后更新
static void Render(void *ptr); //渲染进程
osgViewer::Viewer *getViewer();
private:
HWND m_hWnd;
osgViewer::Viewer *mViewer;
osg::ref_ptr mRoot;
};
#include "stdafx.h"
#include "osgFrame.h"
osgFrame::osgFrame(HWND hWnd)
{
m_hWnd = hWnd;
}
osgFrame::~osgFrame()
{
}
void osgFrame::InitOSG()
{
InitSceneGraph();
InitCamera();
}
void osgFrame::InitSceneGraph()
{
mRoot = new osg::Group();
mRoot->addChild(osgDB::readNodeFile("cow.osg"));
}
void osgFrame::InitCamera()
{
RECT rect;
mViewer = new osgViewer::Viewer();
::GetWindowRect(m_hWnd, &rect);
osg::ref_ptr traits = new osg::GraphicsContext::Traits();
osg::ref_ptr windata = new osgViewer::GraphicsWindowWin32::WindowData(m_hWnd);
traits->x = 0;
traits->y = 0;
traits->width = rect.right - rect.left;
traits->height = rect.bottom - rect.top;
traits->windowDecoration = false;
traits->doubleBuffer = true;
traits->sharedContext = 0;
traits->setInheritedWindowPixelFormat = true;
traits->inheritedWindowData = windata;
osg::GraphicsContext *gc = osg::GraphicsContext::createGraphicsContext(traits);
osg::ref_ptr camera = new osg::Camera();
camera->setGraphicsContext(gc);
camera->setViewport(new osg::Viewport(traits->x, traits->y, traits->width, traits->height));
camera->setProjectionMatrixAsPerspective(30.0f, static_cast(traits->width) / static_cast(traits->height), 1.0, 1000.0);
mViewer->setCamera(camera);
mViewer->setCameraManipulator(new osgGA::TrackballManipulator);
mViewer->setSceneData(mRoot);
mViewer->realize();
mViewer->getCamera()->setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
mViewer->getCamera()->setNearFarRatio(0.000003f);
}
void osgFrame::PreFrameUpdate()
{
//
}
void osgFrame::PostFrameUpdate()
{
//
}
void osgFrame::Render(void* ptr)
{
osgFrame *osg = (osgFrame*)ptr;
osgViewer::Viewer *viewer = osg->getViewer();
while (!viewer->done())
{
osg->PreFrameUpdate();
viewer->frame();
osg->PostFrameUpdate();
}
_endthread();
}
osgViewer::Viewer *osgFrame::getViewer()
{
return mViewer;
}
osgFrame* mOSG;
int COsgMFCView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
{
return -1;
}
else
{
mOSG = new osgFrame(m_hWnd); //创建osgFrame对象
}
return 0;
}
BOOL COsgMFCView::OnEraseBkgnd(CDC* pDC)
{
if (0 == mOSG)
{
return CView::OnEraseBkgnd(pDC);
}
else
{
return FALSE;
}
return CView::OnEraseBkgnd(pDC);
}
void COsgMFCView::OnDestroy()
{
CView::OnDestroy();
if (mOSG != 0)
{
delete mOSG;
}
WaitForSingleObject(mThreadHandle, 1000);
}
void COsgMFCView::OnInitialUpdate()
{
CView::OnInitialUpdate();
mOSG->InitOSG();
mThreadHandle = (HANDLE)_beginthread(&osgFrame::Render, 0, mOSG);
}