opengles实现雾化效果

来源:互联网 发布:k是什么意思网络用语 编辑:程序博客网 时间:2024/06/11 15:58


shader实现类

const char* vs ={"attribute vec3 inVertex;""attribute vec3 inNormal;""attribute vec2 inTexCoord;""uniform mat4 MVPMatrix;""uniform mat4 ModelViewMatrix;""uniform vec3 LightDirection;""uniform float FogDensity;"//雾浓度"uniform float FogEnd;"//雾结束的位置"varying vec2 TexCoord;""varying vec3 DiffuseLight;""varying vec3 FogIntensity;"//随距离变换的雾的强度"void main()""{"//这里需要将顶点转化到摄像机空间,目的是用来计算摄像机与顶点之间的距离"vec3 viewPos=vec3(ModelViewMatrix*vec4(inVertex,1));""float eyeDist=length(viewPos);" //length(x): 向量长度"gl_Position=MVPMatrix*vec4(inVertex,1);""TexCoord=inTexCoord;""float DiffuseIntensity=dot(inNormal,normalize(LightDirection));"//求两向量的点积"DiffuseLight=vec3(max(DiffuseIntensity,0.0)*0.5+0.5);""float fogIntensity=1.0;""fogIntensity=(FogEnd-eyeDist)*FogDensity;"//clamp(x, min, max)  把输入值限制在[min, max]范围内"fogIntensity=clamp(fogIntensity,0.0,1.0);""FogIntensity=vec3(fogIntensity,fogIntensity,fogIntensity);""}"};const char* ps ={"precision lowp float;""uniform sampler2D sTexture;""uniform vec3 FogColor;""varying vec2 TexCoord;""varying vec3 DiffuseLight;""varying vec3 FogIntensity;""void main()""{""vec3 texColor=texture2D(sTexture,TexCoord).rgb;""vec3 color=texColor*DiffuseLight;"//mix(x, y, a): x, y的线性混叠, x(1-a) + y*a;"color=mix(FogColor,color,FogIntensity);""gl_FragColor=vec4(color,1.0);""}"};

渲染函数

       virtual void    onRender(Program_Fog& shader,CELL3RDCamera& camera)        {static float angle = 0;matrix4 matRot(1);matRot.rotateY(angle);matrix4 matTrans;matTrans.translate(0,5,0);matrix4 matScale(1);matScale.scale(0.3f,0.3f,0.3f);//总的模型变换矩阵matrix4 matModel = matTrans*matRot*matScale;angle += 1.0f;matrix4 MVP = camera._matProj*camera._matView*matModel;matrix4 mv = camera._matView*matModel;matrix4 mvI = mv.inverse();float4 vEyePosModel;vEyePosModel = mvI*float4(0,0,0,1);const float fFogStart = 0.0f;//雾开始的地方const float fFogEnd = 200;//雾结束的地方const float fFogDensity = 0.0017f;//雾浓度const float afFogColor[3] = { 0.6f, 0.8f, 1.0f };//雾的颜色_device.setUniform1f(shader.FogEnd,fFogEnd);_device.setUniform1f(shader.FogDensity,fFogDensity);_device.setUniform3fv(shader.FogColor,1,afFogColor);//设置观察点坐标_device.setUniform3fv(shader.EyePositon,1,(float*)&camera._eye);_device.setUniformMatrix4fv(shader.MVPMatrix,1,false,MVP.data());_device.setUniformMatrix4fv(shader.ModelViewMatrix,1,false,mv.data());VertexBumpMap* vert = &_arVertexs.front();_device.attributePointer(shader.inVertex,3,GL_FLOAT,GL_FALSE,sizeof(VertexBumpMap),vert);_device.attributePointer(shader.inNormal, 3, GL_FLOAT, GL_FALSE, sizeof(VertexBumpMap), &vert[0]._normal);_device.attributePointer(shader.inTexCoord, 2, GL_FLOAT, GL_FALSE, sizeof(VertexBumpMap), &vert[0]._uv);_device.drawElements(GL_TRIANGLES,_arFaces.size()*3,GL_UNSIGNED_SHORT,&_arFaces.front());        }


原创粉丝点击