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添加到节点之中。

首先创建网状的场景

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. osg::Geode* createFlagGeode()  
  2. {  
  3.     osg::Geode* geode = new osg::Geode;  
  4.     osg::Geometry *geometry = new osg::Geometry;  
  5.     osg::Vec3Array *vertexArray = new osg::Vec3Array;  
  6.     for (int x = 0; x < SIZE - 1; x++)  
  7.     {  
  8.         for (int z = 0; z < SIZE - 1; z++)  
  9.         {  
  10.             vertexArray->push_back(osg::Vec3(mesh[x][z][0], mesh[x][z][1], mesh[x][z][2]));  
  11.             vertexArray->push_back(osg::Vec3(mesh[x+1][z][0], mesh[x+1][z][1], mesh[x+1][z][2]));  
  12.             wave_movement += 0.00001f;  
  13.             if (wave_movement > TWO_PI)  
  14.                 wave_movement = 0.0f;  
  15.         }  
  16.     }  
  17.     geometry->setVertexArray(vertexArray);  
  18.     osg::PolygonMode *pm = new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE);  
  19.     geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_STRIP, 0, vertexArray->size()));  
  20.     geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);  
  21.     geometry->getOrCreateStateSet()->setAttributeAndModes(pm);  
  22.   
  23.     osg::Uniform *uniform = new osg::Uniform("animStep", wave_movement);  
  24.     uniform->setUpdateCallback(new MoveUpdateCallback);  
  25.     geometry->getStateSet()->addUniform(uniform);  
  26.       
  27.     osg::Shader *vertexShader = new osg::Shader(osg::Shader::VERTEX, vShader);  
  28.     osg::Shader *fragmentShader = new osg::Shader(osg::Shader::FRAGMENT, fShader);  
  29.     osg::Program *program = new osg::Program();  
  30.     program->addShader(vertexShader);  
  31.     program->addShader(fragmentShader);  
  32.     geometry->getOrCreateStateSet()->setAttributeAndModes(program);  
  33.       
  34.     geode->addDrawable(geometry);  
  35.   
  36.     return geode;  
  37. }  

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

VertexShader:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. static const char*      vShader = {  
  2.     "#version 330\n"  
  3.     "in vec4 inVertex;\n"  
  4.     "uniform float animStep;\n"  
  5.     "void main(){\n"  
  6.     "vec4 tmp = inVertex;\n"  
  7.     "tmp.y = ( sin(animStep + (tmp.x / 5.0) ) + sin(animStep + (tmp.z / 4.0) ) ) * 2.5;\n"  
  8.     "gl_Position = gl_ModelViewProjectionMatrix * tmp;\n"  
  9.     "}\n"  
  10. };  

FragmentShader:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. static const char*      fShader = {  
  2.     "#version 330\n"  
  3.     "out vec4 fragColor;\n"  
  4.     "void main(){\n"  
  5.     "fragColor = vec4(0.5, 1.0, 0.5, 1.0);\n"  
  6.     "}\n"  
  7. };  

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

