osg使用Shader实现动态效果的线 代码实现
时间: 2023-05-26 08:01:24 浏览: 303
osg画实时曲线的代码,vc开发
4星 · 用户满意度95%
A:
osg::ref_ptr<osg::Geometry> createLineGeomWithDynamicColor(float thickness, osg::Vec3Array* vertices)
{
osg::ref_ptr<osg::Geometry> lineGeom = new osg::Geometry;
// Set the vertices of the geometry
lineGeom->setVertexArray(vertices);
// Create a series of line segments using PrimitiveSet::LINE_STRIP
osg::ref_ptr<osg::DrawElementsUInt> lineIndices = new osg::DrawElementsUInt(osg::PrimitiveSet::LINE_STRIP, 0);
for(unsigned int i = 0; i < vertices->size(); i++) lineIndices->push_back(i);
lineGeom->addPrimitiveSet(lineIndices);
// Create a dynamic color array to allow for color changes
osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(vertices->size(), osg::Vec4(1.0f, 0.0f, 0.0f, 1.0f));
colors->setBinding(osg::Array::BIND_PER_VERTEX);
lineGeom->setColorArray(colors);
lineGeom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
// Create a shader that allows for dynamic color changes
const char* vertexShaderSource =
"attribute vec4 osg_Color;\n"
"varying vec4 vColor;\n"
"void main()\n"
"{\n"
" gl_Position = ftransform();\n"
" vColor = osg_Color;\n"
"}\n";
const char* fragmentShaderSource =
"varying vec4 vColor;\n"
"void main()\n"
"{\n"
" gl_FragColor = vColor;\n"
"}\n";
osg::ref_ptr<osg::Program> program = new osg::Program;
program->addShader(new osg::Shader(osg::Shader::VERTEX, vertexShaderSource));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource));
lineGeom->getOrCreateStateSet()->setAttribute(program);
// Make sure the geometry is rendered correctly
osg::ref_ptr<osg::LineWidth> lineWidth = new osg::LineWidth;
lineWidth->setWidth(thickness);
lineGeom->getOrCreateStateSet()->setAttributeAndModes(lineWidth);
lineGeom->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
lineGeom->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
return lineGeom;
}
阅读全文