varying vec2 vUv; uniform float opacity; uniform vec3 baseColor; uniform vec3 backColor; uniform float occlusionDistance; uniform float clipDistance; uniform float maxClipFactor; #if defined use_map uniform sampler2D map; #endif #if defined(GL_EXT_frag_depth) && defined(useDepth) //似乎通过gl.getExtension('EXT_frag_depth')得到的GL_EXT_frag_depth uniform sampler2D depthTexture; uniform float nearPlane; uniform float farPlane; uniform vec2 resolution; uniform vec2 viewportOffset; // viewportOffset 范围从0-整个画布的像素 float convertToLinear(float zValue) { float z = zValue * 2.0 - 1.0; return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane)); } #endif void main() { vec4 color = vec4(baseColor, opacity); #if defined(GL_EXT_frag_depth) && defined(useDepth) // mixFactor and clipFactor define the color mixing proportion between the states of // full visibility and occluded visibility // and // full visibility and total invisibility float mixFactor = 0.0; float clipFactor = 0.0; // The linear depth value of the current fragment float fragDepth = convertToLinear(gl_FragCoord.z); // The coordinates of the current fragment in the depth texture vec2 depthTxtCoords = vec2(gl_FragCoord.x-viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution; //gl_FragCoord大小为 viewport client大小 // The linear depth value of the pixel occupied by this fragment in the depth buffer float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r); // The difference between the two depths float delta = fragDepth - textureDepth; if (delta > 0.0)//差距 { // occlusionDistance and clipDistance define the width of the respective zones and // mixFactor and clipFactor express the interpolation between the two colors depending on the position // of the current fragment withing those zones. mixFactor = clamp(delta / occlusionDistance, 0.0, 1.0); clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor); } // If the fragment is totally transparent, don't bother drawing it if (clipFactor == 1.0) { discard; }else{ #if defined use_map color = texture2D(map, vUv) * color; #endif color = vec4(mix(color.rgb, backColor, mixFactor), color.a * (1.0 - clipFactor)); } #else #if defined use_map color = texture2D(map, vUv) * color; #endif #endif gl_FragColor = color; }