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

  • 简介

NeHe教程在这节课向我们介绍了如何模拟一根绳子的运动状态,简单的说,就是把绳子先离散化,把它想象成一个个紧密排列的点,每两个点之间有弹性约束。其实这就是简单的有限元思想。这节课的内容和上节课一样,主要是和物理、数学有关系,和图形图像的关系不大。

  • 实现

首先我们同样是创建场景中的几何体:

	root->addChild(createGround());   //地面
	root->addChild(createRopeShadow()); //绳子阴影
	root->addChild(createRope());   //绳子

接下来设置各个几何体的更新回调:

osg::Geode*	createRope()
{
	osg::Geode *geode = new osg::Geode;
	osg::Geometry *geometry = new osg::Geometry;
	geometry->setUpdateCallback(new RopeUpdateCallback);
	osg::Vec3Array *vertexArray = new osg::Vec3Array;
	osg::Vec3Array *colorArray = new osg::Vec3Array;

	colorArray->push_back(osg::Vec3(1, 1, 0));

	for (int a = 0; a < ropeSimulation->numOfMasses - 1; ++a)
	{
		Mass* mass1 = ropeSimulation->getMass(a);
		Vector3D* pos1 = &mass1->pos;

		Mass* mass2 = ropeSimulation->getMass(a + 1);
		Vector3D* pos2 = &mass2->pos;

		vertexArray->push_back(osg::Vec3(pos1->x, pos1->y, pos1->z));	
		vertexArray->push_back(osg::Vec3(pos2->x, pos2->y, pos2->z));
	}

	geometry->setVertexArray(vertexArray);
	geometry->setColorArray(colorArray, osg::Array::BIND_OVERALL);
	geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	geometry->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, false);
	geometry->getOrCreateStateSet()->setAttributeAndModes(new osg::LineWidth(4.0));
	geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertexArray->size()));
	geode->addDrawable(geometry);
	return geode;
}

在帧循环中更新绳子的各项参数:

		case (osgGA::GUIEventAdapter::FRAME):
			{
				double dt = 0.0;
				_currentTick = osg::Timer::instance()->tick();
				if (_currentTick != _lastTick)
				{		
					dt = osg::Timer::instance()->delta_s(_lastTick, _currentTick);
					_lastTick = _currentTick;
				}

				ropeSimulation->setRopeConnectionVel(ropeConnectionVel);		

				float maxPossible_dt = 0.002f;										

				int numOfIterations = (int)(dt / maxPossible_dt) + 1;			
				if (numOfIterations != 0)
					dt = dt / numOfIterations;	

				for (int a = 0; a < numOfIterations; ++a)
					ropeSimulation->operate(dt);
			}

将各部分添加到场景根节点,编译运行程序:

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

#include "Physics2.h"


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

RopeSimulation* ropeSimulation = new RopeSimulation(
	80,						// 80 Particles (Masses)
	0.05f,					// Each Particle Has A Weight Of 50 Grams
	10000.0f,				// springConstant In The Rope
	0.05f,					// Normal Length Of Springs In The Rope
	0.2f,					// Spring Inner Friction Constant
	Vector3D(0, -9.81f, 0), // Gravitational Acceleration
	0.02f,					// Air Friction Constant
	100.0f,					// Ground Repel Constant
	0.2f,					// Ground Slide Friction Constant
	2.0f,					// Ground Absoption Constant
	-1.5f);					// Height Of Ground



bool initialize ()
{
	ropeSimulation->getMass(ropeSimulation->numOfMasses - 1)->vel.z = 10.0f;
	return true;
}


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


class GroundUpdateCallback : public osg::Drawable::UpdateCallback
{
public:

	virtual void update(osg::NodeVisitor*, osg::Drawable* d)
	{
		osg::Geometry *geometry = dynamic_cast<osg::Geometry*>(d);
		if (!geometry)
			return;

		osg::Vec3Array *vertexArray = dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray());
		if (!vertexArray)
			return;

		vertexArray->clear();
		
		vertexArray->push_back(osg::Vec3(20, ropeSimulation->groundHeight, 20));
		vertexArray->push_back(osg::Vec3(-20, ropeSimulation->groundHeight, 20));
		vertexArray->push_back(osg::Vec3(-20, ropeSimulation->groundHeight, -20));
		vertexArray->push_back(osg::Vec3(20, ropeSimulation->groundHeight, -20));
	
