GoldenThumbs

Relief Mapping

Sep 19th, 2019
691
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. vec2 reliefParallaxMapping(sampler2D depthMap, float heightScale, vec2 texCoords, vec3 viewDir)
  2. {
  3.    // determine required number of layers
  4.    const float minLayers = 10;
  5.    const float maxLayers = 64;
  6.    float numLayers = mix(maxLayers, minLayers, abs(dot(vec3(0, 0, 1), viewDir)));
  7.  
  8.    // height of each layer
  9.    float layerHeight = 1.0 / numLayers;
  10.    // depth of current layer
  11.    float currentLayerHeight = 0;
  12.    // shift of texture coordinates for each iteration
  13.    vec2 dtex = heightScale * viewDir.xy / viewDir.z / numLayers;
  14.  
  15.    // current texture coordinates
  16.    vec2 currentTextureCoords = texCoords;
  17.  
  18.    // depth from heightmap
  19.    float heightFromTexture = texture(depthMap, currentTextureCoords).a;
  20.  
  21.    // while point is above surface
  22.    while(heightFromTexture > currentLayerHeight)
  23.    {
  24.       // go to the next layer
  25.       currentLayerHeight += layerHeight;
  26.       // shift texture coordinates along viewDir
  27.       currentTextureCoords -= dtex;
  28.       // new depth from heightmap
  29.       heightFromTexture = texture(depthMap, currentTextureCoords).a;
  30.    }
  31.  
  32.    ///////////////////////////////////////////////////////////
  33.    // Start of Relief Parallax Mapping
  34.  
  35.    // decrease shift and height of layer by half
  36.    vec2 deltaTexCoord = dtex / 2;
  37.    float deltaHeight = layerHeight / 2;
  38.  
  39.    // return to the mid point of previous layer
  40.    currentTextureCoords += deltaTexCoord;
  41.    currentLayerHeight -= deltaHeight;
  42.  
  43.    // binary search to increase precision of Steep Parallax Mapping
  44.    const int numSearches = 5;
  45.    for(int i=0; i<numSearches; i++)
  46.    {
  47.       // decrease shift and height of layer by half
  48.       deltaTexCoord /= 2;
  49.       deltaHeight /= 2;
  50.  
  51.       // new depth from heightmap
  52.       heightFromTexture = texture(depthMap, currentTextureCoords).a;
  53.  
  54.       // shift along or agains vector viewDir
  55.       if(heightFromTexture > currentLayerHeight) // below the surface
  56.       {
  57.          currentTextureCoords -= deltaTexCoord;
  58.          currentLayerHeight += deltaHeight;
  59.       }
  60.       else // above the surface
  61.       {
  62.          currentTextureCoords += deltaTexCoord;
  63.          currentLayerHeight -= deltaHeight;
  64.       }
  65.    }
  66.  
  67.    // return results
  68.    //parallaxHeight = currentLayerHeight;
  69.    return currentTextureCoords;
  70. }
RAW Paste Data