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

  • 简介

NeHe教程在这节课向我们介绍了Cg编程技术。Gg是nVidio公司面向GPU的语言,类似的语言还有微软的HLSL,OpenGL的GLSL,ATI的shaderMonker。关于可编程的着色语言可以在网络上找到很多的学习资源,这也是新式OpenGL的特点之一。可以预见未来随着GPU的发展,越来越多的固定管线部分可以被可编程的部分所替代。考虑到在OSG中使用GLSL比较方便,本课使用GLSL来实现。

  • 实现

在OSG中可编程的Shader部分是通过osg::Program和osg::Shader进行了封装,同时把osg::Progarm作为一种StateAttribute添加到节点之中。

首先创建网状的场景

osg::Geode*	createFlagGeode()
{
	osg::Geode* geode = new osg::Geode;
	osg::Geometry *geometry = new osg::Geometry;
	osg::Vec3Array *vertexArray = new osg::Vec3Array;
	for (int x = 0; x < SIZE - 1; x++)
	{
		for (int z = 0; z < SIZE - 1; z++)
		{
			vertexArray->push_back(osg::Vec3(mesh[x][z][0], mesh[x][z][1], mesh[x][z][2]));
			vertexArray->push_back(osg::Vec3(mesh[x+1][z][0], mesh[x+1][z][1], mesh[x+1][z][2]));
			wave_movement += 0.00001f;
			if (wave_movement > TWO_PI)
				wave_movement = 0.0f;
		}
	}
	geometry->setVertexArray(vertexArray);
	osg::PolygonMode *pm = new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE);
	geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_STRIP, 0, vertexArray->size()));
	geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	geometry->getOrCreateStateSet()->setAttributeAndModes(pm);

	osg::Uniform *uniform = new osg::Uniform("animStep", wave_movement);
	uniform->setUpdateCallback(new MoveUpdateCallback);
	geometry->getStateSet()->addUniform(uniform);
	
	osg::Shader *vertexShader = new osg::Shader(osg::Shader::VERTEX, vShader);
	osg::Shader *fragmentShader = new osg::Shader(osg::Shader::FRAGMENT, fShader);
	osg::Program *program = new osg::Program();
	program->addShader(vertexShader);
	program->addShader(fragmentShader);
	geometry->getOrCreateStateSet()->setAttributeAndModes(program);
	
	geode->addDrawable(geometry);

	return geode;
}

在OSG中Shader可以写到单独的文件中,使用osgDB::readShaderFile来读取,对于简单的shader可以直接写到字符串中:

VertexShader:

static const char*		vShader = {
	"#version 330\n"
	"in vec4 inVertex;\n"
	"uniform float animStep;\n"
	"void main(){\n"
	"vec4 tmp = inVertex;\n"
	"tmp.y = ( sin(animStep + (tmp.x / 5.0) ) + sin(animStep + (tmp.z / 4.0) ) ) * 2.5;\n"
	"gl_Position = gl_ModelViewProjectionMatrix * tmp;\n"
	"}\n"
};

FragmentShader:

static const char*		fShader = {
	"#version 330\n"
	"out vec4 fragColor;\n"
	"void main(){\n"
	"fragColor = vec4(0.5, 1.0, 0.5, 1.0);\n"
	"}\n"
};

在顶点Shader中不断的修改网状几何体的y值,形成一种类似于正弦波的效果,带代码中需要我们修改Uniform的值,让模型呈现动态的效果。

可以在Uniform的回调中完成:

class MoveUpdateCallback : public osg::Uniform::Callback
{
	virtual void operator()(osg::Uniform *uniform, osg::NodeVisitor *nv)
	{
		if(!uniform)
			return;

		float animStep;
		uniform->get(animStep);

		//按照NeHe课程中方式每帧改变64*64*0.00001
		for (int x = 0; x < SIZE - 1; x++)
		{
			for (int z = 0; z < SIZE - 1; z++)
			{
				wave_movement += 0.00001f;
				if (wave_movement > TWO_PI)
					wave_movement = 0.0f;
			}
		}		
		animStep = wave_movement;
		uniform->set(animStep);
	}
};