		geometry->setVertexArray(vertexArray);
		vertexArray->dirty();
	}

};



class RopeShadowUpdateCallback : public osg::Drawable::UpdateCallback
{
public:

	virtual void update(osg::NodeVisitor*, osg::Drawable* d)
	{
		osg::Geometry *geometry = dynamic_cast<osg::Geometry*>(d);
		if (!geometry)
			return;

		osg::Vec3Array *vertexArray = dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray());
		if (!vertexArray)
			return;

		vertexArray->clear();

		for (int a = 0; a < ropeSimulation->numOfMasses - 1; ++a)
		{
			Mass* mass1 = ropeSimulation->getMass(a);
			Vector3D* pos1 = &mass1->pos;

			Mass* mass2 = ropeSimulation->getMass(a + 1);
			Vector3D* pos2 = &mass2->pos;
			vertexArray->push_back(osg::Vec3(pos1->x, ropeSimulation->groundHeight, pos1->z));		// Draw Shadow At groundHeight
			vertexArray->push_back(osg::Vec3(pos2->x, ropeSimulation->groundHeight, pos2->z));		// Draw Shadow At groundHeight
		}

		geometry->setVertexArray(vertexArray);
		vertexArray->dirty();
	}

};


class RopeUpdateCallback : public osg::Drawable::UpdateCallback
{
public:

	virtual void update(osg::NodeVisitor*, osg::Drawable* d)
	{
		osg::Geometry *geometry = dynamic_cast<osg::Geometry*>(d);
		if (!geometry)
			return;

		osg::Vec3Array *vertexArray = dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray());
		if (!vertexArray)
			return;

		vertexArray->clear();

		for (int a = 0; a < ropeSimulation->numOfMasses - 1; ++a)
		{
			Mass* mass1 = ropeSimulation->getMass(a);
			Vector3D* pos1 = &mass1->pos;

			Mass* mass2 = ropeSimulation->getMass(a + 1);
			Vector3D* pos2 = &mass2->pos;

			vertexArray->push_back(osg::Vec3(pos1->x, pos1->y, pos1->z));	
			vertexArray->push_back(osg::Vec3(pos2->x, pos2->y, pos2->z));
		}

		geometry->setVertexArray(vertexArray);
		vertexArray->dirty();
	}

};





osg::Geode*	createGround()
{
	osg::Geode *geode = new osg::Geode;
	osg::Geometry *geometry = new osg::Geometry;
	geometry->setUpdateCallback(new GroundUpdateCallback);
	osg::Vec3Array *vertexArray = new osg::Vec3Array;
	osg::Vec3Array *colorArray = new osg::Vec3Array;
	
	colorArray->push_back(osg::Vec3(0, 0, 1.0));
	vertexArray->push_back(osg::Vec3(20, ropeSimulation->groundHeight, 20));
	colorArray->push_back(osg::Vec3(0, 0, 1.0));
	vertexArray->push_back(osg::Vec3(-20, ropeSimulation->groundHeight, 20));
	colorArray->push_back(osg::Vec3(0,0,0));
	vertexArray->push_back(osg::Vec3(-20, ropeSimulation->groundHeight, -20));
	colorArray->push_back(osg::Vec3(0,0,0));
	vertexArray->push_back(osg::Vec3(20, ropeSimulation->groundHeight, -20));

	geometry->setVertexArray(vertexArray);
	geometry->setColorArray(colorArray, osg::Array::BIND_PER_VERTEX);
	geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, vertexArray->size()));
	geode->addDrawable(geometry);
	return geode;
}