可以在Uniform的回调中完成:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class MoveUpdateCallback : public osg::Uniform::Callback  
  2. {  
  3.     virtual void operator()(osg::Uniform *uniform, osg::NodeVisitor *nv)  
  4.     {  
  5.         if(!uniform)  
  6.             return;  
  7.   
  8.         float animStep;  
  9.         uniform->get(animStep);  
  10.   
  11.         //按照NeHe课程中方式每帧改变64*64*0.00001  
  12.         for (int x = 0; x < SIZE - 1; x++)  
  13.         {  
  14.             for (int z = 0; z < SIZE - 1; z++)  
  15.             {  
  16.                 wave_movement += 0.00001f;  
  17.                 if (wave_movement > TWO_PI)  
  18.                     wave_movement = 0.0f;  
  19.             }  
  20.         }         
  21.         animStep = wave_movement;  
  22.         uniform->set(animStep);  
  23.     }  
  24. };  

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


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

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include "../osgNeHe.h"  
  2.   
  3. #include <QtCore/QTimer>  
  4. #include <QtGui/QApplication>  
  5. #include <QtGui/QVBoxLayout>  
  6.   
  7. #include <osgViewer/Viewer>  
  8. #include <osgDB/ReadFile>  
  9. #include <osgQt/GraphicsWindowQt>  
  10.   
  11. #include <osg/MatrixTransform>  
  12. #include <osg/PolygonMode>  
  13.   
  14. #include <osg/Shader>  
  15. #include <osg/Uniform>  
  16. #include <osg/Program>  
  17.   
  18. //  
  19. #define     TWO_PI 6.2831853071                                   
  20. #define     SIZE    64  
  21. GLfloat     mesh[SIZE][SIZE][3];      
  22. GLfloat     wave_movement = 0.0f;  
  23. //  
  24.   
  25.   
  26. static const char*      vShader = {  
  27.     "#version 330\n"  
  28.     "in vec4 inVertex;\n"  
  29.     "uniform float animStep;\n"  
  30.     "void main(){\n"  
  31.     "vec4 tmp = inVertex;\n"  
  32.     "tmp.y = ( sin(animStep + (tmp.x / 5.0) ) + sin(animStep + (tmp.z / 4.0) ) ) * 2.5;\n"  
  33.     "gl_Position = gl_ModelViewProjectionMatrix * tmp;\n"  
  34.     "}\n"  
  35. };  
  36.   
  37. static const char*      fShader = {  
  38.     "#version 330\n"  
  39.     "out vec4 fragColor;\n"  
  40.     "void main(){\n"  
  41.     "fragColor = vec4(0.5, 1.0, 0.5, 1.0);\n"  
  42.     "}\n"  
  43. };  
  44.   
  45.   
  46. class MoveUpdateCallback : public osg::Uniform::Callback  
  47. {  
  48.     virtual void operator()(osg::Uniform *uniform, osg::NodeVisitor *nv)  
  49.     {  
  50.         if(!uniform)  
  51.             return;  
  52.   
  53.         float animStep;  
  54.         uniform->get(animStep);  
  55.   
  56.         //按照NeHe课程中方式每帧改变64*64*0.00001  
  57.         for (int x = 0; x < SIZE - 1; x++)  
  58.         {  
  59.             for (int z = 0; z < SIZE - 1; z++)  
  60.             {  
  61.                 wave_movement += 0.00001f;  
  62.                 if (wave_movement > TWO_PI)  
  63.                     wave_movement = 0.0f;  
  64.             }  
  65.         }         
  66.         animStep = wave_movement;  
  67.         uniform->set(animStep);  
  68.     }  
  69. };  
  70.   
  71.   
  72.   
  73. void initialize()  
  74. {  
  75.     for (int x = 0; x < SIZE; x++)  
  76.     {  
  77.         for (int z = 0; z < SIZE; z++)  
  78.         {  
  79.             mesh[x][z][0] = (float) (SIZE / 2) - x;  
  80.             mesh[x][z][1] = 0.0f;  
  81.             mesh[x][z][2] = (float) (SIZE / 2) - z;  
  82.         }  
  83.     }  
  84. }  
  85.   
  86.   
  87. osg::Geode* createFlagGeode()  
  88. {  
  89.     osg::Geode* geode = new osg::Geode;  
  90.     osg::Geometry *geometry = new osg::Geometry;  
  91.     osg::Vec3Array *vertexArray = new osg::Vec3Array;  
  92.     for (int x = 0; x < SIZE - 1; x++)  
  93.     {  
  94.         for (int z = 0; z < SIZE - 1; z++)  
  95.         {  
  96.             vertexArray->push_back(osg::Vec3(mesh[x][z][0], mesh[x][z][1], mesh[x][z][2]));  
  97.             vertexArray->push_back(osg::Vec3(mesh[x+1][z][0], mesh[x+1][z][1], mesh[x+1][z][2]));  
  98.             wave_movement += 0.00001f;  
  99.             if (wave_movement > TWO_PI)  
  100.                 wave_movement = 0.0f;  
  101.         }  
  102.     }  
  103.     geometry->setVertexArray(vertexArray);  
  104.     osg::PolygonMode *pm = new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE);  
  105.     geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_STRIP, 0, vertexArray->size()));  
  106.     geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);  
  107.     geometry->getOrCreateStateSet()->setAttributeAndModes(pm);  
  108.   
  109.     osg::Uniform *uniform = new osg::Uniform("animStep", wave_movement);  
  110.     uniform->setUpdateCallback(new MoveUpdateCallback);  
  111.     geometry->getStateSet()->addUniform(uniform);  
  112.       
  113.     osg::Shader *vertexShader = new osg::Shader(osg::Shader::VERTEX, vShader);  
  114.     osg::Shader *fragmentShader = new osg::Shader(osg::Shader::FRAGMENT, fShader);  
  115.     osg::Program *program = new osg::Program();  
  116.     program->addShader(vertexShader);  
  117.     program->addShader(fragmentShader);  
  118.     geometry->getOrCreateStateSet()->setAttributeAndModes(program);  
  119.       
  120.     geode->addDrawable(geometry);  
  121.   
  122.     return geode;  
  123. }  
  124.   
  125.   
  126. class ViewerWidget : public QWidget, public osgViewer::Viewer  
  127. {  
  128. public:  
  129.     ViewerWidget(osg::Node *scene = NULL)  
  130.     {  
  131.         QWidget* renderWidget = getRenderWidget( createGraphicsWindow(0,0,640,480), scene);  
  132.   
  133.         QVBoxLayout* layout = new QVBoxLayout;  
  134.         layout->addWidget(renderWidget);  
  135.         layout->setContentsMargins(0, 0, 0, 1);  
  136.         setLayout( layout );  
  137.   
  138.         connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );  
  139.         _timer.start( 10 );  
  140.     }  
  141.   
  142.     QWidget* getRenderWidget( osgQt::GraphicsWindowQt* gw, osg::Node* scene )  
  143.     {  
  144.         osg::Camera* camera = this->getCamera();  
  145.         camera->setGraphicsContext( gw );  
  146.   
  147.         const osg::GraphicsContext::Traits* traits = gw->getTraits();  
  148.   
  149.         camera->setClearColor( osg::Vec4(0.0, 0.0, 0.0, 1.0) );  
  150.         camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );  
  151.         camera->setProjectionMatrixAsPerspective(45.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 0.1f, 100.0f );          
  152.         camera->setViewMatrixAsLookAt(osg::Vec3d(0.0f, 25.0f, -45.0f), osg::Vec3d(0, 0, 0), osg::Vec3d(0, 1, 0));  
  153.   
  154.         this->setSceneData( scene );  
  155.   
  156.         return gw->getGLWidget();  
  157.     }  
  158.   
  159.     osgQt::GraphicsWindowQt* createGraphicsWindow( int x, int y, int w, int h, const std::string& name=""bool windowDecoration=false )  
  160.     {  
  161.         osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();  
  162.         osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;  
  163.         traits->windowName = name;  
  164.         traits->windowDecoration = windowDecoration;  
  165.         traits->x = x;  
  166.         traits->y = y;  
  167.         traits->width = w;  
  168.         traits->height = h;  
  169.         traits->doubleBuffer = true;  
  170.         traits->alpha = ds->getMinimumNumAlphaBits();  
  171.         traits->stencil = ds->getMinimumNumStencilBits();  
  172.         traits->sampleBuffers = ds->getMultiSamples();  
  173.         traits->samples = ds->getNumMultiSamples();  
  174.   
  175.         return new osgQt::GraphicsWindowQt(traits.get());  
  176.     }  
  177.   
  178.     virtual void paintEvent( QPaintEvent* event )  
  179.     {   
  180.         frame();   
  181.     }  
  182.   
  183. protected:  
  184.   
  185.     QTimer _timer;  
  186. };  
  187.   
  188.   
  189.   
  190. osg::Node*  buildScene()  
  191. {  
  192.     initialize();  
  193.   
  194.     osg::Group *root = new osg::Group;  
  195.     root->addChild(createFlagGeode());  
  196.     return root;  
  197. }  
  198.   
  199.   
  200.   
  201. int main( int argc, char** argv )  
  202. {  
  203.     QApplication app(argc, argv);  
  204.     ViewerWidget* viewWidget = new ViewerWidget(buildScene());  
  205.     viewWidget->setGeometry( 100, 100, 640, 480 );  
  206.     viewWidget->show();  
  207.     return app.exec();  
  208. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值