3,882
社区成员




//这是OSG画矩形并贴上纹理图片的函数
osg::ref_ptr<osg::Node> setTex(const std::string& filename)
{
osg::Group* group = new osg::Group;
osg::Geometry* geom = new osg::Geometry;
osg::Vec3Array* vertices = new osg::Vec3Array(4);
vertices->push_back(osg::Vec3(0,0,0));
vertices->push_back(osg::Vec3(0,0,1));
vertices->push_back(osg::Vec3(1,0,1));
vertices->push_back(osg::Vec3(1,0,0));
geom->setVertexArray(vertices);
osg::Vec2Array* texcoords = new osg::Vec2Array(4);
texcoords->push_back(osg::Vec2(0.0f,0.0f));
texcoords->push_back(osg::Vec2(1.0f,0.0f));
texcoords->push_back(osg::Vec2(1.0f,1.0f));
texcoords->push_back(osg::Vec2(0.0f,1.0f));
//(*texcoords)[0].set(0.0f,0.0f);
//(*texcoords)[1].set(1.0f,0.0f);
//(*texcoords)[2].set(1.0f,1.0f);
//(*texcoords)[3].set(0.0f,1.0f);
geom->setTexCoordArray(0,texcoords);
//osg::Vec3Array* normals = new osg::Vec3Array(1);
//(*normals)[0].set(-1.0f,0.0f,0.0f);
//geom->setNormalArray(normals);
//geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
//osg::Vec4Array* colors = new osg::Vec4Array(1);
//(*colors)[0].set(1.0f,1.0f,1.0f,1.0f);
//geom->setColorArray(colors);
//geom->setColorBinding(osg::Geometry::BIND_OVERALL);
geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,4));
// set up the texture state.
osg::Texture2D* texture = new osg::Texture2D;
texture->setDataVariance(osg::Object::DYNAMIC); // protect from being optimized away as static state.
//texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
//texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
//texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,0.5f)); // only used when wrap is set to CLAMP_TO_BORDER
texture->setImage(osgDB::readImageFile(filename));
osg::StateSet* stateset = geom->getOrCreateStateSet();
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
osg::Geode* geode = new osg::Geode;
geode->addDrawable(geom);
group->addChild(geode);
return group;
}
//mian()
int main(int argc, char* argv[])
{
osgViewer::Viewer viewer;
osg::Group * root = new osg::Group();
root->addChild(setTex("forestRoof.png").get());
viewer.setSceneData(root);
viewer.run();
return 0;
}
osg::Vec3Array* vertices = new osg::Vec3Array(4);//这里已经初始化了4个顶点
//后边再push_back四个顶,结果有8个顶点了
//应该是:osg::Vec3Array* vertices = new osg::Vec3Array;
vertices->push_back(osg::Vec3(0,0,0));
vertices->push_back(osg::Vec3(0,0,1));
vertices->push_back(osg::Vec3(1,0,1));
vertices->push_back(osg::Vec3(1,0,0));
geom->setVertexArray(vertices);
osg::Vec2Array* texcoords = new osg::Vec2Array(4);//这里也同上。
texcoords->push_back(osg::Vec2(0.0f,0.0f));
texcoords->push_back(osg::Vec2(1.0f,0.0f));
texcoords->push_back(osg::Vec2(1.0f,1.0f));
texcoords->push_back(osg::Vec2(0.0f,1.0f));