把节点添加到根节点下,编译运行程序:

用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/Shader>
#include <osg/Uniform>
#include <osg/Program>

//////////////////////////////////////////////////////////////////////////
#define		TWO_PI 6.2831853071									
#define		SIZE	64
GLfloat		mesh[SIZE][SIZE][3];	
GLfloat		wave_movement = 0.0f;
//////////////////////////////////////////////////////////////////////////


static const char*		vShader = {
	"#version 330\n"
	"in vec4 inVertex;\n"
	"uniform float animStep;\n"
	"void main(){\n"
	"vec4 tmp = inVertex;\n"
	"tmp.y = ( sin(animStep + (tmp.x / 5.0) ) + sin(animStep + (tmp.z / 4.0) ) ) * 2.5;\n"
	"gl_Position = gl_ModelViewProjectionMatrix * tmp;\n"
	"}\n"
};

static const char*		fShader = {
	"#version 330\n"
	"out vec4 fragColor;\n"
	"void main(){\n"
	"fragColor = vec4(0.5, 1.0, 0.5, 1.0);\n"
	"}\n"
};


class MoveUpdateCallback : public osg::Uniform::Callback
{
	virtual void operator()(osg::Uniform *uniform, osg::NodeVisitor *nv)
	{
		if(!uniform)
			return;

		float animStep;
		uniform->get(animStep);

		//按照NeHe课程中方式每帧改变64*64*0.00001
		for (int x = 0; x < SIZE - 1; x++)
		{
			for (int z = 0; z < SIZE - 1; z++)
			{
				wave_movement += 0.00001f;
				if (wave_movement > TWO_PI)
					wave_movement = 0.0f;
			}
		}		
		animStep = wave_movement;
		uniform->set(animStep);
	}
};



void initialize()
{
	for (int x = 0; x < SIZE; x++)
	{
		for (int z = 0; z < SIZE; z++)
		{
			mesh[x][z][0] = (float) (SIZE / 2) - x;
			mesh[x][z][1] = 0.0f;
			mesh[x][z][2] = (float) (SIZE / 2) - z;
		}
	}
}


osg::Geode*	createFlagGeode()
{
	osg::Geode* geode = new osg::Geode;
	osg::Geometry *geometry = new osg::Geometry;
	osg::Vec3Array *vertexArray = new osg::Vec3Array;
	for (int x = 0; x < SIZE - 1; x++)
	{
		for (int z = 0; z < SIZE - 1; z++)
		{
			vertexArray->push_back(osg::Vec3(mesh[x][z][0], mesh[x][z][1], mesh[x][z][2]));
			vertexArray->push_back(osg::Vec3(mesh[x+1][z][0], mesh[x+1][z][1], mesh[x+1][z][2]));
			wave_movement += 0.00001f;
			if (wave_movement > TWO_PI)
				wave_movement = 0.0f;
		}
	}
	geometry->setVertexArray(vertexArray);
	osg::PolygonMode *pm = new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE);
	geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_STRIP, 0, vertexArray->size()));
	geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	geometry->getOrCreateStateSet()->setAttributeAndModes(pm);

	osg::Uniform *uniform = new osg::Uniform("animStep", wave_movement);
	uniform->setUpdateCallback(new MoveUpdateCallback);
	geometry->getStateSet()->addUniform(uniform);
	
	osg::Shader *vertexShader = new osg::Shader(osg::Shader::VERTEX, vShader);
	osg::Shader *fragmentShader = new osg::Shader(osg::Shader::FRAGMENT, fShader);
	osg::Program *program = new osg::Program();
	program->addShader(vertexShader);
	program->addShader(fragmentShader);
	geometry->getOrCreateStateSet()->setAttributeAndModes(program);
	
	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, 25.0f, -45.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()
{
	initialize();

	osg::Group *root = new osg::Group;
	root->addChild(createFlagGeode());
	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)