用OpenSceneGraph实现的NeHe OpenGL教程 - 第四十五课

  • 简介

这节课NeHe课程主要向我们演示了怎么使用OpenGL中的VertexBufferObject,VBO的介绍可以参考另一篇文章VA VAO和VBO API备忘

在OSG中默认绘制Drawable的时候采用了显示列表的方式,另外也可以通过

virtual void  setUseVertexBufferObjects (bool flag)
来在VBO和显示列表之间进行切换。在我们之前的课程中,当需要修改Geometry中顶点位置和颜色等属性时(一般在OSG::Drawable::Update),都会使用这个函数切换几何体的绘制方式为VBO,从而实现修改其中的数据。

  • 实现

本课的实现过程十分简单,从灰度图中读取像素灰度值然后转换成顶点的高度:

	int nPos = ( ( nX % image->s() )  + ( ( nY % image->t() ) * image->s() ) ) * 3;
	float flR = (float) image->data()[ nPos ];
	float flG = (float) image->data()[ nPos + 1 ];
	float flB = (float) image->data()[ nPos + 2 ];
	return ( 0.299f * flR + 0.587f * flG + 0.114f * flB );

绘制整个地形:

osg::Geode*  loadHeightmap( char* szPath, float flHeightScale, float flResolution )
{
	FILE* fTest = fopen( szPath, "r" );
	if( !fTest )
		return false;
	fclose( fTest );

	osg::Geode *geode = new osg::Geode;
	osg::Geometry *geometry = new osg::Geometry;

	osg::Image *image = osgDB::readImageFile("Terrain.bmp");
	int nVertexCount = (int)(image->s() * image->t() * 6 / (flResolution * flResolution));

	osg::Vec3Array *vertexArray = new osg::Vec3Array;
	osg::Vec2Array *textureArray = new osg::Vec2Array;

	int nX, nZ, nTri, nIndex=0;
	float flX, flZ;
	for( nZ = 0; nZ < image->t(); nZ += (int) flResolution )
	{
		for( nX = 0; nX < image->s(); nX += (int) flResolution )
		{
			for( nTri = 0; nTri < 6; nTri++ )
			{
				flX = (float) nX + ( ( nTri == 1 || nTri == 2 || nTri == 5 ) ? flResolution : 0.0f );
				flZ = (float) nZ + ( ( nTri == 2 || nTri == 4 || nTri == 5 ) ? flResolution : 0.0f );
				vertexArray->push_back(osg::Vec3(flX - ( image->s() / 2 ), ptHeight( (int) flX, (int) flZ, image ) *  flHeightScale, flZ - ( image->t() / 2 )));
				textureArray->push_back(osg::Vec2(flX / image->s(), flZ / image->t()));
				nIndex++;
			}
		}
	}
	
	osg::Texture2D *texture2D = new osg::Texture2D;
	texture2D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
	texture2D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
	texture2D->setImage(image);
	geometry->setVertexArray(vertexArray);
	geometry->setTexCoordArray(0, textureArray);
	geometry->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture2D);
	geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, vertexArray->size()));
	geometry->setUseVertexBufferObjects(true);
	geode->addDrawable(geometry);

	return geode;
}

编译运行程序:

用OpenSceneGraph实现的NeHe OpenGL教程 - 第四十五课_第1张图片

附:本课源码(源码中可能存在错误和不足,仅供参考)

#include "../osgNeHe.h"

#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QVBoxLayout>

#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <osgQt/GraphicsWindowQt>

#include <osg/MatrixTransform>
#include <osg/PolygonMode>

#include <osg/Image>
#include <osg/Texture2D>

#include <osg/AnimationPath>


#define MESH_RESOLUTION 4.0f
#define MESH_HEIGHTSCALE 1.0f

//////////////////////////////////////////////////////////////////////////

float ptHeight( int nX, int nY, osg::Image *image)
{
	int nPos = ( ( nX % image->s() )  + ( ( nY % image->t() ) * image->s() ) ) * 3;
	float flR = (float) image->data()[ nPos ];
	float flG = (float) image->data()[ nPos + 1 ];
	float flB = (float) image->data()[ nPos + 2 ];
	return ( 0.299f * flR + 0.587f * flG + 0.114f * flB );
}


