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

  • 简介

NeHe教程在这节课向我们介绍了如何从一个2D的灰度图创建地形。这节课的内容比较简单,只是从一个2D灰度图中读取灰度数据,然后将灰度数据转换成高度数据,最后将这些数据显示出来就可以了。

  • 实现

首先读取raw格式的图片,将里面的灰度值转换成Y值:

void LoadRawFile(LPSTR strName, int nSize, BYTE *pHeightMap) //读取灰度图
{
	FILE *pFile = NULL;
	pFile = fopen( strName, "rb" );
	if ( pFile == NULL )	
	{
		return;
	}
	fread( pHeightMap, 1, nSize, pFile );
	int result = ferror( pFile );
	fclose(pFile);
}
int Height(BYTE *pHeightMap, int X, int Y)				// This Returns The Height From A Height Map Index
{
	int x = X % MAP_SIZE;								// Error Check Our x Value
	int y = Y % MAP_SIZE;								// Error Check Our y Value

	if(!pHeightMap) return 0;							// Make Sure Our Data Is Valid

	return pHeightMap[x + (y * MAP_SIZE)];				// Index Into Our Height Array And Return The Height
}
读取完成之后,创建整个网格:

osg::Geode* RenderHeightMap(BYTE pHeightMap[])

最后在与鼠标的交互中切换显示的模式:

		case(osgGA::GUIEventAdapter::PUSH):
			{
				if (ea.getButtonMask() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
				{
					if (!g_TerrainGeometry)
						return false;
					osg::Vec3Array *vertexArray = dynamic_cast<osg::Vec3Array*>(g_TerrainGeometry->getVertexArray());
					if (!vertexArray)
						return false;
					
					static bool flag = true;
					if (flag){
						g_TerrainGeometry->setPrimitiveSet(0, new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertexArray->size()));
						flag = !flag;
					} else {
						g_TerrainGeometry->setPrimitiveSet(0, new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, vertexArray->size()));
						flag = !flag;
					}
				}
			}
将所有部分添加到场景,编译运行程序:

用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>


#define		MAP_SIZE	  1024
#define		STEP_SIZE	  16
#define		HEIGHT_RATIO  1.5f

BYTE g_HeightMap[MAP_SIZE*MAP_SIZE];
float scaleValue = 0.15f;
osg::Geometry *g_TerrainGeometry = NULL;


void LoadRawFile(LPSTR strName, int nSize, BYTE *pHeightMap)
{
	FILE *pFile = NULL;
	pFile = fopen( strName, "rb" );
	if ( pFile == NULL )	
	{
		return;
	}
	fread( pHeightMap, 1, nSize, pFile );
	int result = ferror( pFile );
	fclose(pFile);
}


int Height(BYTE *pHeightMap, int X, int Y)				// This Returns The Height From A Height Map Index
{
	int x = X % MAP_SIZE;								// Error Check Our x Value
	int y = Y % MAP_SIZE;								// Error Check Our y Value

	if(!pHeightMap) return 0;							// Make Sure Our Data Is Valid

	return pHeightMap[x + (y * MAP_SIZE)];				// Index Into Our Height Array And Return The Height
}


osg::Vec3 SetVertexColor(BYTE *pHeightMap, int x, int y) 
{
	float fColor = -0.15f + (Height(pHeightMap, x, y ) / 256.0f);
	return osg::Vec3(0, 0, fColor );
}