osg::Geode*	createRopeShadow()
{
	osg::Geode *geode = new osg::Geode;
	osg::Geometry *geometry = new osg::Geometry;
	geometry->setUpdateCallback(new RopeShadowUpdateCallback);
	osg::Vec3Array *vertexArray = new osg::Vec3Array;
	osg::Vec3Array *colorArray = new osg::Vec3Array;

	colorArray->push_back(osg::Vec3(0, 0, 0));
	
	for (int a = 0; a < ropeSimulation->numOfMasses - 1; ++a)
	{
		Mass* mass1 = ropeSimulation->getMass(a);
		Vector3D* pos1 = &mass1->pos;

		Mass* mass2 = ropeSimulation->getMass(a + 1);
		Vector3D* pos2 = &mass2->pos;
		vertexArray->push_back(osg::Vec3(pos1->x, ropeSimulation->groundHeight, pos1->z));		// Draw Shadow At groundHeight
		vertexArray->push_back(osg::Vec3(pos2->x, ropeSimulation->groundHeight, pos2->z));		// Draw Shadow At groundHeight
	}
	
	geometry->setVertexArray(vertexArray);
	geometry->setColorArray(colorArray, osg::Array::BIND_OVERALL);
	geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	geometry->getOrCreateStateSet()->setAttributeAndModes(new osg::LineWidth(2.0));
	geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertexArray->size()));
	geode->addDrawable(geometry);
	return geode;
}


osg::Geode*	createRope()
{
	osg::Geode *geode = new osg::Geode;
	osg::Geometry *geometry = new osg::Geometry;
	geometry->setUpdateCallback(new RopeUpdateCallback);
	osg::Vec3Array *vertexArray = new osg::Vec3Array;
	osg::Vec3Array *colorArray = new osg::Vec3Array;

	colorArray->push_back(osg::Vec3(1, 1, 0));

	for (int a = 0; a < ropeSimulation->numOfMasses - 1; ++a)
	{
		Mass* mass1 = ropeSimulation->getMass(a);
		Vector3D* pos1 = &mass1->pos;

		Mass* mass2 = ropeSimulation->getMass(a + 1);
		Vector3D* pos2 = &mass2->pos;

		vertexArray->push_back(osg::Vec3(pos1->x, pos1->y, pos1->z));	
		vertexArray->push_back(osg::Vec3(pos2->x, pos2->y, pos2->z));
	}

	geometry->setVertexArray(vertexArray);
	geometry->setColorArray(colorArray, osg::Array::BIND_OVERALL);
	geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	geometry->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, false);
	geometry->getOrCreateStateSet()->setAttributeAndModes(new osg::LineWidth(4.0));
	geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertexArray->size()));
	geode->addDrawable(geometry);
	return geode;
}



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

class ManipulatorSceneHandler : public osgGA::GUIEventHandler
{
public:
	ManipulatorSceneHandler()
	{
		_lastTick  =  osg::Timer::instance()->tick();
		_currentTick = _lastTick;
	}

public:
	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;

		osg::Group *root = viewer->getSceneData()->asGroup();

		switch(ea.getEventType())
		{
		case (osgGA::GUIEventAdapter::FRAME):
			{
				double dt = 0.0;
				_currentTick = osg::Timer::instance()->tick();
				if (_currentTick != _lastTick)
				{		
					dt = osg::Timer::instance()->delta_s(_lastTick, _currentTick);
					_lastTick = _currentTick;
				}

				ropeSimulation->setRopeConnectionVel(ropeConnectionVel);		

				float maxPossible_dt = 0.002f;										

				int numOfIterations = (int)(dt / maxPossible_dt) + 1;			
				if (numOfIterations != 0)
					dt = dt / numOfIterations;	

				for (int a = 0; a < numOfIterations; ++a)
					ropeSimulation->operate(dt);
			}
			break;
		case(osgGA::GUIEventAdapter::KEYDOWN):
			{
				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Up)
				{
						ropeConnectionVel.z -= 1.0f;	
				}

				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Down)
				{
					ropeConnectionVel.z += 1.0f;
				}
				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Left)
				{
					ropeConnectionVel.x -= 1.0f;
				}

				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Right)
				{
						ropeConnectionVel.x += 1.0f;
				}
				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Home)
				{
					ropeConnectionVel.y += 1.0f;	
				}

				if (ea.getKey() == osgGA::GUIEventAdapter::KEY_End)
				{
					ropeConnectionVel.y -= 1.0f;
				}
			}
			break;

		default: break;
		}
		return false;
	}

	osg::Timer_t _lastTick;
	osg::Timer_t _currentTick;
	Vector3D ropeConnectionVel;
};







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.0, 0.0, 0.0, 0.5) );
		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, 0, 4), osg::Vec3d(0, 0, 0), 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()
{
	initialize();

	osg::Group *root = new osg::Group;

	root->addChild(createGround());
	root->addChild(createRopeShadow());
	root->addChild(createRope());

	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)