OIT_frag.glsl 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. uniform sampler2DArray ColorLayers;
  2. uniform sampler2DArray DepthLayers;
  3. void main()
  4. {
  5. const int layerCount = 6;
  6. vec4 vColor[layerCount];
  7. float vDepth[layerCount];
  8. int vSurfOrder[layerCount];
  9. int i = 0;
  10. // Calculate un-normalized texture coordinates
  11. vec2 tmp = floor(textureSize(DepthLayers, 0).xy * gl_TexCoord[0].st);
  12. // First, get sample data and init the surface order
  13. for (i = 0; i < layerCount; i++)
  14. {
  15. vSurfOrder[i] = i;
  16. vColor[i] = texelFetch(ColorLayers, ivec3(tmp, i), 0);
  17. vDepth[i] = texelFetch(DepthLayers, ivec3(tmp, i), 0).r;
  18. }
  19. // Sort depth values, largest to front and smallest to back
  20. // Must run through array (size^2-size) times, or early-exit
  21. // if any pass shows all samples to be in order
  22. for (int j = 0; j < layerCount; j++)
  23. {
  24. bool bFinished = true;
  25. for (i = 0; i < (layerCount-1); i++)
  26. {
  27. float temp1 = vDepth[vSurfOrder[i]];
  28. float temp2 = vDepth[vSurfOrder[i+1]];
  29. if (temp2 < temp1)
  30. {
  31. // swap values
  32. int tempIndex = vSurfOrder[i];
  33. vSurfOrder[i] = vSurfOrder[i+1];
  34. vSurfOrder[i+1] = tempIndex;
  35. bFinished = false;
  36. }
  37. }
  38. if (bFinished) j = layerCount;
  39. }
  40. // Now, sum all colors in order from front to back. Apply alpha.
  41. bool bFoundFirstColor = false;
  42. vec4 summedColor = vec4(0.0, 0.0, 0.0, 0.0);
  43. for (i = (layerCount-1); i >= 0; i--)
  44. {
  45. int surfIndex = vSurfOrder[i];
  46. if(vColor[surfIndex].a > 0.001)
  47. {
  48. if (bFoundFirstColor == false)
  49. {
  50. // apply 100% of the first color
  51. summedColor = vColor[surfIndex];
  52. bFoundFirstColor = true;
  53. }
  54. else
  55. {
  56. // apply color with alpha
  57. summedColor.rgb = (summedColor.rgb * (1.0 - vColor[surfIndex].a)) +
  58. (vColor[surfIndex].rgb * vColor[surfIndex].a);
  59. }
  60. }
  61. }
  62. gl_FragColor = vec4(summedColor.rgb, 1.0);
  63. }