osg::Geode* RenderHeightMap(BYTE pHeightMap[])
{
	int X = 0, Y = 0;
	int x, y=0, z;	

	osg::Geode *terrainGeode = new osg::Geode;
	osg::Geometry *terrainGeomety = new osg::Geometry;
	osg::Vec3Array *vertexArray = new osg::Vec3Array;
	osg::Vec3Array *colorArray = new osg::Vec3Array;

	for ( X = 0; X < (MAP_SIZE-STEP_SIZE); X += STEP_SIZE )
		for ( Y = 0; Y < (MAP_SIZE-STEP_SIZE); Y += STEP_SIZE )
		{
			//左下点坐标
			x = X;							
			y = Height(pHeightMap, X, Y );	
			z = Y;							
			vertexArray->push_back(osg::Vec3(x, y, z));
	
			osg::Vec3 colorLeftBottom = SetVertexColor(pHeightMap, x, z);
			colorArray->push_back(colorLeftBottom);

			//左上点坐标
			x = X;										
			y = Height(pHeightMap, X, Y + STEP_SIZE );  
			z = Y + STEP_SIZE ;
			vertexArray->push_back(osg::Vec3(x, y, z));

			osg::Vec3 colorLeftTop = SetVertexColor(pHeightMap, x, z);
			colorArray->push_back(colorLeftTop);

			// 右上点坐标
			x = X + STEP_SIZE; 
			y = Height(pHeightMap, X + STEP_SIZE, Y + STEP_SIZE ); 
			z = Y + STEP_SIZE ;
			vertexArray->push_back(osg::Vec3(x, y, z));

			osg::Vec3 colorRightTop = SetVertexColor(pHeightMap, x, z);
			colorArray->push_back(colorRightTop);

			// Get The (X, Y, Z) Value For The Bottom Right Vertex
			x = X + STEP_SIZE; 
			y = Height(pHeightMap, X + STEP_SIZE, Y ); 
			z = Y;
			vertexArray->push_back(osg::Vec3(x, y, z));

			osg::Vec3 colorRightBottom = SetVertexColor(pHeightMap, x, z);
			colorArray->push_back(colorRightBottom);
		}

        terrainGeomety->setVertexArray(vertexArray);
		terrainGeomety->setColorArray(colorArray, osg::Array::BIND_PER_VERTEX);
		terrainGeomety->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, vertexArray->size()));
		terrainGeomety->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
		g_TerrainGeometry = terrainGeomety;

		terrainGeode->addDrawable(terrainGeomety);
		return terrainGeode;
}


//////////////////////////////////////////////////////////////////////////
class ManipulatorSceneHandler : public osgGA::GUIEventHandler
{
public:
	ManipulatorSceneHandler()
	{
	}

	virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
	{
		osgViewer::Viewer *viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
		if (!viewer)
			return false;
		if (!viewer->getSceneData())
			return false;
		if (ea.getHandled()) 
			return false;

		switch(ea.getEventType())
		{
		case(osgGA::GUIEventAdapter::PUSH):
			{
				if (ea.getButtonMask() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
				{
					if (!g_TerrainGeometry)
						return false;
					osg::Vec3Array *vertexArray = dynamic_cast<osg::Vec3Array*>(g_TerrainGeometry->getVertexArray());
					if (!vertexArray)
						return false;
					
					static bool flag = true;
					if (flag){
						g_TerrainGeometry->setPrimitiveSet(0, new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertexArray->size()));
						flag = !flag;
					} else {
						g_TerrainGeometry->setPrimitiveSet(0, new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, vertexArray->size()));
						flag = !flag;
					}
				}
			}
		default: break;
		}
		return false;
	}
};
//////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////////
/////////////////////osgNeHe框架//////////////////////////////////
//////////////////////////////////////////////////////////////////////////

class ViewerWidget : public QWidget, public osgViewer::Viewer
{
public:
	ViewerWidget(osg::Node *scene = NULL)
	{
		QWidget* renderWidget = getRenderWidget( createGraphicsWindow(0,0,100,100), 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.0f, 0.0f, 0.0f, 0.5f) );
		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(212, 60, 194), osg::Vec3d(186, 55, 171), osg::Vec3d(0, 1, 0));

		this->setSceneData( scene );
		this->addEventHandler(new ManipulatorSceneHandler);
		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()
{
	LoadRawFile("Data/Terrain.raw", MAP_SIZE * MAP_SIZE, g_HeightMap);

	osg::Group *root = new osg::Group;
	osg::MatrixTransform *scaleMT = new osg::MatrixTransform;
	scaleMT->setMatrix(osg::Matrix::scale(scaleValue, scaleValue * HEIGHT_RATIO, scaleValue));
	scaleMT->addChild(RenderHeightMap(g_HeightMap));
	root->addChild(scaleMT);

	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)