# WebGL学习之法线贴图

## 法线贴图

// 将法线向量转换为范围[-1,1]
vec3 normal = normalize(normal * 2.0 - 1.0);


## 着色器

dFdx(p) //在x方向的偏导数
dFdy(p) //在y方向的偏导数
cross(p0,p1) //向量p0,p1的叉乘


#extension GL_OES_standard_derivatives : enable// 注意要开启该扩展
//...
uniform sampler2D u_diffMap;
uniform sampler2D u_specMap;
uniform sampler2D u_normMap;
//...
vec2 dHdxy_fwd() {
vec2 dSTdx = dFdx( v_texcoord );
vec2 dSTdy = dFdy( v_texcoord );
float Hll = bumpScale * texture2D( u_normMap, v_texcoord ).x;
float dBx = bumpScale * texture2D( u_normMap, v_texcoord + dSTdx ).x - Hll;
float dBy = bumpScale * texture2D( u_normMap, v_texcoord + dSTdy ).x - Hll;
return vec2( dBx, dBy );
}
vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {
vec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );
vec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );
vec3 vN = surf_norm;
vec3 R1 = cross( vSigmaY, vN );
vec3 R2 = cross( vN, vSigmaX );
float fDet = dot( vSigmaX, R1 );
fDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );
vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
return normalize( abs( fDet ) * surf_norm - vGrad );
}

//...
// 从法线贴图计算出逐像素法线向量
vec3 normal = perturbNormalArb( -v_position, normal, dHdxy_fwd());
//...
// 总的光照
gl_FragColor = vec4(ambient + diffuse + specular, diffuseColor.a);


## 后记

posted @ 2019-05-01 13:10  Jeff.Zhong  阅读(984)  评论(0编辑  收藏