osg::Geode*  loadHeightmap( char* szPath, float flHeightScale, float flResolution )
{
	FILE* fTest = fopen( szPath, "r" );
	if( !fTest )
		return false;
	fclose( fTest );

	osg::Geode *geode = new osg::Geode;
	osg::Geometry *geometry = new osg::Geometry;

	osg::Image *image = osgDB::readImageFile("Terrain.bmp");
	int nVertexCount = (int)(image->s() * image->t() * 6 / (flResolution * flResolution));

	osg::Vec3Array *vertexArray = new osg::Vec3Array;
	osg::Vec2Array *textureArray = new osg::Vec2Array;

	int nX, nZ, nTri, nIndex=0;
	float flX, flZ;
	for( nZ = 0; nZ < image->t(); nZ += (int) flResolution )
	{
		for( nX = 0; nX < image->s(); nX += (int) flResolution )
		{
			for( nTri = 0; nTri < 6; nTri++ )
			{
				flX = (float) nX + ( ( nTri == 1 || nTri == 2 || nTri == 5 ) ? flResolution : 0.0f );
				flZ = (float) nZ + ( ( nTri == 2 || nTri == 4 || nTri == 5 ) ? flResolution : 0.0f );
				vertexArray->push_back(osg::Vec3(flX - ( image->s() / 2 ), ptHeight( (int) flX, (int) flZ, image ) *  flHeightScale, flZ - ( image->t() / 2 )));
				textureArray->push_back(osg::Vec2(flX / image->s(), flZ / image->t()));
				nIndex++;
			}
		}
	}
	
	osg::Texture2D *texture2D = new osg::Texture2D;
	texture2D->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
	texture2D->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
	texture2D->setImage(image);
	geometry->setVertexArray(vertexArray);
	geometry->setTexCoordArray(0, textureArray);
	geometry->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture2D);
	geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, vertexArray->size()));
	geometry->setUseVertexBufferObjects(true);
	geode->addDrawable(geometry);

	return geode;
}



class ViewerWidget : public QWidget, public osgViewer::Viewer
{
public:
	ViewerWidget(osg::Node *scene = NULL)
	{
		QWidget* renderWidget = getRenderWidget( createGraphicsWindow(0,0,640,480), scene);

		QVBoxLayout* layout = new QVBoxLayout;
		layout->addWidget(renderWidget);
		layout->setContentsMargins(0, 0, 0, 1);
		setLayout( layout );

		connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );
		_timer.start( 10 );
	}

	QWidget* getRenderWidget( osgQt::GraphicsWindowQt* gw, osg::Node* scene )
	{
		osg::Camera* camera = this->getCamera();
		camera->setGraphicsContext( gw );

		const osg::GraphicsContext::Traits* traits = gw->getTraits();

		camera->setClearColor( osg::Vec4(0.0, 0.0, 0.0, 1.0) );
		camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );
		camera->setProjectionMatrixAsPerspective(45.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 0.1f, 100.0f );		
		camera->setViewMatrixAsLookAt(osg::Vec3d(0.0f, 0.0f, 1.0f), osg::Vec3d(0, 0, 0), osg::Vec3d(0, 1, 0));

		this->setSceneData( scene );

		return gw->getGLWidget();
	}

	osgQt::GraphicsWindowQt* createGraphicsWindow( int x, int y, int w, int h, const std::string& name="", bool windowDecoration=false )
	{
		osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
		osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
		traits->windowName = name;
		traits->windowDecoration = windowDecoration;
		traits->x = x;
		traits->y = y;
		traits->width = w;
		traits->height = h;
		traits->doubleBuffer = true;
		traits->alpha = ds->getMinimumNumAlphaBits();
		traits->stencil = ds->getMinimumNumStencilBits();
		traits->sampleBuffers = ds->getMultiSamples();
		traits->samples = ds->getNumMultiSamples();

		return new osgQt::GraphicsWindowQt(traits.get());
	}

	virtual void paintEvent( QPaintEvent* event )
	{ 
		frame(); 
	}

protected:

	QTimer _timer;
};



osg::Node*	buildScene()
{
	osg::Group *root = new osg::Group;

	osg::MatrixTransform *zoomMT = new osg::MatrixTransform;
	zoomMT->setMatrix(osg::Matrix::translate(0.0f, -220.0f, 0.0f));

	osg::MatrixTransform *rotateSlightMT = new osg::MatrixTransform;
	rotateSlightMT->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(10.0), osg::X_AXIS));

	osg::MatrixTransform *rotateYMT = new osg::MatrixTransform;
	rotateYMT->addUpdateCallback(new osg::AnimationPathCallback(osg::Vec3(), osg::Y_AXIS, 0.3));

	root->addChild(zoomMT);
	zoomMT->addChild(rotateSlightMT);
	rotateSlightMT->addChild(rotateYMT);
	rotateYMT->addChild(loadHeightmap("terrain.bmp", MESH_HEIGHTSCALE, MESH_RESOLUTION));

	return root;
}



int main( int argc, char** argv )
{
	QApplication app(argc, argv);
	ViewerWidget* viewWidget = new ViewerWidget(buildScene());
	viewWidget->setGeometry( 100, 100, 640, 480 );
	viewWidget->show();
	return app.exec();
}

你可能感兴趣的:(C++,qt,OpenGL,nehe,OSG)