OSG + GLSL 實現搖擺的樹

#include <iostream>
#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>
#include <osg/Geometry>
#include <osgGA/TrackballManipulator>

#include <osg/Texture2D>
#include <osg/Geode>
#include <osg/LightSource>
#include <osg/TexGenNode>
#include <osg/TexMat>
#include <osgDB/WriteFile>
#include <osgUtil/Optimizer>

#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>

#include <osgViewer/Viewer>
#include <osgViewer/CompositeViewer>
#include <string>
#include <osg/Program>
#include <osg/Uniform>
using namespace std;

static const char* vertSource = {
	"varying vec2 Texcoord;\n"
	"uniform float uTime;\n"
	"void main( void )\n"
	"{\n"
		"vec4 ver= gl_Vertex;\n"
		"if(ver.z>2.0)\n"
		"{\n"
			//"uTime +=  (gl_ModelViewMatrix * ver-vec4(0,0,2,0)).x/100.0;\n"
			"ver.xy += vec2(sin(uTime), cos(uTime))*ver.y/20.0;\n"
		"}\n"
		"gl_Position = gl_ModelViewProjectionMatrix * ver;\n"
		"Texcoord    = gl_MultiTexCoord0.xy;\n"
	"}\n"
};

static const char* fragSource = {
	"uniform sampler2D baseMap;\n"
	"varying vec2 Texcoord;\n"
	"void main( void )\n"
	"{\n"
		"gl_FragColor = texture2D( baseMap, Texcoord );\n"
	"}\n"
};
class ColorCallback : public osg::Uniform::Callback
{
public:
	ColorCallback() : _incRed(false),time(1.05) {}

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

		//osg::Vec4 color;
		//uniform->get( color );

	/*	if ( _incRed==true )
		{
			if ( color.x()<1.0 ) color.x() += 0.01;
			else _incRed = false;
		}
		else
		{
			if ( color.x()>0.0 ) color.x() -= 0.01;
			else _incRed = true;
		}*/

		time+=0.1;
		uniform->set( time );
	}

protected:
	bool _incRed;
	float time;
};

void createShaders( osg::StateSet& ss )
{
	osg::ref_ptr<osg::Shader> vertShader = new osg::Shader( osg::Shader::VERTEX, vertSource );
	osg::ref_ptr<osg::Shader> fragShader = new osg::Shader( osg::Shader::FRAGMENT, fragSource);

	osg::ref_ptr<osg::Program> program = new osg::Program;
	program->addShader( vertShader.get() );
	program->addShader( fragShader.get() );

	osg::ref_ptr<osg::Uniform> utime = new osg::Uniform( "uTime", 1.05f );
	utime->setUpdateCallback( new ColorCallback );

   osg::ref_ptr<osg::Uniform> tex = new osg::Uniform( "baseMap", 0);

	ss.addUniform( utime.get() );
	ss.addUniform(tex.get());
	ss.setAttributeAndModes( program.get() );
}
int main(int argc, char ** argv) 
{
	osgViewer::Viewer viewer;
	viewer.setUpViewInWindow(200,50,800,600);

	osg::Group* root = new osg::Group;
	osg::Node* node = osgDB::readNodeFile("c:/palm.ive");
	
createShaders(*(node->getOrCreateStateSet()));

	 root->addChild(node);

	 
	
	viewer.setSceneData(root);
	viewer.run();

	//if(osgDB::writeNodeFile(*node,"c:/glsl.osg"))
	//	std::cout<<"成功"<<std::endl;
	//else
	//	std::cout<<"失敗"<<std::endl;
	return 0;

}


可惜圖片 是 靜態的 看不出 效果嘍   哈哈

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章