osg多光源的实现

网上查找了关于osg光源的设置,基本上都是一个光源的,后来查找了一些资料,包括osg官方的例子。其实多个光源的实现非常简单,只要多建立一个osg::Light的对象并设置对应参数即可。

以两个光源为例

osg::ref_ptr<osg::Group> createLight(osg::ref_ptr<osg::Node> node)
{
	osg::ref_ptr<osg::Group> lightRoot = new osg::Group();
	lightRoot->addChild(node);

	//开启光照
	osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet();
	stateset = lightRoot->getOrCreateStateSet();
	stateset->setMode(GL_LIGHTING , osg::StateAttribute::ON);
	stateset->setMode(GL_LIGHT0 , osg::StateAttribute::ON);//允许GL_LIGHT0光照
	stateset->setMode(GL_LIGHT1 , osg::StateAttribute::ON);
	


	//计算包围盒
	/*osg::BoundingSphere bs;
	node->computeBound();
	bs = node->getBound();*/
	
	//创建两个个Light对象
	osg::ref_ptr<osg::Light> light = new osg::Light();
	osg::ref_ptr<osg::Light> light1 = new osg::Light();
	//开启光照
	light->setLightNum(0);
	light1->setLightNum(1);//0对应GL_LIGHT0,1对应GL_LIGHT1,默认情况下为GL_LIGHT0
	//设置方向
	//light->setDirection(osg::Vec3(0.0f , 0.0f , -1.0f));
	//设置位置 最后一个参数1是点光源,0是平行光
	light->setPosition(osg::Vec4(0.f , 0.f , 800.f  , 1.0f));
	light1->setPosition(osg::Vec4(100.f, 100.f , 800.f  , 1.0f));

	
	//设置光源颜色
	light->setAmbient(osg::Vec4(0.3f, 0.3f, 0.5f, 1.0f));
	light1->setAmbient(osg::Vec4(0.3f, 0.3f, 0.5f, 1.0f));
	//设置散射光的颜色
	light->setDiffuse(osg::Vec4(0.75f, 0.75f, 0.75f, 1.0f));
	light1->setDiffuse(osg::Vec4(0.75f, 0.75f, 0.75f, 1.0f));
	//镜面反射颜色
	light->setSpecular(osg::Vec4d( 0.8f, 0.8f, 0.8f, 1.0f ));
	light1->setSpecular(osg::Vec4d( 0.8f, 0.8f, 0.8f, 1.0f ));

	


	//设置恒衰减指数
	light->setConstantAttenuation(1.f);
	light1->setConstantAttenuation(1.f);
	//设置线性衰减指数
	light->setLinearAttenuation(0.f);
	light1->setLinearAttenuation(0.f);
	//light->setLinearAttenuation(0.f);
	//设置二次方衰减指数
	light->setQuadraticAttenuation(0.f);
	light1->setQuadraticAttenuation(0.f);
	//stateset->setAttribute(light,osg::StateAttribute::OFF);

	//light->setQuadraticAttenuation(0.f);

	//创建光源 
	osg::ref_ptr<osg::LightSource> lightSource = new osg::LightSource();
	osg::ref_ptr<osg::LightSource> lightSource1 = new osg::LightSource();
	lightSource->setLight(light.get());
	lightSource1->setLight(light1.get());
	lightRoot->addChild(lightSource.get());
	lightRoot->addChild(lightSource1.get());

	return lightRoot.get();

}



猜你喜欢

转载自blog.csdn.net/jaggerjack330/article/details/75977653