1.
HUD流程圖:
完整原始碼如下:
/*OSG中的HUD,文字總是顯示在最前面*/
#include
<osgDB/ReadFile>
#include
<osgViewer/Viewer>
#include
<osg/Geode>
#include
<osg/Depth>
#include
<osg/CameraNode>
#include
<osgText/Text>
#pragma
comment( lib,
"osgd.lib"); //.在Debug版本下的庫名都加d,如"osgd.lib"
#pragma
comment( lib,
"osgDBd.lib")
#pragma
comment( lib,
"osgViewerd.lib");
#pragma
comment( lib,
"osgTextd.lib");
osg::Node* createHUD()
{
//文字
osgText::Text* text = new osgText::Text;
//設定字型
std::string caiyun("fonts /STCAIYUN.TTF");//此處設定的是漢字字型
text->setFont(caiyun);
//設定文字顯示的位置
osg::Vec3 position(150.0f,500.0f,0.0f);
text->setPosition(position);
text->setColor( osg::Vec4( 1, 1, 0, 1));
text->setText(L"osg中國官網網站www.osgChina.org");//設定顯示的文字
//幾何體節點
osg::Geode* geode = new osg::Geode();
geode->addDrawable( text );//將文字Text作這drawable加入到Geode節點中
//設定狀態
osg::StateSet* stateset = geode->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);//關閉燈光
stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);//關閉深度測試
//開啟GL_BLEND混合模式(以保證Alpha紋理正確)
stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
//相機
osg::Camera* camera = new osg::Camera;
//設定透視矩陣
camera->setProjectionMatrix(osg::Matrix::ortho2D(0,600,0,600));//正交投影
//設定絕對參考座標系,確保視圖矩陣不會被上級節點的變換矩陣影響
camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
//視圖矩陣為預設的
camera->setViewMatrix(osg::Matrix::identity());
//設定背景為透明,否則的話可以設定ClearColor
camera->setClearMask(GL_DEPTH_BUFFER_BIT);
camera->setAllowEventFocus( false);//不響應事件,始終得不到焦點
//設定渲染順序,必須在最後渲染
camera->setRenderOrder(osg::CameraNode::POST_RENDER);
camera->addChild(geode);//將要顯示的Geode節點加入到相機
return camera;
};
int main(
int argc, char **argv )
{
osgViewer::Viewer viewer;
osg::ref_ptr<osg::Node> model = osgDB::readNodeFile("fountain.osg");
osg::ref_ptr<osg::Group> root= new osg::Group;
root->addChild( model.get());//加入某個模型
root->addChild(createHUD());//把HUD文字的相機加入到根節點下
viewer.setSceneData( root.get());
viewer.realize();
viewer.run() ;
return 0;
}