AnyHit.hlsl 2.6 KB

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