SimpleBlocksAnyHit.hlsl 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "Common.hlsl"
  2. Texture2D<float4> textures[] : register(t0, space1);
  3. SamplerState gSampler : register(s0, space0);
  4. struct VertexData
  5. {
  6. float2 texcoord;
  7. float3 normal;
  8. };
  9. StructuredBuffer<int> textureIdBuffer : register(t1, space2);
  10. StructuredBuffer<int> indexBuffer : register(t1, space3);
  11. StructuredBuffer<VertexData> vertexData : register(t1, space4);
  12. StructuredBuffer<int> indexOffsetBuffer : register(t1, space5);
  13. [shader("anyhit")]
  14. void SimpleBlocksAnyHit(inout HitInfo payload, SimpleBlocksAttributes attrib)
  15. {
  16. //payload.colorAndDistance = float4(1, 1, 1, 1.0);
  17. int instanceId = InstanceID();
  18. int currentTriangle = PrimitiveIndex();
  19. int geometryIndex = GeometryIndex();
  20. int textureId = textureIdBuffer[geometryIndex];
  21. Texture2D<float4> texture = textures[textureId];
  22. int index = indexOffsetBuffer[geometryIndex] + currentTriangle * 3;
  23. VertexData v0 = vertexData[indexBuffer[index]];
  24. VertexData v1 = vertexData[indexBuffer[index + 1]];
  25. VertexData v2 = vertexData[indexBuffer[index + 2]];
  26. float2 texcoord = v0.texcoord * (1 - attrib.bary.x - attrib.bary.y) + v1.texcoord * attrib.bary.x + v2.texcoord * attrib.bary.y;
  27. float4 color = texture.SampleLevel(gSampler, texcoord, 0);
  28. if (color.w == 0.f)
  29. {
  30. IgnoreHit();
  31. }
  32. float distance = RayTCurrent();
  33. bool found = false;
  34. for (int i = 0; i < payload.hitCount; i++)
  35. {
  36. if (payload.distance[i] > distance)
  37. {
  38. found = true;
  39. float4 tmpColor = payload.color[i];
  40. payload.color[i] = color;
  41. float tmpDistance = payload.distance[i];
  42. payload.distance[i] = distance;
  43. if (color.w == 1.f)
  44. {
  45. payload.hitCount = i + 1;
  46. }
  47. else
  48. {
  49. for (int j = i + 1; j < payload.hitCount + 1 && j < MAX_TRANSPACENT_HITS; j++)
  50. {
  51. float4 tmpColor2 = payload.color[j];
  52. float tmpDistance2 = payload.distance[j];
  53. payload.color[j] = tmpColor;
  54. payload.distance[j] = tmpDistance;
  55. tmpColor = tmpColor2;
  56. tmpDistance = tmpDistance2;
  57. }
  58. }
  59. break;
  60. }
  61. else
  62. {
  63. if (payload.color[i].w == 1.f)
  64. {
  65. found = true;
  66. break;
  67. }
  68. }
  69. }
  70. if (!found && payload.hitCount < MAX_TRANSPACENT_HITS)
  71. {
  72. payload.color[payload.hitCount] = color;
  73. payload.distance[payload.hitCount] = distance;
  74. payload.hitCount++;
  75. }
  76. if (color.w < 1.f)
  77. {
  78. IgnoreHit();
  79. }
  80. }