osg shader 例子
时间: 2023-06-15 22:04:07 浏览: 196
以下是一个简单的osg shader的例子,它使用了相对复杂的光照和纹理映射,用于渲染一个纹理贴图的模型:
```cpp
osg::ref_ptr<osg::Shader> vertexShader = new osg::Shader(osg::Shader::VERTEX, R"(
#version 330
in vec3 vertex;
in vec3 normal;
in vec2 texCoord;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform mat4 normalMatrix;
out vec3 normalInterp;
out vec2 texCoordInterp;
out vec3 fragPos;
void main()
{
normalInterp = vec3(normalMatrix * vec4(normal, 0.0));
texCoordInterp = texCoord;
fragPos = vec3(modelViewMatrix * vec4(vertex, 1.0));
gl_Position = projectionMatrix * modelViewMatrix * vec4(vertex, 1.0);
}
)");
osg::ref_ptr<osg::Shader> fragmentShader = new osg::Shader(osg::Shader::FRAGMENT, R"(
#version 330
in vec3 normalInterp;
in vec2 texCoordInterp;
in vec3 fragPos;
uniform sampler2D tex;
uniform vec3 lightPos;
uniform vec3 lightColor;
uniform vec3 objectColor;
uniform float shininess;
out vec4 fragColor;
void main()
{
vec3 ambient = 0.1 * objectColor;
vec3 norm = normalize(normalInterp);
vec3 lightDir = normalize(lightPos - fragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * lightColor;
vec3 viewDir = normalize(-fragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), shininess);
vec3 specular = spec * lightColor;
vec4 texColor = texture(tex, texCoordInterp);
fragColor = vec4((ambient + diffuse + specular) * texColor.rgb, texColor.a);
}
)");
osg::ref_ptr<osg::Program> program = new osg::Program;
program->addShader(vertexShader.get());
program->addShader(fragmentShader.get());
osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet;
stateSet->setAttributeAndModes(program.get(), osg::StateAttribute::ON);
osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
texture->setImage(osgDB::readImageFile("texture.png"));
stateSet->setTextureAttributeAndModes(0, texture.get(), osg::StateAttribute::ON);
osg::ref_ptr<osg::Node> model = osgDB::readNodeFile("model.obj");
model->setStateSet(stateSet.get());
osgViewer::Viewer viewer;
viewer.setSceneData(model.get());
viewer.run();
```
这段代码使用了OpenGL的着色器语言(GLSL)来定义顶点着色器和片段着色器,并创建了一个OpenGL程序(Program)对象,将两个着色器链接在一起。然后创建了一个状态集(StateSet)对象,并将程序和纹理对象(texture)绑定到状态集中。最后将状态集设置到模型上,用于渲染整个场景。
阅读全文