osg.ShapeDrawable是OpenSceneGraph中的一个Drawable,它可以通过定义一系列基本几何形状来创建一个可渲染的图形对象。
使用osg.ShapeDrawable创建一个简单的正方形。
osg::ref_ptr<osg::Box> box = new osg::Box(osg::Vec3(0,0,0), 1.0f);
osg::ref_ptr<osg::ShapeDrawable> drawable = new osg::ShapeDrawable(box.get());
osg.ShapeDrawable提供了以下几种基本形状:
osg.ShapeDrawable可以通过设置Material属性来定义其外观,包括颜色、反射率和透明度等。下面的代码演示了如何设置一个红色的盒子。
osg::ref_ptr<osg::Material> material = new osg::Material();
material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(1.0,0.0,0.0,1.0));
material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.2,0.2,0.2,1.0));
material->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.8,0.8,0.8,1.0));
material->setShininess(osg::Material::FRONT_AND_BACK, 96.0f);
osg::ref_ptr<osg::Box> box = new osg::Box(osg::Vec3(0,0,0), 1.0f);
osg::ref_ptr<osg::ShapeDrawable> drawable = new osg::ShapeDrawable(box.get());
drawable->setColor(osg::Vec4(1.0,0.0,0.0,1.0));
drawable->getOrCreateStateSet()->setAttributeAndModes(material.get());
osg.ShapeDrawable可以使用纹理将图形贴到几何形状上。下面的代码演示了如何将贴有花纹的图像应用于一个瓶子形状。
osg::ref_ptr<osg::Image> image = osgDB::readImageFile("texture.jpg");
if (image.valid())
{
osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D(image.get());
texture->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
texture->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
osg::ref_ptr<osg::Capsule> capsule = new osg::Capsule();
osg::ref_ptr<osg::ShapeDrawable> drawable = new osg::ShapeDrawable(capsule.get());
drawable->setColor(osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f));
drawable->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture.get());
}