AnyHit.hlsl 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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> polygonSizeBuffer : register(t1, space5);
  13. [shader("anyhit")]
  14. void AnyHit(inout HitInfo payload, Attributes attrib)
  15. {
  16. //payload.colorAndDistance = float4(1, 1, 1, 1.0);
  17. int instanceId = InstanceID();
  18. int currentTriangle = PrimitiveIndex();
  19. int textureId = 0;
  20. for (int i = 0; currentTriangle >= 0; i++)
  21. {
  22. currentTriangle -= polygonSizeBuffer[i];
  23. textureId = textureIdBuffer[i];
  24. }
  25. Texture2D<float4> texture = textures[textureId];
  26. int index = PrimitiveIndex() * 3;
  27. VertexData v0 = vertexData[indexBuffer[index]];
  28. VertexData v1 = vertexData[indexBuffer[index + 1]];
  29. VertexData v2 = vertexData[indexBuffer[index + 2]];
  30. float2 texcoord = v0.texcoord * (1 - attrib.bary.x - attrib.bary.y) + v1.texcoord * attrib.bary.x + v2.texcoord * attrib.bary.y;
  31. float4 color = texture.SampleLevel(gSampler, texcoord, 0);
  32. if (color.w == 0.f)
  33. {
  34. IgnoreHit();
  35. }
  36. float distance = RayTCurrent();
  37. bool found = false;
  38. for (int i = 0; i < payload.hitCount; i++)
  39. {
  40. if (payload.distance[i] > distance)
  41. {
  42. found = true;
  43. float4 tmpColor = payload.color[i];
  44. payload.color[i] = color;
  45. float tmpDistance = payload.distance[i];
  46. payload.distance[i] = distance;
  47. if (color.w == 1.f)
  48. {
  49. payload.hitCount = i + 1;
  50. }
  51. else
  52. {
  53. for (int j = i + 1; j < payload.hitCount + 1 && j < MAX_TRANSPACENT_HITS; j++)
  54. {
  55. float4 tmpColor2 = payload.color[j];
  56. float tmpDistance2 = payload.distance[j];
  57. payload.color[j] = tmpColor;
  58. payload.distance[j] = tmpDistance;
  59. tmpColor = tmpColor2;
  60. tmpDistance = tmpDistance2;
  61. }
  62. }
  63. break;
  64. }
  65. else
  66. {
  67. if (payload.color[i].w == 1.f)
  68. {
  69. found = true;
  70. break;
  71. }
  72. }
  73. }
  74. if (!found && payload.hitCount < MAX_TRANSPACENT_HITS)
  75. {
  76. payload.color[payload.hitCount] = color;
  77. payload.distance[payload.hitCount] = distance;
  78. payload.hitCount++;
  79. }
  80. if (color.w < 1.f)
  81. {
  82. IgnoreHit();
  83. }
  84. }