<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.3.2">Jekyll</generator><link href="https://penantumbra.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://penantumbra.github.io/" rel="alternate" type="text/html" /><updated>2026-11-24T15:53:52+00:00</updated><id>https://penantumbra.github.io/feed.xml</id><title type="html">Penantumbra Tech Blogs</title><subtitle></subtitle><entry><title type="html">Alpha-Tested Ray-Traced Shadows with Ray Queries</title><link href="https://penantumbra.github.io/ray-traced-alpha-shadows/" rel="alternate" type="text/html" title="Alpha-Tested Ray-Traced Shadows with Ray Queries" /><published>2026-11-24T00:00:00+00:00</published><updated>2026-11-24T00:00:00+00:00</updated><id>https://penantumbra.github.io/ray-traced-alpha-shadows</id><content type="html" xml:base="https://penantumbra.github.io/ray-traced-alpha-shadows/"><![CDATA[<p>Foliage and fences often use alpha-tested textures to cut holes in a small number of triangles. A shadow ray intersects the full triangle, so the renderer must decide whether the hit falls on solid material or a cutout.</p>

<p>This article compares five ways to make that decision with inline ray queries, from treating every hit as opaque to using opacity micromaps. The methods differ in where they evaluate opacity and how much work remains in the shader.</p>

<h2 id="shared-assumptions">Shared assumptions</h2>

<p>The examples use HLSL-style ray queries and return <code class="language-plaintext highlighter-rouge">true</code> when the ray is blocked. They assume triangle geometry, a valid shadow-ray interval, and an origin offset that avoids self-intersection.</p>

<p>Solid geometry is built as opaque. Alpha-masked geometry is built as non-opaque so it can produce candidates for shader-side testing. The examples cover binary cutout shadows. <code class="language-plaintext highlighter-rouge">LoadRTDraw()</code> maps an instance ID to mesh data, and <code class="language-plaintext highlighter-rouge">SampleRayTracingAlpha()</code> reconstructs UVs and evaluates texture alpha together with the material alpha factor. Alpha sampling uses an explicit LOD because neighboring shadow rays do not necessarily hit the same surface.</p>

<h2 id="opaque-baseline">Opaque baseline</h2>

<p>The simplest path treats every triangle as opaque. This avoids material lookups and alpha texture samples, but foliage cards cast the silhouette of their full triangles.</p>

<div class="language-hlsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">bool</span> <span class="nf">TraceRTShadowOpaque</span><span class="p">(</span><span class="n">RaytracingAccelerationStructure</span> <span class="n">Scene</span><span class="p">,</span> <span class="n">RayDesc</span> <span class="n">Ray</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">RayQuery</span><span class="o">&lt;</span><span class="n">RAY_FLAG_ACCEPT_FIRST_HIT_AND_END_SEARCH</span> <span class="o">|</span>
             <span class="n">RAY_FLAG_FORCE_OPAQUE</span> <span class="o">|</span> <span class="n">RAY_FLAG_SKIP_PROCEDURAL_PRIMITIVES</span><span class="o">&gt;</span> <span class="n">Rq</span><span class="p">;</span>
    <span class="n">Rq</span><span class="p">.</span><span class="n">TraceRayInline</span><span class="p">(</span><span class="n">Scene</span><span class="p">,</span> <span class="n">RAY_FLAG_NONE</span><span class="p">,</span> <span class="mh">0xff</span><span class="p">,</span> <span class="n">Ray</span><span class="p">);</span>
    <span class="n">Rq</span><span class="p">.</span><span class="n">Proceed</span><span class="p">();</span>
    <span class="k">return</span> <span class="n">Rq</span><span class="p">.</span><span class="n">CommittedStatus</span><span class="p">()</span> <span class="o">==</span> <span class="n">COMMITTED_TRIANGLE_HIT</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">FORCE_OPAQUE</code> prevents non-opaque triangle candidates from returning to the shader. With procedural primitives skipped, one <code class="language-plaintext highlighter-rouge">Proceed()</code> completes the query. <code class="language-plaintext highlighter-rouge">ACCEPT_FIRST_HIT_AND_END_SEARCH</code> allows traversal to stop at the first accepted blocker because a binary shadow only needs to know whether a blocker exists.</p>

<h2 id="candidate-alpha-testing">Candidate alpha testing</h2>

<p>This is the inline equivalent of an any-hit alpha test. Each non-opaque candidate provides a primitive index and barycentric coordinates. The shader samples alpha and commits the candidate when it meets the material cutoff. Leaving a candidate uncommitted lets traversal continue.</p>

<div class="language-hlsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">bool</span> <span class="nf">TraceRTShadowAlpha</span><span class="p">(</span><span class="n">RaytracingAccelerationStructure</span> <span class="n">Scene</span><span class="p">,</span> <span class="n">RayDesc</span> <span class="n">Ray</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">RayQuery</span><span class="o">&lt;</span><span class="n">RAY_FLAG_ACCEPT_FIRST_HIT_AND_END_SEARCH</span> <span class="o">|</span> <span class="n">RAY_FLAG_SKIP_PROCEDURAL_PRIMITIVES</span><span class="o">&gt;</span> <span class="n">Rq</span><span class="p">;</span>
    <span class="n">Rq</span><span class="p">.</span><span class="n">TraceRayInline</span><span class="p">(</span><span class="n">Scene</span><span class="p">,</span> <span class="n">RAY_FLAG_NONE</span><span class="p">,</span> <span class="mh">0xff</span><span class="p">,</span> <span class="n">Ray</span><span class="p">);</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">Rq</span><span class="p">.</span><span class="n">Proceed</span><span class="p">())</span>
    <span class="p">{</span>
        <span class="n">GpuDrawData</span> <span class="n">Mesh</span> <span class="o">=</span> <span class="n">LoadRTDraw</span><span class="p">(</span><span class="n">uint</span><span class="p">(</span><span class="n">Rq</span><span class="p">.</span><span class="n">CandidateInstanceID</span><span class="p">()));</span>
        <span class="kt">ByteAddressBuffer</span> <span class="n">Materials</span> <span class="o">=</span> <span class="n">ResourceDescriptorHeap</span><span class="p">[</span><span class="n">MaterialsIndex</span><span class="p">];</span>
        <span class="n">GpuMaterialData</span>   <span class="n">Material</span> <span class="o">=</span> <span class="n">Materials</span><span class="p">.</span><span class="n">Load</span><span class="o">&lt;</span><span class="n">GpuMaterialData</span><span class="o">&gt;</span><span class="p">(</span><span class="n">Mesh</span><span class="p">.</span><span class="n">Material</span> <span class="o">*</span> <span class="kr">sizeof</span><span class="p">(</span><span class="n">GpuMaterialData</span><span class="p">));</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">SampleRayTracingAlpha</span><span class="p">(</span><span class="n">Mesh</span><span class="p">,</span> <span class="n">Material</span><span class="p">,</span> <span class="n">Rq</span><span class="p">.</span><span class="n">CandidatePrimitiveIndex</span><span class="p">(),</span> <span class="n">Rq</span><span class="p">.</span><span class="n">CandidateTriangleBarycentrics</span><span class="p">())</span> <span class="o">&gt;=</span> <span class="n">Material</span><span class="p">.</span><span class="n">AlphaCutoff</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">Rq</span><span class="p">.</span><span class="n">CommitNonOpaqueTriangleHit</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">Rq</span><span class="p">.</span><span class="n">CommittedStatus</span><span class="p">()</span> <span class="o">==</span> <span class="n">COMMITTED_TRIANGLE_HIT</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Opaque geometry is handled automatically. For masked geometry, the cost includes mesh and material reads, UV reconstruction, texture sampling, and returning control between traversal and shader code. Dense layers of foliage can require many candidate tests per ray.</p>

<h2 id="opaque-retracing">Opaque retracing</h2>

<p>Another approach forces opaque traversal, retrieves the closest hit, and evaluates its alpha afterward. If the hit is a cutout, the shader advances <code class="language-plaintext highlighter-rouge">TMin</code> and starts another query along the same ray.</p>

<div class="language-hlsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">bool</span> <span class="nf">TraceRTShadowRetrace</span><span class="p">(</span><span class="n">RaytracingAccelerationStructure</span> <span class="n">Scene</span><span class="p">,</span> <span class="n">RayDesc</span> <span class="n">Ray</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">RayQuery</span><span class="o">&lt;</span><span class="n">RAY_FLAG_FORCE_OPAQUE</span> <span class="o">|</span> <span class="n">RAY_FLAG_SKIP_PROCEDURAL_PRIMITIVES</span><span class="o">&gt;</span> <span class="n">Rq</span><span class="p">;</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">uint</span> <span class="n">Depth</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">Depth</span> <span class="o">&lt;</span> <span class="n">RetraceMaxDepth</span><span class="p">;</span> <span class="o">++</span><span class="n">Depth</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">Rq</span><span class="p">.</span><span class="n">TraceRayInline</span><span class="p">(</span><span class="n">Scene</span><span class="p">,</span> <span class="n">RAY_FLAG_NONE</span><span class="p">,</span> <span class="mh">0xff</span><span class="p">,</span> <span class="n">Ray</span><span class="p">);</span>
        <span class="n">Rq</span><span class="p">.</span><span class="n">Proceed</span><span class="p">();</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">Rq</span><span class="p">.</span><span class="n">CommittedStatus</span><span class="p">()</span> <span class="o">==</span> <span class="n">COMMITTED_NOTHING</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">return</span> <span class="nb">false</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="n">GpuDrawData</span> <span class="n">Mesh</span> <span class="o">=</span> <span class="n">LoadRTDraw</span><span class="p">(</span><span class="n">uint</span><span class="p">(</span><span class="n">Rq</span><span class="p">.</span><span class="n">CommittedInstanceID</span><span class="p">()));</span>
        <span class="kt">ByteAddressBuffer</span> <span class="n">Materials</span> <span class="o">=</span> <span class="n">ResourceDescriptorHeap</span><span class="p">[</span><span class="n">MaterialsIndex</span><span class="p">];</span>
        <span class="n">GpuMaterialData</span>   <span class="n">Material</span> <span class="o">=</span> <span class="n">Materials</span><span class="p">.</span><span class="n">Load</span><span class="o">&lt;</span><span class="n">GpuMaterialData</span><span class="o">&gt;</span><span class="p">(</span><span class="n">Mesh</span><span class="p">.</span><span class="n">Material</span> <span class="o">*</span> <span class="kr">sizeof</span><span class="p">(</span><span class="n">GpuMaterialData</span><span class="p">));</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">SampleRayTracingAlpha</span><span class="p">(</span><span class="n">Mesh</span><span class="p">,</span> <span class="n">Material</span><span class="p">,</span> <span class="n">Rq</span><span class="p">.</span><span class="n">CommittedPrimitiveIndex</span><span class="p">(),</span> <span class="n">Rq</span><span class="p">.</span><span class="n">CommittedTriangleBarycentrics</span><span class="p">())</span> <span class="o">&gt;=</span> <span class="n">Material</span><span class="p">.</span><span class="n">AlphaCutoff</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">return</span> <span class="nb">true</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="c1">// Positive ray distances: advance one representable float without a fixed gap.</span>
        <span class="n">Ray</span><span class="p">.</span><span class="n">TMin</span> <span class="o">=</span> <span class="nb">asfloat</span><span class="p">(</span><span class="nb">asuint</span><span class="p">(</span><span class="n">Rq</span><span class="p">.</span><span class="n">CommittedRayT</span><span class="p">())</span> <span class="o">+</span> <span class="mi">1u</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">Ray</span><span class="p">.</span><span class="n">TMin</span> <span class="o">&gt;=</span> <span class="n">Ray</span><span class="p">.</span><span class="n">TMax</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">return</span> <span class="nb">false</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
    <span class="c1">// Conservatively keep the shadow when the budget is exhausted.</span>
    <span class="k">return</span> <span class="nb">true</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This path must find the closest hit on each iteration. Using <code class="language-plaintext highlighter-rouge">ACCEPT_FIRST_HIT_AND_END_SEARCH</code> could return a farther cutout first, and advancing past it could skip a nearer blocker.</p>

<p>For positive finite ray distances, incrementing the float bit pattern advances <code class="language-plaintext highlighter-rouge">TMin</code> by one representable value. This avoids introducing a fixed gap between traces, although it does not remove the need for a robust initial ray offset.</p>

<p><code class="language-plaintext highlighter-rouge">RetraceMaxDepth</code> bounds the number of queries. A miss returns unblocked, an accepted alpha test returns blocked, and an exhausted budget conservatively returns blocked. A small budget can therefore make layered foliage too dark. Repeated traversal also has a cost, so opaque retracing needs to be measured against candidate testing on the target GPU and scene.</p>

<h2 id="screen-space-alpha-testing">Screen-space alpha testing</h2>

<p>The GBuffer has already alpha-tested the surfaces visible to the camera. That depth can provide evidence that a masked hit lies in a cutout. If the hit projects clearly in front of the visible surface, its triangle did not write depth there. A valid projected hit over sky provides similar evidence.</p>

<p>The test below ignores those hits. Hits near the visible depth, behind it, outside the screen, or outside the camera clip range are kept as blockers.</p>

<div class="language-hlsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">bool</span> <span class="nf">ScreenSpaceAlphaCutout</span><span class="p">(</span><span class="kt">float3</span> <span class="n">HitPosition</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">StructuredBuffer</span><span class="o">&lt;</span><span class="n">FrameData</span><span class="o">&gt;</span> <span class="n">Frames</span> <span class="o">=</span> <span class="n">ResourceDescriptorHeap</span><span class="p">[</span><span class="n">FrameIndexBuffer</span><span class="p">];</span>
    <span class="k">const</span> <span class="kt">float4</span>                <span class="n">Clip</span> <span class="o">=</span> <span class="nb">mul</span><span class="p">(</span><span class="n">Frames</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="n">ViewProjection</span><span class="p">,</span> <span class="kt">float4</span><span class="p">(</span><span class="n">HitPosition</span><span class="p">,</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">));</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Clip</span><span class="p">.</span><span class="n">w</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nb">false</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">const</span> <span class="kt">float3</span> <span class="n">Ndc</span> <span class="o">=</span> <span class="n">Clip</span><span class="p">.</span><span class="n">xyz</span> <span class="o">/</span> <span class="n">Clip</span><span class="p">.</span><span class="n">w</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="nb">any</span><span class="p">(</span><span class="nb">abs</span><span class="p">(</span><span class="n">Ndc</span><span class="p">.</span><span class="n">xy</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">)</span> <span class="o">||</span> <span class="n">Ndc</span><span class="p">.</span><span class="n">z</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span> <span class="o">||</span> <span class="n">Ndc</span><span class="p">.</span><span class="n">z</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nb">false</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="kt">Texture2D</span><span class="o">&lt;</span><span class="n">float</span><span class="o">&gt;</span> <span class="n">DepthTexture</span> <span class="o">=</span> <span class="n">ResourceDescriptorHeap</span><span class="p">[</span><span class="n">DepthIndex</span><span class="p">];</span>
    <span class="n">uint2</span>            <span class="n">Size</span><span class="p">;</span>
    <span class="n">DepthTexture</span><span class="p">.</span><span class="n">GetDimensions</span><span class="p">(</span><span class="n">Size</span><span class="p">.</span><span class="n">x</span><span class="p">,</span> <span class="n">Size</span><span class="p">.</span><span class="n">y</span><span class="p">);</span>
    <span class="k">const</span> <span class="n">uint2</span> <span class="n">Pixel</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">uint2</span><span class="p">((</span><span class="n">Ndc</span><span class="p">.</span><span class="n">xy</span> <span class="o">*</span> <span class="kt">float2</span><span class="p">(</span><span class="mi">0</span><span class="p">.</span><span class="mi">5</span><span class="p">,</span> <span class="o">-</span><span class="mi">0</span><span class="p">.</span><span class="mi">5</span><span class="p">)</span> <span class="o">+</span> <span class="mi">0</span><span class="p">.</span><span class="mi">5</span><span class="p">)</span> <span class="o">*</span> <span class="kt">float2</span><span class="p">(</span><span class="n">Size</span><span class="p">)),</span> <span class="n">Size</span> <span class="o">-</span> <span class="mi">1</span><span class="p">);</span>
    <span class="k">const</span> <span class="n">float</span> <span class="n">SceneDepth</span> <span class="o">=</span> <span class="n">DepthTexture</span><span class="p">.</span><span class="n">Load</span><span class="p">(</span><span class="kt">int3</span><span class="p">(</span><span class="n">Pixel</span><span class="p">,</span> <span class="mi">0</span><span class="p">));</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">SceneDepth</span> <span class="o">&gt;=</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nb">true</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="c1">// Express the tolerance as a fraction of camera distance.</span>
    <span class="k">const</span> <span class="kt">float3</span> <span class="n">Eye</span> <span class="o">=</span> <span class="n">Frames</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="n">Eye</span><span class="p">.</span><span class="n">xyz</span><span class="p">;</span>
    <span class="k">const</span> <span class="kt">float3</span> <span class="n">Visible</span> <span class="o">=</span> <span class="n">ReconstructWorldPosition</span><span class="p">((</span><span class="kt">float2</span><span class="p">(</span><span class="n">Pixel</span><span class="p">)</span> <span class="o">+</span> <span class="mi">0</span><span class="p">.</span><span class="mi">5</span><span class="p">)</span> <span class="o">/</span> <span class="kt">float2</span><span class="p">(</span><span class="n">Size</span><span class="p">),</span> <span class="n">SceneDepth</span><span class="p">,</span> <span class="n">Frames</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="n">InverseViewProjection</span><span class="p">);</span>
    <span class="k">const</span> <span class="n">float</span>  <span class="n">VisibleDistance</span> <span class="o">=</span> <span class="nb">length</span><span class="p">(</span><span class="n">Visible</span> <span class="o">-</span> <span class="n">Eye</span><span class="p">);</span>
    <span class="k">return</span> <span class="nb">length</span><span class="p">(</span><span class="n">HitPosition</span> <span class="o">-</span> <span class="n">Eye</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">VisibleDistance</span> <span class="o">*</span> <span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="mi">0</span> <span class="o">-</span> <span class="n">ScreenSpaceAlphaTestDepthBias</span><span class="p">);</span>
<span class="p">}</span>

<span class="n">bool</span> <span class="nf">TraceRTShadowScreenSpace</span><span class="p">(</span><span class="n">RaytracingAccelerationStructure</span> <span class="n">Scene</span><span class="p">,</span> <span class="n">RayDesc</span> <span class="n">Ray</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">RayQuery</span><span class="o">&lt;</span><span class="n">RAY_FLAG_ACCEPT_FIRST_HIT_AND_END_SEARCH</span> <span class="o">|</span> <span class="n">RAY_FLAG_SKIP_PROCEDURAL_PRIMITIVES</span><span class="o">&gt;</span> <span class="n">Rq</span><span class="p">;</span>
    <span class="n">Rq</span><span class="p">.</span><span class="n">TraceRayInline</span><span class="p">(</span><span class="n">Scene</span><span class="p">,</span> <span class="n">RAY_FLAG_NONE</span><span class="p">,</span> <span class="mh">0xff</span><span class="p">,</span> <span class="n">Ray</span><span class="p">);</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">Rq</span><span class="p">.</span><span class="n">Proceed</span><span class="p">())</span>
    <span class="p">{</span>
        <span class="k">const</span> <span class="kt">float3</span> <span class="n">HitPosition</span> <span class="o">=</span> <span class="n">Ray</span><span class="p">.</span><span class="n">Origin</span> <span class="o">+</span> <span class="n">Ray</span><span class="p">.</span><span class="n">Direction</span> <span class="o">*</span> <span class="n">Rq</span><span class="p">.</span><span class="n">CandidateTriangleRayT</span><span class="p">();</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">ScreenSpaceAlphaCutout</span><span class="p">(</span><span class="n">HitPosition</span><span class="p">))</span>
        <span class="p">{</span>
            <span class="n">Rq</span><span class="p">.</span><span class="n">CommitNonOpaqueTriangleHit</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">Rq</span><span class="p">.</span><span class="n">CommittedStatus</span><span class="p">()</span> <span class="o">==</span> <span class="n">COMMITTED_TRIANGLE_HIT</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This example assumes forward-Z depth in the range [0, 1], with a clear value of 1. The UV conversion matches a framebuffer whose Y direction is opposite to camera NDC. <code class="language-plaintext highlighter-rouge">ReconstructWorldPosition()</code> uses the same projection and depth convention as the GBuffer.</p>

<p><code class="language-plaintext highlighter-rouge">ScreenSpaceAlphaTestDepthBias</code> is a relative camera-distance tolerance. A value of 0.001 requires the hit to be at least 0.1% closer than the reconstructed visible surface before rejecting it. This avoids expressing the tolerance in nonlinear depth units. Depth quantization and pixel discretization still affect the result.</p>

<p>The inference depends on the masked triangles being present in the camera pass with matching geometry, transforms, and alpha rules. Backface culling must not remove surfaces that the shadow rays can hit. Camera-pass occlusion culling or mismatched LODs can also invalidate the inference.</p>

<p>This method avoids material-alpha sampling, but it still reads scene depth and reconstructs a position. Hidden and off-screen cutouts remain opaque, so shadows can be too dark and can change as the camera moves. Thin geometry and silhouette pixels are particularly sensitive to the depth comparison.</p>

<h2 id="opacity-micromaps">Opacity micromaps</h2>

<p>Opacity micromaps precompute opacity classifications over subdivided triangles and attach the data to ray tracing geometry. Traversal can then resolve many hits before returning a candidate to the shader. The feature requires API, driver, and hardware support. The acceleration-structure build flags and shader or pipeline declarations must enable OMM for the selected API. The candidate alpha-test function above can remain the fallback for unresolved hits.</p>

<p>A 2-state micromap stores one bit per microtriangle for opaque or transparent. A 4-state micromap stores two bits and adds unknown states. With ordinary 4-state traversal, opaque hits are accepted, transparent hits are ignored, and unknown hits still reach the shader for alpha testing. These traversal rules are described in the <a href="https://docs.vulkan.org/spec/latest/chapters/raytraversal.html">Vulkan specification</a>.</p>

<p>At subdivision level L, a triangle has 4^L microtriangles. Higher levels can classify smaller regions around alpha boundaries, at the cost of more bake work and data. A low level may leave much of a detailed leaf texture unknown, so alpha-test shader execution can remain substantial even with OMM enabled.</p>

<p>OMM also adds preprocessing and resource-management costs. Changes to the alpha texture, cutoff, UV mapping, or subdivision settings may require rebaking micromaps and rebuilding the associated acceleration structures. Whether this pays off depends on how often those costs are incurred and how much runtime alpha testing is avoided.</p>

<h2 id="visual-comparison">Visual comparison</h2>

<h3 id="screen-space-alpha-test">Screen-space alpha test</h3>

<p><img src="/assets/img/ray-traced-alpha-shadows/screen-space-alpha-test.jpg" alt="Screen-space alpha test" /></p>

<h3 id="opaque-retrace">Opaque retrace</h3>

<p><img src="/assets/img/ray-traced-alpha-shadows/opaque-retrace.jpg" alt="Opaque retrace" /></p>

<h3 id="alpha-test">Alpha test</h3>

<p><img src="/assets/img/ray-traced-alpha-shadows/candidate-alpha-test.jpg" alt="Alpha test" /></p>

<h3 id="opaque">Opaque</h3>

<p><img src="/assets/img/ray-traced-alpha-shadows/opaque.jpg" alt="Opaque" /></p>

<h3 id="opacity-micromaps-omm">Opacity micromaps (OMM)</h3>

<p><img src="/assets/img/ray-traced-alpha-shadows/omm.jpg" alt="Opacity micromaps (OMM)" /></p>

<h2 id="comparing-the-methods">Comparing the methods</h2>

<table>
  <thead>
    <tr>
      <th>Method</th>
      <th>Opacity work</th>
      <th>Main tradeoff</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Opaque</td>
      <td>No material-alpha evaluation</td>
      <td>Full triangles block light</td>
    </tr>
    <tr>
      <td>Candidate alpha test</td>
      <td>Shader evaluates non-opaque candidates</td>
      <td>Candidate and texture costs grow with foliage overlap</td>
    </tr>
    <tr>
      <td>Opaque retrace</td>
      <td>Shader evaluates each closest hit</td>
      <td>Repeated traversal and a finite query budget</td>
    </tr>
    <tr>
      <td>Screen space</td>
      <td>Camera depth approximates cutouts</td>
      <td>View-dependent errors and incomplete coverage</td>
    </tr>
    <tr>
      <td>OMM</td>
      <td>Precomputed classifications, with shader fallback for unknowns</td>
      <td>Bake cost, storage, and feature support</td>
    </tr>
  </tbody>
</table>

<p>Candidate alpha testing provides a useful quality reference. Opaque retracing trades candidate processing for repeated queries, while screen-space testing accepts view-dependent error to avoid material-alpha reads. OMM moves part of the classification work into preprocessing and traversal.</p>

<p>For an isolated comparison, run the first four methods with OMM disabled. With OMM enabled, its classifications can resolve hits before shader-side alpha testing.</p>

<p>The practical choice depends on foliage density, alpha complexity, camera position, and GPU architecture. Comparing GPU time and shadow quality across representative views gives a more reliable basis than counting alpha samples alone. OMM comparisons should also account for bake time, memory use, and how frequently the data changes.</p>

<h2 id="references">References</h2>

<ul>
  <li><a href="https://developer.mediatek.com/RayTracing/642649b5f55b040d6989a9a1.html">MediaTek — Best Practices for Mobile Ray Tracing</a></li>
  <li><a href="https://www.youtube.com/watch?v=Gq1QdlQSzn0">Real-Time Path Tracing in RE ENGINE for Resident Evil Requiem and PRAGMATA</a></li>
  <li><a href="https://devblogs.microsoft.com/directx/omm/">Microsoft DirectX Developer Blog — D3D12 Opacity Micromaps</a></li>
  <li><a href="https://docs.vulkan.org/spec/latest/chapters/raytraversal.html">Vulkan Specification — Ray Traversal</a></li>
</ul>]]></content><author><name></name></author><category term="ideas" /><summary type="html"><![CDATA[Foliage and fences often use alpha-tested textures to cut holes in a small number of triangles. A shadow ray intersects the full triangle, so the renderer must decide whether the hit falls on solid material or a cutout.]]></summary></entry><entry><title type="html">OMM Survey</title><link href="https://penantumbra.github.io/omm/" rel="alternate" type="text/html" title="OMM Survey" /><published>2026-11-19T00:00:00+00:00</published><updated>2026-11-19T00:00:00+00:00</updated><id>https://penantumbra.github.io/omm</id><content type="html" xml:base="https://penantumbra.github.io/omm/"><![CDATA[<blockquote>
  <p>Opacity Micro Map for Ray Tracing Survey</p>
</blockquote>

<h2 id="background-why-omm">Background: Why OMM?</h2>

<p>RTCore is dedicated hardware for ray-scene intersection. In practice, however, the visible shape of many objects is not defined by geometry alone. Foliage is the classic example: a leaf is usually a simple quad with an alpha texture, and its real silhouette comes from alpha testing.</p>

<p>To support this, DXR exposes the Any-Hit Shader (AHS), which lets the application decide at runtime whether to accept or ignore a given intersection. The problem is that AHS is expensive:</p>

<ul>
  <li>Every invocation forces the GPU to switch between RTCore and the ShaderCore.</li>
  <li>On the ShaderCore, an extra alpha texture fetch is usually needed to make the decision.</li>
</ul>

<p>In foliage-heavy scenes, AHS is often the largest part of the ray tracing cost. This led to a simple idea: bake the alpha texture into a set of subdivided micro-triangles, so the hardware can resolve most intersections with a lookup and skip the AHS. That is the core of the Opacity Micromap (OMM).</p>

<p>The rest of this post walks through how OMM has evolved, in chronological order.</p>

<h2 id="2020--stoc-sub-triangle-opacity-masks">2020 | STOC: Sub-triangle Opacity Masks</h2>

<p>Paper: <em>Sub-triangle opacity masks for faster ray tracing of transparent objects</em>, by Holger Gruen (now at AMD) et al.</p>

<p>The method recursively subdivides each triangle and bakes the opacity from the alpha texture into the resulting sub-triangles. At a high enough subdivision level, the result closely approximates sampling the alpha texture directly.</p>

<p><img src="图片和附件/image%205.png" alt="image.png" /></p>

<p>Each sub-triangle is assigned one of three states:</p>

<table>
  <thead>
    <tr>
      <th>State</th>
      <th>Meaning</th>
      <th>At intersection time</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Opaque</td>
      <td>The whole sub-triangle is opaque</td>
      <td>Accept the hit</td>
    </tr>
    <tr>
      <td>Transparent</td>
      <td>The whole sub-triangle is transparent</td>
      <td>Ignore the hit</td>
    </tr>
    <tr>
      <td>Unknown</td>
      <td>The sub-triangle is partly opaque, partly transparent</td>
      <td>Invoke the AHS and sample alpha</td>
    </tr>
  </tbody>
</table>

<p>The first two states are resolved by reading a few state bits; only the third falls back to the AHS. Finer subdivision shrinks the Unknown region and reduces AHS calls, at the cost of more storage.</p>

<h2 id="2022--omm-in-hardware-dxr-opacity-micromaps">2022 | OMM in Hardware: DXR Opacity Micromaps</h2>

<p>In 2022, DXR introduced an OMM extension, meaning the STOC approach had been built into GPU hardware by the vendors.</p>

<p>A quick recap: the BVH used for ray tracing is a tree whose leaf nodes hold the original triangle data. The RTCore intersection unit reads these nodes and tests them against the ray. With the OMM extension, leaf nodes also carry OMM data, so RTCore can read it and resolve opacity in hardware, without switching back to the ShaderCore.</p>

<p><img src="图片和附件/image%206.png" alt="image.png" /></p>

<p>The ordering of sub-triangles within an OMM is also designed for spatial locality.</p>

<p><img src="图片和附件/image%207.png" alt="image.png" /></p>

<p>On the production side, <em>Alan Wake 2</em> (2023) shipped with OMM and used it to reduce path tracing cost in its foliage-dense scenes.</p>

<h2 id="2023--img-compressed-opacity-maps-for-ray-tracing">2023 | IMG: Compressed Opacity Maps for Ray Tracing</h2>

<p>Paper: <a href="https://diglib.eg.org/server/api/core/bitstreams/c5b73779-98f7-4570-bfe0-836531ddc63c/content">https://diglib.eg.org/server/api/core/bitstreams/c5b73779-98f7-4570-bfe0-836531ddc63c/content</a></p>

<p><img src="图片和附件/image%204.png" alt="image.png" /></p>

<h3 id="motivation-quads-instead-of-triangles">Motivation: quads instead of triangles</h3>

<p>IMG made two observations:</p>

<ol>
  <li>Alpha-tested foliage is almost always built from quads.</li>
  <li>Many IHV implementations already pair the two triangles that share an edge in a leaf node, to save vertex memory.</li>
</ol>

<p><img src="图片和附件/image.png" alt="image.png" /></p>

<p>So they proposed using <strong>quads</strong> instead of triangles as the OMM subdivision unit, combined with lossy VQ (vector quantization) compression.</p>

<h3 id="vq2x2">VQ2x2</h3>

<p>Each subdivision level splits a cell into 4 children, and each child is in one of three states: T (transparent), O (opaque), or C (unknown).</p>

<ul>
  <li>A 2x2 block therefore has 3^4 = 81 possible combinations.</li>
  <li>In real data, T and O never appear together in the same 2x2 block, so mixed blocks follow only two patterns: CT and CO.</li>
  <li>With this constraint, each block fits in 5 bits.</li>
</ul>

<p><img src="图片和附件/image%203.png" alt="image.png" /></p>

<p>2x2 patterns are also symmetric, which allows a further 2–4x compression.</p>

<p><img src="图片和附件/image%209.png" alt="image.png" /></p>

<p>Finally, a pattern-to-LUT table is built, under 256b in size (16x16). If a pattern is missing from the table during decoding, it falls back to C, which defers to the AHS and keeps the result correct.</p>

<p>Result: at 16x16 subdivision and the same memory budget, AHS invocations drop by about 10%.</p>

<h3 id="vq4x4">VQ4x4</h3>

<p>VQ2x2 gives limited gains at 16x16. The authors therefore apply VQ4x4 to 32x32 subdivision, again at 256b of memory, and report about 10% fewer AHS invocations compared with uncompressed 32x32 OMMs.</p>

<h2 id="2024--2026--lossless-compression">2024 / 2026 | Lossless Compression</h2>

<ul>
  <li><strong>2024: Succinct Opacity Micromaps</strong>, based on succinct tree encoding.</li>
  <li><strong>2026: Common Subtree Merging Compressed Opacity Micromaps</strong>, based on an SVDAG that merges repeated subtrees.</li>
</ul>

<p>Both are lossless and cut OMM memory dramatically, but neither brings much performance gain:</p>

<ul>
  <li>Succinct OMMs get slower at high subdivision levels.</li>
  <li>The SVDAG approach performs roughly on par with uncompressed OMMs.</li>
</ul>

<h2 id="beyond-opacity-what-else-can-the-acceleration-structure-hold">Beyond Opacity: What Else Can the Acceleration Structure Hold?</h2>

<p>Reference: <a href="https://www.gustafwaldemarson.com/posts/rendering-small-things/">Rendering Small Things: Hardware Micromaps and Particles</a></p>

<p>Gustaf Waldemarson explored a natural follow-up question: if the acceleration structure can store OMMs, can it store other data too?</p>

<ul>
  <li><strong>Displacement Micromaps</strong>: store per-sub-triangle displacement for finer geometric detail.</li>
  <li><strong>Color Micromaps</strong>: store per-sub-triangle color.</li>
</ul>

<h2 id="summary">Summary</h2>

<p>OMM has evolved in three steps:</p>

<ol>
  <li><strong>The algorithm</strong> (STOC, 2020): subdivision plus a three-state mask moves most alpha-test decisions out of the AHS.</li>
  <li><strong>Hardware adoption</strong> (DXR, 2022): OMM data lives in BVH leaf nodes and is resolved directly by RTCore.</li>
  <li><strong>Compression</strong> (2023 onward): lossy VQ compression further reduces AHS calls at the same memory budget, while lossless schemes mainly save memory with little performance gain.</li>
</ol>

<p>Extensions such as Displacement and Color Micromaps suggest that baking more data into the acceleration structure, and letting fixed-function hardware act on it, still has plenty of room to explore.</p>]]></content><author><name></name></author><category term="ideas" /><summary type="html"><![CDATA[Opacity Micro Map for Ray Tracing Survey Background: Why OMM? RTCore is dedicated hardware for ray-scene intersection. In practice, however, the visible shape of many objects is not defined by geometry alone. Foliage is the classic example: a leaf is usually a simple quad with an alpha texture, and its real silhouette comes from alpha testing. To support this, DXR exposes the Any-Hit Shader (AHS), which lets the application decide at runtime whether to accept or ignore a given intersection. The problem is that AHS is expensive: Every invocation forces the GPU to switch between RTCore and the ShaderCore. On the ShaderCore, an extra alpha texture fetch is usually needed to make the decision. In foliage-heavy scenes, AHS is often the largest part of the ray tracing cost. This led to a simple idea: bake the alpha texture into a set of subdivided micro-triangles, so the hardware can resolve most intersections with a lookup and skip the AHS. That is the core of the Opacity Micromap (OMM). The rest of this post walks through how OMM has evolved, in chronological order. 2020 | STOC: Sub-triangle Opacity Masks Paper: Sub-triangle opacity masks for faster ray tracing of transparent objects, by Holger Gruen (now at AMD) et al. The method recursively subdivides each triangle and bakes the opacity from the alpha texture into the resulting sub-triangles. At a high enough subdivision level, the result closely approximates sampling the alpha texture directly. Each sub-triangle is assigned one of three states: State Meaning At intersection time Opaque The whole sub-triangle is opaque Accept the hit Transparent The whole sub-triangle is transparent Ignore the hit Unknown The sub-triangle is partly opaque, partly transparent Invoke the AHS and sample alpha The first two states are resolved by reading a few state bits; only the third falls back to the AHS. Finer subdivision shrinks the Unknown region and reduces AHS calls, at the cost of more storage. 2022 | OMM in Hardware: DXR Opacity Micromaps In 2022, DXR introduced an OMM extension, meaning the STOC approach had been built into GPU hardware by the vendors. A quick recap: the BVH used for ray tracing is a tree whose leaf nodes hold the original triangle data. The RTCore intersection unit reads these nodes and tests them against the ray. With the OMM extension, leaf nodes also carry OMM data, so RTCore can read it and resolve opacity in hardware, without switching back to the ShaderCore. The ordering of sub-triangles within an OMM is also designed for spatial locality. On the production side, Alan Wake 2 (2023) shipped with OMM and used it to reduce path tracing cost in its foliage-dense scenes. 2023 | IMG: Compressed Opacity Maps for Ray Tracing Paper: https://diglib.eg.org/server/api/core/bitstreams/c5b73779-98f7-4570-bfe0-836531ddc63c/content Motivation: quads instead of triangles IMG made two observations: Alpha-tested foliage is almost always built from quads. Many IHV implementations already pair the two triangles that share an edge in a leaf node, to save vertex memory. So they proposed using quads instead of triangles as the OMM subdivision unit, combined with lossy VQ (vector quantization) compression. VQ2x2 Each subdivision level splits a cell into 4 children, and each child is in one of three states: T (transparent), O (opaque), or C (unknown). A 2x2 block therefore has 3^4 = 81 possible combinations. In real data, T and O never appear together in the same 2x2 block, so mixed blocks follow only two patterns: CT and CO. With this constraint, each block fits in 5 bits. 2x2 patterns are also symmetric, which allows a further 2–4x compression. Finally, a pattern-to-LUT table is built, under 256b in size (16x16). If a pattern is missing from the table during decoding, it falls back to C, which defers to the AHS and keeps the result correct. Result: at 16x16 subdivision and the same memory budget, AHS invocations drop by about 10%. VQ4x4 VQ2x2 gives limited gains at 16x16. The authors therefore apply VQ4x4 to 32x32 subdivision, again at 256b of memory, and report about 10% fewer AHS invocations compared with uncompressed 32x32 OMMs. 2024 / 2026 | Lossless Compression 2024: Succinct Opacity Micromaps, based on succinct tree encoding. 2026: Common Subtree Merging Compressed Opacity Micromaps, based on an SVDAG that merges repeated subtrees. Both are lossless and cut OMM memory dramatically, but neither brings much performance gain: Succinct OMMs get slower at high subdivision levels. The SVDAG approach performs roughly on par with uncompressed OMMs. Beyond Opacity: What Else Can the Acceleration Structure Hold? Reference: Rendering Small Things: Hardware Micromaps and Particles Gustaf Waldemarson explored a natural follow-up question: if the acceleration structure can store OMMs, can it store other data too? Displacement Micromaps: store per-sub-triangle displacement for finer geometric detail. Color Micromaps: store per-sub-triangle color. Summary OMM has evolved in three steps: The algorithm (STOC, 2020): subdivision plus a three-state mask moves most alpha-test decisions out of the AHS. Hardware adoption (DXR, 2022): OMM data lives in BVH leaf nodes and is resolved directly by RTCore. Compression (2023 onward): lossy VQ compression further reduces AHS calls at the same memory budget, while lossless schemes mainly save memory with little performance gain. Extensions such as Displacement and Color Micromaps suggest that baking more data into the acceleration structure, and letting fixed-function hardware act on it, still has plenty of room to explore.]]></summary></entry><entry><title type="html">analysis a android tombstone crash</title><link href="https://penantumbra.github.io/tombstoneanalysis/" rel="alternate" type="text/html" title="analysis a android tombstone crash" /><published>2026-10-21T00:00:00+00:00</published><updated>2026-10-21T00:00:00+00:00</updated><id>https://penantumbra.github.io/tombstoneanalysis</id><content type="html" xml:base="https://penantumbra.github.io/tombstoneanalysis/"><![CDATA[<p>拉取 tombstone 文件：</p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>adb pull /data/tombstones/
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Build fingerprint: 'Xiaomi/lhasa/lhasa:17/CP2A.260605.016/OS4.0.260921.1.XPNCNXM.PRE:userdebug/test-keys'
Kernel Release: '6.18.21-android17-5-maybe-dirty-4k'
Revision: '0'
ABI: 'arm64'
Timestamp: 2026-09-22 18:41:13.604705632+0800
Process uptime: 509s
Executable: /system/bin/app_process64
Cmdline: com.khronos.vulkan_samples
pid: 12103, ppid: 1805, tid: 14016, name: Thread-9  &gt;&gt;&gt; com.khronos.vulkan_samples &lt;&lt;&lt;
uid: 10353
tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE)
pac_enabled_keys: 000000000000000f (PR_PAC_APIAKEY, PR_PAC_APIBKEY, PR_PAC_APDAKEY, PR_PAC_APDBKEY)
esr: 0000000092000046 (Data Abort Exception 0x24)
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x000000000000007c (write)
Cause: null pointer dereference
    x0  0000000000000000  x1  b40000740b2958d0  x2  0000000000000001  x3  0000000000000000
    x4  0000000000000000  x5  0000000000000001  x6  0000007340257438  x7  0000000000000001
    x8  0000000000000006  x9  0000005fce000a48  x10 0000000000000000  x11 0400ff0000000000
    x12 0300000000010000  x13 000000731e51f000  x14 00000000ffffffe8  x15 0000000000000000
    x16 00000073241d5ee0  x17 00000076180c9300  x18 00000072b2e44000  x19 b40000740b2958d0
    x20 0000000000000000  x21 0000000000000000  x22 0000005fc9574a00  x23 0000000000000001
    x24 0000007340257b88  x25 0000007340257558  x26 025000000bad0bad  x27 0000007340257b88
    x28 0000000000004e20  x29 0000007340257728
    lr  0000007320b18c10  sp  00000073402574d0  pc  0000007320b18c3c  pst 0000000060001000
    esr 0000000092000046  vg  0000000000000002

20 total frames
backtrace:
      #00 pc 0000000002900c3c  /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26)
      #01 pc 0000000002900c0c  /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26)
      #02 pc 0000000002877778  /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26)
      #03 pc 0000000001207860  /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26)
      #04 pc 0000000001207b34  /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26)
      #05 pc 00000000011e5a90  /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26)
      #06 pc 000000000098387c  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk (offset 0x92c000) (BuildId: a91af5ca8686d706622bf20c727c551ecccbf6f1)
      #07 pc 0000000000c694e0  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk (offset 0x92c000) (BuildId: a91af5ca8686d706622bf20c727c551ecccbf6f1)
      #08 pc 00000000007f46b4  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (vkb::core::AccelerationStructure::build(VkQueue_T*, unsigned int, VkBuildAccelerationStructureModeKHR)+1704) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817)
      #09 pc 00000000007fc6a0  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (RaytracingExtended::create_bottom_level_acceleration_structure(bool, bool)+472) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817)
      #10 pc 00000000007fda10  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (RaytracingExtended::create_scene()+352) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817)
      #11 pc 0000000000800e0c  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (RaytracingExtended::prepare(vkb::ApplicationOptions const&amp;)+416) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817)
      #12 pc 00000000004d2610  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (vkb::Platform::start_app()+372) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817)
      #13 pc 00000000004d2178  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (vkb::Platform::main_loop_frame()+52) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817)
      #14 pc 00000000004d2b78  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (vkb::Platform::main_loop()+20) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817)
      #15 pc 00000000004ce23c  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (platform_main(vkb::PlatformContext const&amp;)+100) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817)
      #16 pc 00000000004ce164  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (android_main+40) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817)
      #17 pc 0000000000928584  /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817)
      #18 pc 000000000008e830  /apex/com.android.runtime/lib64/bionic/libc.so (__pthread_start(void*) (.__uniq.67847048707805468364044055584648682506)+184) (BuildId: 79c2c20a592482e53185605996fae138)
      #19 pc 000000000007fb24  /apex/com.android.runtime/lib64/bionic/libc.so (__start_thread+68) (BuildId: 79c2c20a592482e53185605996fae138)
</code></pre></div></div>

<p>拉取带符号的驱动文件</p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>adb pull /xxx/libGLES_mali.so
</code></pre></div></div>

<p>用llvm-addr2line.exe和驱动文件寻找crash栈的函数名</p>

<div class="language-bat highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@echo <span class="na">off</span>
<span class="kd">set</span> <span class="s2">"TC=D:\Android\Sdk\ndk\29.0.14206865\toolchains\llvm\prebuilt\windows-x86_64\bin\llvm-addr2line.exe"</span>
<span class="kd">set</span> <span class="s2">"SYM=.\libGLES_mali1.so"</span>

<span class="s2">"</span><span class="nv">%TC%</span><span class="s2">"</span> <span class="na">-f -C -e </span><span class="s2">"</span><span class="nv">%SYM%</span><span class="s2">"</span> <span class="m">0000000002900</span><span class="kd">c3c</span> <span class="m">0000000002900</span><span class="kd">c0c</span> <span class="m">0000000002877778</span>
</code></pre></div></div>

<ul>
  <li>-f：输出函数名（function name）。</li>
  <li>-C：对 C++ 符号做反混淆（demangle），例如把 _ZN3foo3barEv 显示为 foo::bar()。</li>
  <li>-e <文件>：指定要查地址的 ELF/共享库文件，例如 -e libGLES_mali1.so。
注意：你写的 -c 小写通常不是 -C。llvm-addr2line 里常用的是大写 -C；Windows 命令行参数区分大小写。
输出</文件></li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>xxx::xxx::build_acceleration_structure_hploc_single_template_internal::init(xxx::xxx::device_internal const&amp;)
xxx.cpp:0
xxx::xxx::build_acceleration_structure_hploc_template_internal::build_command(xxx::command_memory&amp;, xxx::xxx::gpu_state_internal&amp;, xxx::xxx::command_list_internal&amp;, xxx::acceleration_structure_build_info const&amp;) const
xxx.cpp:0
xxx::xxx::command_buffer_builder::build_acceleration_structure_hploc(xxx::acceleration_structure_build_info const&amp;)
xxx.cpp:0

</code></pre></div></div>]]></content><author><name></name></author><category term="ideas" /><summary type="html"><![CDATA[拉取 tombstone 文件： adb pull /data/tombstones/ Build fingerprint: 'Xiaomi/lhasa/lhasa:17/CP2A.260605.016/OS4.0.260921.1.XPNCNXM.PRE:userdebug/test-keys' Kernel Release: '6.18.21-android17-5-maybe-dirty-4k' Revision: '0' ABI: 'arm64' Timestamp: 2026-09-22 18:41:13.604705632+0800 Process uptime: 509s Executable: /system/bin/app_process64 Cmdline: com.khronos.vulkan_samples pid: 12103, ppid: 1805, tid: 14016, name: Thread-9 &gt;&gt;&gt; com.khronos.vulkan_samples &lt;&lt;&lt; uid: 10353 tagged_addr_ctrl: 0000000000000001 (PR_TAGGED_ADDR_ENABLE) pac_enabled_keys: 000000000000000f (PR_PAC_APIAKEY, PR_PAC_APIBKEY, PR_PAC_APDAKEY, PR_PAC_APDBKEY) esr: 0000000092000046 (Data Abort Exception 0x24) signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x000000000000007c (write) Cause: null pointer dereference x0 0000000000000000 x1 b40000740b2958d0 x2 0000000000000001 x3 0000000000000000 x4 0000000000000000 x5 0000000000000001 x6 0000007340257438 x7 0000000000000001 x8 0000000000000006 x9 0000005fce000a48 x10 0000000000000000 x11 0400ff0000000000 x12 0300000000010000 x13 000000731e51f000 x14 00000000ffffffe8 x15 0000000000000000 x16 00000073241d5ee0 x17 00000076180c9300 x18 00000072b2e44000 x19 b40000740b2958d0 x20 0000000000000000 x21 0000000000000000 x22 0000005fc9574a00 x23 0000000000000001 x24 0000007340257b88 x25 0000007340257558 x26 025000000bad0bad x27 0000007340257b88 x28 0000000000004e20 x29 0000007340257728 lr 0000007320b18c10 sp 00000073402574d0 pc 0000007320b18c3c pst 0000000060001000 esr 0000000092000046 vg 0000000000000002 20 total frames backtrace: #00 pc 0000000002900c3c /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26) #01 pc 0000000002900c0c /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26) #02 pc 0000000002877778 /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26) #03 pc 0000000001207860 /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26) #04 pc 0000000001207b34 /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26) #05 pc 00000000011e5a90 /vendor/lib64/egl/libGLES_mali.so (BuildId: b84ffec1fe5d0c26) #06 pc 000000000098387c /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk (offset 0x92c000) (BuildId: a91af5ca8686d706622bf20c727c551ecccbf6f1) #07 pc 0000000000c694e0 /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk (offset 0x92c000) (BuildId: a91af5ca8686d706622bf20c727c551ecccbf6f1) #08 pc 00000000007f46b4 /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (vkb::core::AccelerationStructure::build(VkQueue_T*, unsigned int, VkBuildAccelerationStructureModeKHR)+1704) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817) #09 pc 00000000007fc6a0 /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (RaytracingExtended::create_bottom_level_acceleration_structure(bool, bool)+472) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817) #10 pc 00000000007fda10 /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (RaytracingExtended::create_scene()+352) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817) #11 pc 0000000000800e0c /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (RaytracingExtended::prepare(vkb::ApplicationOptions const&amp;)+416) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817) #12 pc 00000000004d2610 /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (vkb::Platform::start_app()+372) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817) #13 pc 00000000004d2178 /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (vkb::Platform::main_loop_frame()+52) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817) #14 pc 00000000004d2b78 /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (vkb::Platform::main_loop()+20) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817) #15 pc 00000000004ce23c /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (platform_main(vkb::PlatformContext const&amp;)+100) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817) #16 pc 00000000004ce164 /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (android_main+40) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817) #17 pc 0000000000928584 /data/app/~~RSotEG6DEP5-UOBfM45JuA==/com.khronos.vulkan_samples-iSACuCXQFnjTwltGRAk7kQ==/base.apk!libvulkan_samples.so (offset 0x1e04000) (BuildId: 6df4158d6f2398d8e1d31a25771803c9252dd817) #18 pc 000000000008e830 /apex/com.android.runtime/lib64/bionic/libc.so (__pthread_start(void*) (.__uniq.67847048707805468364044055584648682506)+184) (BuildId: 79c2c20a592482e53185605996fae138) #19 pc 000000000007fb24 /apex/com.android.runtime/lib64/bionic/libc.so (__start_thread+68) (BuildId: 79c2c20a592482e53185605996fae138) 拉取带符号的驱动文件 adb pull /xxx/libGLES_mali.so 用llvm-addr2line.exe和驱动文件寻找crash栈的函数名 @echo off set "TC=D:\Android\Sdk\ndk\29.0.14206865\toolchains\llvm\prebuilt\windows-x86_64\bin\llvm-addr2line.exe" set "SYM=.\libGLES_mali1.so" "%TC%" -f -C -e "%SYM%" 0000000002900c3c 0000000002900c0c 0000000002877778 -f：输出函数名（function name）。 -C：对 C++ 符号做反混淆（demangle），例如把 _ZN3foo3barEv 显示为 foo::bar()。 -e ：指定要查地址的 ELF/共享库文件，例如 -e libGLES_mali1.so。 注意：你写的 -c 小写通常不是 -C。llvm-addr2line 里常用的是大写 -C；Windows 命令行参数区分大小写。 输出 xxx::xxx::build_acceleration_structure_hploc_single_template_internal::init(xxx::xxx::device_internal const&amp;) xxx.cpp:0 xxx::xxx::build_acceleration_structure_hploc_template_internal::build_command(xxx::command_memory&amp;, xxx::xxx::gpu_state_internal&amp;, xxx::xxx::command_list_internal&amp;, xxx::acceleration_structure_build_info const&amp;) const xxx.cpp:0 xxx::xxx::command_buffer_builder::build_acceleration_structure_hploc(xxx::acceleration_structure_build_info const&amp;) xxx.cpp:0]]></summary></entry><entry><title type="html">Vulkan CTS</title><link href="https://penantumbra.github.io/vulkancts/" rel="alternate" type="text/html" title="Vulkan CTS" /><published>2026-10-21T00:00:00+00:00</published><updated>2026-10-21T00:00:00+00:00</updated><id>https://penantumbra.github.io/vulkancts</id><content type="html" xml:base="https://penantumbra.github.io/vulkancts/"><![CDATA[<blockquote>
  <p>A quick reference for running dEQP-VK Ray Tracing tests on Windows / Android.</p>
</blockquote>

<h2 id="1-ray-tracing-test-groups">1. Ray Tracing Test Groups</h2>

<p>Vulkan CTS has two main ray tracing test groups:</p>

<table>
  <thead>
    <tr>
      <th>Test Group</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">dEQP-VK.ray_tracing_pipeline.*</code></td>
      <td>Ray Tracing Pipeline tests</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">dEQP-VK.ray_query.*</code></td>
      <td>Ray Query (inline ray tracing) tests</td>
    </tr>
  </tbody>
</table>

<blockquote>
  <p>These correspond to the two ray tracing models: the pipeline model (raygen/hit/miss + SBT) and the inline model (<code class="language-plaintext highlighter-rouge">rayQueryEXT</code> inside a shader).</p>
</blockquote>

<hr />

<h2 id="2-running-on-windows">2. Running on Windows</h2>

<h3 id="21-enter-the-test-resource-directory">2.1 Enter the test resource directory</h3>

<p>Tests must run from their resource directory (relative paths depend on it):</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">cd</span><span class="w"> </span><span class="err">&lt;</span><span class="nx">vulkancts</span><span class="err">&gt;</span><span class="nx">\build\external\vulkancts\modules\vulkan</span><span class="w">
</span></code></pre></div></div>

<h3 id="22-run-a-single-case-first-to-verify-the-environment">2.2 Run a single case first to verify the environment</h3>

<p>The full group is huge — <strong>always run a single case first</strong> to confirm the setup works:</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">.</span><span class="n">\Release\deqp-vk.exe</span><span class="w"> </span><span class="se">`
</span><span class="w">  </span><span class="nt">--deqp-case</span><span class="o">=</span><span class="n">dEQP-VK.ray_tracing_pipeline.trace_rays_cmds.direct.11_13_1</span><span class="w"> </span><span class="se">`
</span><span class="w">  </span><span class="nt">--deqp-log-filename</span><span class="o">=</span><span class="n">rt-single.qpa</span><span class="w">
</span></code></pre></div></div>

<h3 id="23-run-the-full-groups">2.3 Run the full groups</h3>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Full Ray Tracing Pipeline group</span><span class="w">
</span><span class="o">.</span><span class="n">\Release\deqp-vk.exe</span><span class="w"> </span><span class="s2">"--deqp-case=dEQP-VK.ray_tracing_pipeline.*"</span><span class="w"> </span><span class="se">`
</span><span class="w">  </span><span class="nt">--deqp-log-filename</span><span class="o">=</span><span class="n">raytracing.qpa</span><span class="w">

</span><span class="c"># Full Ray Query group</span><span class="w">
</span><span class="o">.</span><span class="n">\Release\deqp-vk.exe</span><span class="w"> </span><span class="s2">"--deqp-case=dEQP-VK.ray_query.*"</span><span class="w"> </span><span class="se">`
</span><span class="w">  </span><span class="nt">--deqp-log-filename</span><span class="o">=</span><span class="n">rayquery.qpa</span><span class="w">
</span></code></pre></div></div>

<p>Results show in the console in real time; detailed logs go to the <code class="language-plaintext highlighter-rouge">.qpa</code> file in the current directory.</p>

<hr />

<h2 id="3-running-on-android">3. Running on Android</h2>

<h3 id="31-install-the-apk-from-the-repo-root">3.1 Install the APK (from the repo root)</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>adb <span class="nb">install</span> <span class="nt">-r</span> build/android/package/dEQP.apk
</code></pre></div></div>

<h3 id="32-enter-the-device-shell-and-launch-the-test">3.2 Enter the device shell and launch the test</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>adb shell

<span class="c"># Make sure no stale process is running</span>
am force-stop com.drawelements.deqp

<span class="c"># Launch the test (ray_query full group as an example)</span>
am start <span class="nt">-n</span> com.drawelements.deqp/android.app.NativeActivity <span class="nt">-e</span> cmdLine <span class="se">\</span>
  <span class="s2">"deqp --deqp-case=dEQP-VK.ray_query.* </span><span class="se">\</span><span class="s2">
  --deqp-log-filename=/sdcard/Documents/raytracing.qpa </span><span class="se">\</span><span class="s2">
  --deqp-log-images=disable </span><span class="se">\</span><span class="s2">
  --deqp-log-shader-sources=disable"</span>

<span class="nb">exit</span>
</code></pre></div></div>

<blockquote>
  <p><code class="language-plaintext highlighter-rouge">--deqp-log-images=disable</code> and <code class="language-plaintext highlighter-rouge">--deqp-log-shader-sources=disable</code> reduce log size — recommended for full runs.</p>
</blockquote>

<h3 id="33-monitor-progress">3.3 Monitor progress</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>adb logcat <span class="nt">-s</span> dEQP
</code></pre></div></div>

<h3 id="34-pull-the-log-after-ctrlc-to-exit-logcat">3.4 Pull the log (after Ctrl+C to exit logcat)</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>adb pull /sdcard/Documents/raytracing.qpa <span class="nb">.</span>
</code></pre></div></div>

<p>On Android you can also swap the filter for a single case or another group (e.g. <code class="language-plaintext highlighter-rouge">dEQP-VK.ray_tracing_pipeline.*</code>).</p>

<hr />

<h2 id="4-common-command-line-options">4. Common Command-Line Options</h2>

<table>
  <thead>
    <tr>
      <th>Option</th>
      <th>Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--deqp-case=&lt;pattern&gt;</code></td>
      <td>Select cases, supports <code class="language-plaintext highlighter-rouge">*</code> wildcard</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--deqp-log-filename=&lt;file&gt;</code></td>
      <td>Set <code class="language-plaintext highlighter-rouge">.qpa</code> log output path</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--deqp-log-images=disable</code></td>
      <td>Disable image logging (smaller logs)</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--deqp-log-shader-sources=disable</code></td>
      <td>Disable shader source logging</td>
    </tr>
  </tbody>
</table>

<hr />

<h2 id="5-reading-results-notsupported--fail">5. Reading Results: NotSupported ≠ Fail</h2>

<p>This is the most commonly misread point:</p>

<ul>
  <li>If the device/driver <strong>does not support an extension or feature</strong> a case requires, the result is usually <strong><code class="language-plaintext highlighter-rouge">NotSupported</code></strong>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">NotSupported</code> does NOT mean the test failed</strong> — it means the environment can’t run that case.</li>
  <li>The actual failure state is <strong><code class="language-plaintext highlighter-rouge">Fail</code></strong> (plus <code class="language-plaintext highlighter-rouge">QualityWarning</code> / <code class="language-plaintext highlighter-rouge">CompatibilityWarning</code>, which deserve attention).</li>
</ul>

<p>Common result states:</p>

<table>
  <thead>
    <tr>
      <th>State</th>
      <th>Meaning</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Pass</code></td>
      <td>Passed</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Fail</code></td>
      <td>Failed (needs investigation)</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">NotSupported</code></td>
      <td>Feature/extension unsupported — not a failure</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">QualityWarning</code></td>
      <td>Passed, but with a quality warning</td>
    </tr>
  </tbody>
</table>]]></content><author><name></name></author><category term="ideas" /><summary type="html"><![CDATA[A quick reference for running dEQP-VK Ray Tracing tests on Windows / Android. 1. Ray Tracing Test Groups Vulkan CTS has two main ray tracing test groups: Test Group Description dEQP-VK.ray_tracing_pipeline.* Ray Tracing Pipeline tests dEQP-VK.ray_query.* Ray Query (inline ray tracing) tests These correspond to the two ray tracing models: the pipeline model (raygen/hit/miss + SBT) and the inline model (rayQueryEXT inside a shader). 2. Running on Windows 2.1 Enter the test resource directory Tests must run from their resource directory (relative paths depend on it): cd &lt;vulkancts&gt;\build\external\vulkancts\modules\vulkan 2.2 Run a single case first to verify the environment The full group is huge — always run a single case first to confirm the setup works: .\Release\deqp-vk.exe ` --deqp-case=dEQP-VK.ray_tracing_pipeline.trace_rays_cmds.direct.11_13_1 ` --deqp-log-filename=rt-single.qpa 2.3 Run the full groups # Full Ray Tracing Pipeline group .\Release\deqp-vk.exe "--deqp-case=dEQP-VK.ray_tracing_pipeline.*" ` --deqp-log-filename=raytracing.qpa # Full Ray Query group .\Release\deqp-vk.exe "--deqp-case=dEQP-VK.ray_query.*" ` --deqp-log-filename=rayquery.qpa Results show in the console in real time; detailed logs go to the .qpa file in the current directory. 3. Running on Android 3.1 Install the APK (from the repo root) adb install -r build/android/package/dEQP.apk 3.2 Enter the device shell and launch the test adb shell # Make sure no stale process is running am force-stop com.drawelements.deqp # Launch the test (ray_query full group as an example) am start -n com.drawelements.deqp/android.app.NativeActivity -e cmdLine \ "deqp --deqp-case=dEQP-VK.ray_query.* \ --deqp-log-filename=/sdcard/Documents/raytracing.qpa \ --deqp-log-images=disable \ --deqp-log-shader-sources=disable" exit --deqp-log-images=disable and --deqp-log-shader-sources=disable reduce log size — recommended for full runs. 3.3 Monitor progress adb logcat -s dEQP 3.4 Pull the log (after Ctrl+C to exit logcat) adb pull /sdcard/Documents/raytracing.qpa . On Android you can also swap the filter for a single case or another group (e.g. dEQP-VK.ray_tracing_pipeline.*). 4. Common Command-Line Options Option Purpose --deqp-case=&lt;pattern&gt; Select cases, supports * wildcard --deqp-log-filename=&lt;file&gt; Set .qpa log output path --deqp-log-images=disable Disable image logging (smaller logs) --deqp-log-shader-sources=disable Disable shader source logging 5. Reading Results: NotSupported ≠ Fail This is the most commonly misread point: If the device/driver does not support an extension or feature a case requires, the result is usually NotSupported. NotSupported does NOT mean the test failed — it means the environment can’t run that case. The actual failure state is Fail (plus QualityWarning / CompatibilityWarning, which deserve attention). Common result states: State Meaning Pass Passed Fail Failed (needs investigation) NotSupported Feature/extension unsupported — not a failure QualityWarning Passed, but with a quality warning]]></summary></entry><entry><title type="html">Vulkan Ray Tracing Acceleration Structure</title><link href="https://penantumbra.github.io/as/" rel="alternate" type="text/html" title="Vulkan Ray Tracing Acceleration Structure" /><published>2026-10-13T00:00:00+00:00</published><updated>2026-10-13T00:00:00+00:00</updated><id>https://penantumbra.github.io/as</id><content type="html" xml:base="https://penantumbra.github.io/as/"><![CDATA[<p>加速结构（AS）通过空间层次组织场景，减少射线求交测试。Vulkan 将其分为两层：<strong>BLAS 组织几何，TLAS 组织实例</strong>。</p>

<p>示例使用 Vulkan-Hpp，省略初始化和错误检查。<code class="language-plaintext highlighter-rouge">createBuffer()</code>、<code class="language-plaintext highlighter-rouge">destroyBuffer()</code>、<code class="language-plaintext highlighter-rouge">submitAndWait()</code> 为应用封装；buffer 封装负责分配、绑定和对齐，提供 <code class="language-plaintext highlighter-rouge">.buffer</code> 与 <code class="language-plaintext highlighter-rouge">.address</code>。</p>

<p>使用 C++20 designated initializer，按成员声明顺序初始化。首次包含 Vulkan-Hpp 前关闭构造函数：</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#define VULKAN_HPP_NO_CONSTRUCTORS
#include</span> <span class="cpf">&lt;vulkan/vulkan.hpp&gt;</span><span class="cp">
</span></code></pre></div></div>

<h2 id="1-blas-与-tlas">1. BLAS 与 TLAS</h2>

<p>一个 BLAS 可以包含多个 geometry。TLAS 的每个 instance 引用一个 BLAS，并指定变换、可见性 mask 等信息。</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>TLAS
├── instance 0：BLAS A，变换 T0
├── instance 1：BLAS A，变换 T1
└── instance 2：BLAS B，变换 T2
</code></pre></div></div>

<p>多个实例可以共享 BLAS。只改变物体变换时处理 TLAS；几何形状变化时处理对应 BLAS。下面以三角形为例。</p>

<h2 id="2-构建-blas">2. 构建 BLAS</h2>

<p>流程：<strong>描述几何 → 查询大小 → 分配资源 → 执行构建</strong>。</p>

<h3 id="描述输入几何">描述输入几何</h3>

<p><code class="language-plaintext highlighter-rouge">vk::AccelerationStructureGeometryKHR</code> 描述几何类型，以及顶点、索引的地址和格式。</p>

<p><img src="https://docs.vulkan.org/tutorial/latest/_images/images/38_TASK02_blas_structures.png" alt="三角形几何的输入数据与描述结构" /></p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureGeometryTrianglesDataKHR</span> <span class="n">triangles</span><span class="p">{</span>
    <span class="p">.</span><span class="n">vertexFormat</span>  <span class="o">=</span> <span class="n">desc</span><span class="p">.</span><span class="n">vertex_format</span><span class="p">,</span>
    <span class="p">.</span><span class="n">vertexData</span>    <span class="o">=</span> <span class="p">{.</span><span class="n">deviceAddress</span> <span class="o">=</span> <span class="n">vertex_buffer</span><span class="p">.</span><span class="n">address</span> <span class="o">+</span> <span class="n">vertex_offset</span><span class="p">},</span>
    <span class="p">.</span><span class="n">vertexStride</span>  <span class="o">=</span> <span class="n">desc</span><span class="p">.</span><span class="n">vertex_stride</span><span class="p">,</span>
    <span class="p">.</span><span class="n">maxVertex</span>     <span class="o">=</span> <span class="n">vertex_count</span> <span class="o">-</span> <span class="mi">1</span><span class="p">,</span>
    <span class="p">.</span><span class="n">indexType</span>     <span class="o">=</span> <span class="n">desc</span><span class="p">.</span><span class="n">index_type</span><span class="p">,</span>
    <span class="p">.</span><span class="n">indexData</span>     <span class="o">=</span> <span class="p">{.</span><span class="n">deviceAddress</span> <span class="o">=</span> <span class="n">index_buffer</span><span class="p">.</span><span class="n">address</span> <span class="o">+</span> <span class="n">index_offset</span><span class="p">},</span>
    <span class="p">.</span><span class="n">transformData</span> <span class="o">=</span> <span class="p">{.</span><span class="n">deviceAddress</span> <span class="o">=</span> <span class="mi">0</span><span class="p">},</span>  <span class="c1">// 不提供额外几何变换，使用单位变换</span>
<span class="p">};</span>

<span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureGeometryKHR</span> <span class="n">geometry</span><span class="p">{</span>
    <span class="p">.</span><span class="n">geometryType</span> <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">GeometryTypeKHR</span><span class="o">::</span><span class="n">eTriangles</span><span class="p">,</span>
    <span class="p">.</span><span class="n">geometry</span>     <span class="o">=</span> <span class="p">{.</span><span class="n">triangles</span> <span class="o">=</span> <span class="n">triangles</span><span class="p">},</span>
    <span class="p">.</span><span class="n">flags</span>        <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">GeometryFlagBitsKHR</span><span class="o">::</span><span class="n">eOpaque</span><span class="p">,</span>
<span class="p">};</span>

<span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureBuildRangeInfoKHR</span> <span class="n">range</span><span class="p">{</span>
    <span class="p">.</span><span class="n">primitiveCount</span> <span class="o">=</span> <span class="n">index_count</span> <span class="o">/</span> <span class="mi">3</span><span class="p">,</span>
<span class="p">};</span>
</code></pre></div></div>

<p>示例假设索引三角形列表非空，地址已包含数据偏移。<code class="language-plaintext highlighter-rouge">maxVertex</code> 是最大顶点索引，<code class="language-plaintext highlighter-rouge">vertexStride</code> 是顶点步长（字节）。</p>

<p>输入 buffer 需要 <code class="language-plaintext highlighter-rouge">eAccelerationStructureBuildInputReadOnlyKHR</code>、<code class="language-plaintext highlighter-rouge">eShaderDeviceAddress</code> 及设备地址分配支持。</p>

<p><code class="language-plaintext highlighter-rouge">eOpaque</code> 用于不透明几何；使用 any-hit 做 alpha test 时，需要检查几何、实例和射线的不透明性标志。</p>

<h3 id="查询构建大小">查询构建大小</h3>

<p><code class="language-plaintext highlighter-rouge">build_info</code> 指定 AS 类型、构建模式、优化标志和输入几何。</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureBuildGeometryInfoKHR</span> <span class="n">build_info</span><span class="p">{</span>
    <span class="p">.</span><span class="n">type</span>          <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureTypeKHR</span><span class="o">::</span><span class="n">eBottomLevel</span><span class="p">,</span>
    <span class="p">.</span><span class="n">flags</span>         <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">BuildAccelerationStructureFlagBitsKHR</span><span class="o">::</span><span class="n">ePreferFastTrace</span><span class="p">,</span>
    <span class="p">.</span><span class="n">mode</span>          <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">BuildAccelerationStructureModeKHR</span><span class="o">::</span><span class="n">eBuild</span><span class="p">,</span>
    <span class="p">.</span><span class="n">geometryCount</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
    <span class="p">.</span><span class="n">pGeometries</span>   <span class="o">=</span> <span class="o">&amp;</span><span class="n">geometry</span><span class="p">,</span>
<span class="p">};</span>

<span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureBuildSizesInfoKHR</span> <span class="n">sizes_info</span><span class="p">{};</span>
<span class="k">const</span> <span class="kt">uint32_t</span> <span class="n">max_primitive_count</span> <span class="o">=</span> <span class="n">range</span><span class="p">.</span><span class="n">primitiveCount</span><span class="p">;</span>
<span class="n">device</span><span class="p">.</span><span class="n">getAccelerationStructureBuildSizesKHR</span><span class="p">(</span>
    <span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureBuildTypeKHR</span><span class="o">::</span><span class="n">eDevice</span><span class="p">,</span>
    <span class="o">&amp;</span><span class="n">build_info</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">max_primitive_count</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">sizes_info</span><span class="p">);</span>
</code></pre></div></div>

<p>多个 geometry 需要对应的 geometry、range 和最大图元数量数组。<code class="language-plaintext highlighter-rouge">geometryCount</code> 是几何数量，不是 buffer 数量。</p>

<p>查询返回三种大小：</p>

<table>
  <thead>
    <tr>
      <th>字段</th>
      <th>用途</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">accelerationStructureSize</code></td>
      <td>AS 构建结果所需的存储空间</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">buildScratchSize</code></td>
      <td>BUILD 操作所需的临时工作空间</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">updateScratchSize</code></td>
      <td>UPDATE 操作所需的临时工作空间</td>
    </tr>
  </tbody>
</table>

<p>AS 内部布局由驱动管理。常见的<a href="https://docs.vulkan.org/refpages/latest/refpages/source/VkBuildAccelerationStructureFlagBitsKHR.html">构建标志</a>选择如下：</p>

<table>
  <thead>
    <tr>
      <th>类型</th>
      <th>常见选择</th>
      <th>原因</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>静态 BLAS</td>
      <td><code class="language-plaintext highlighter-rouge">ePreferFastTrace</code></td>
      <td>构建少、遍历多</td>
    </tr>
    <tr>
      <td>动态 BLAS</td>
      <td><code class="language-plaintext highlighter-rouge">ePreferFastBuild</code></td>
      <td>几何频繁变化</td>
    </tr>
    <tr>
      <td>TLAS</td>
      <td><code class="language-plaintext highlighter-rouge">ePreferFastBuild</code></td>
      <td>实例通常频繁变化</td>
    </tr>
  </tbody>
</table>

<p>实际选择取决于构建与遍历的总耗时。UPDATE 和 COMPACT 分别要求初始构建加入 <code class="language-plaintext highlighter-rouge">eAllowUpdate</code>、<code class="language-plaintext highlighter-rouge">eAllowCompaction</code>。</p>

<h3 id="分配存储">分配存储</h3>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">auto</span> <span class="n">as_buffer</span> <span class="o">=</span> <span class="n">createBuffer</span><span class="p">(</span>
    <span class="n">sizes_info</span><span class="p">.</span><span class="n">accelerationStructureSize</span><span class="p">,</span>
    <span class="n">vk</span><span class="o">::</span><span class="n">BufferUsageFlagBits</span><span class="o">::</span><span class="n">eAccelerationStructureStorageKHR</span> <span class="o">|</span>
        <span class="n">vk</span><span class="o">::</span><span class="n">BufferUsageFlagBits</span><span class="o">::</span><span class="n">eShaderDeviceAddress</span><span class="p">);</span>

<span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureCreateInfoKHR</span> <span class="n">create_info</span><span class="p">{</span>
    <span class="p">.</span><span class="n">buffer</span> <span class="o">=</span> <span class="n">as_buffer</span><span class="p">.</span><span class="n">buffer</span><span class="p">,</span>
    <span class="p">.</span><span class="n">offset</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span>
    <span class="p">.</span><span class="n">size</span>   <span class="o">=</span> <span class="n">sizes_info</span><span class="p">.</span><span class="n">accelerationStructureSize</span><span class="p">,</span>
    <span class="p">.</span><span class="n">type</span>   <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureTypeKHR</span><span class="o">::</span><span class="n">eBottomLevel</span><span class="p">,</span>
<span class="p">};</span>
<span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureKHR</span> <span class="n">blas</span> <span class="o">=</span>
    <span class="n">device</span><span class="p">.</span><span class="n">createAccelerationStructureKHR</span><span class="p">(</span><span class="n">create_info</span><span class="p">);</span>

<span class="k">const</span> <span class="k">auto</span> <span class="n">scratch_alignment</span> <span class="o">=</span>
    <span class="n">as_properties</span><span class="p">.</span><span class="n">minAccelerationStructureScratchOffsetAlignment</span><span class="p">;</span>
<span class="k">auto</span> <span class="n">scratch_buffer</span> <span class="o">=</span> <span class="n">createBuffer</span><span class="p">(</span>
    <span class="n">sizes_info</span><span class="p">.</span><span class="n">buildScratchSize</span><span class="p">,</span>
    <span class="n">vk</span><span class="o">::</span><span class="n">BufferUsageFlagBits</span><span class="o">::</span><span class="n">eStorageBuffer</span> <span class="o">|</span>
        <span class="n">vk</span><span class="o">::</span><span class="n">BufferUsageFlagBits</span><span class="o">::</span><span class="n">eShaderDeviceAddress</span><span class="p">,</span>
    <span class="n">scratch_alignment</span><span class="p">);</span>
</code></pre></div></div>

<p><strong>创建 AS 对象不等于完成构建。</strong> AS buffer 保存结果，scratch 提供临时空间。最终 scratch 地址必须对齐；手动偏移地址时，要为偏移后的完整区间预留空间。</p>

<h3 id="执行构建">执行构建</h3>

<p><img src="https://docs.vulkan.org/tutorial/latest/_images/images/38_TASK02_blas_build.png" alt="BLAS 构建时的输入、scratch 与结果存储" /></p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">build_info</span><span class="p">.</span><span class="n">dstAccelerationStructure</span> <span class="o">=</span> <span class="n">blas</span><span class="p">;</span>
<span class="n">build_info</span><span class="p">.</span><span class="n">scratchData</span><span class="p">.</span><span class="n">deviceAddress</span> <span class="o">=</span> <span class="n">scratch_buffer</span><span class="p">.</span><span class="n">address</span><span class="p">;</span>

<span class="k">const</span> <span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureBuildRangeInfoKHR</span><span class="o">*</span> <span class="n">ranges</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="o">&amp;</span><span class="n">range</span><span class="p">};</span>
<span class="c1">// 在记录构建命令前，建立输入数据写入 -&gt; AS 构建读取的依赖。</span>
<span class="n">command_buffer</span><span class="p">.</span><span class="n">buildAccelerationStructuresKHR</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">build_info</span><span class="p">,</span> <span class="n">ranges</span><span class="p">);</span>

<span class="c1">// 后续使用 AS 前，还需要相应的构建写入 -&gt; 读取依赖。</span>
<span class="n">submitAndWait</span><span class="p">(</span><span class="n">command_buffer</span><span class="p">);</span>
<span class="n">destroyBuffer</span><span class="p">(</span><span class="n">scratch_buffer</span><span class="p">);</span>
</code></pre></div></div>

<p>命令提交并完成后才能回收 scratch。示例直接等待，实际渲染器可用 fence 或 timeline semaphore 延迟回收。</p>

<h2 id="3-构建-tlas">3. 构建 TLAS</h2>

<p>TLAS 的构建流程与 BLAS 相同，输入换成 <code class="language-plaintext highlighter-rouge">vk::AccelerationStructureInstanceKHR</code> 数组。</p>

<p><img src="https://docs.vulkan.org/tutorial/latest/_images/images/38_TASK03_tlas_structures.png" alt="TLAS 实例、变换矩阵与 BLAS 引用" /></p>

<h3 id="描述实例">描述实例</h3>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureInstanceKHR</span> <span class="n">instance</span><span class="p">{</span>
    <span class="p">.</span><span class="n">transform</span>                              <span class="o">=</span> <span class="n">desc</span><span class="p">.</span><span class="n">transform_matrix</span><span class="p">,</span>
    <span class="p">.</span><span class="n">instanceCustomIndex</span>                    <span class="o">=</span> <span class="n">desc</span><span class="p">.</span><span class="n">mesh_index</span><span class="p">,</span>
    <span class="p">.</span><span class="n">mask</span>                                   <span class="o">=</span> <span class="mh">0xFF</span><span class="p">,</span>
    <span class="p">.</span><span class="n">instanceShaderBindingTableRecordOffset</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span>
    <span class="p">.</span><span class="n">flags</span> <span class="o">=</span> <span class="k">static_cast</span><span class="o">&lt;</span><span class="n">VkGeometryInstanceFlagsKHR</span><span class="o">&gt;</span><span class="p">(</span>
        <span class="n">vk</span><span class="o">::</span><span class="n">GeometryInstanceFlagBitsKHR</span><span class="o">::</span><span class="n">eTriangleFacingCullDisable</span><span class="p">),</span>
    <span class="p">.</span><span class="n">accelerationStructureReference</span> <span class="o">=</span>
        <span class="n">device</span><span class="p">.</span><span class="n">getAccelerationStructureDeviceAddressKHR</span><span class="p">(</span>
            <span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureDeviceAddressInfoKHR</span><span class="p">{</span>
                <span class="p">.</span><span class="n">accelerationStructure</span> <span class="o">=</span> <span class="n">blas</span><span class="p">,</span>
            <span class="p">}),</span>
<span class="p">};</span>
</code></pre></div></div>

<table>
  <thead>
    <tr>
      <th>字段</th>
      <th>含义</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transform</code></td>
      <td>BLAS 局部坐标到场景坐标的 3×4 矩阵，注意存储顺序</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">instanceCustomIndex</code></td>
      <td>应用定义的 24 位索引</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">mask</code></td>
      <td>与射线的 cull mask 按位与，结果为 0 时跳过实例</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">instanceShaderBindingTableRecordOffset</code></td>
      <td>命中组 SBT 索引计算中的记录偏移</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">accelerationStructureReference</code></td>
      <td>BLAS 的 AS 地址，不是 buffer 地址</td>
    </tr>
  </tbody>
</table>

<p>将实例上传到具备 <code class="language-plaintext highlighter-rouge">eAccelerationStructureBuildInputReadOnlyKHR</code> 和 <code class="language-plaintext highlighter-rouge">eShaderDeviceAddress</code> 用途的 buffer，并完成上传同步。</p>

<h3 id="描述实例数组并构建">描述实例数组并构建</h3>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureGeometryKHR</span> <span class="n">instances_geometry</span><span class="p">{</span>
    <span class="p">.</span><span class="n">geometryType</span> <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">GeometryTypeKHR</span><span class="o">::</span><span class="n">eInstances</span><span class="p">,</span>
    <span class="p">.</span><span class="n">geometry</span> <span class="o">=</span> <span class="p">{</span>
        <span class="p">.</span><span class="n">instances</span> <span class="o">=</span> <span class="p">{</span>
            <span class="p">.</span><span class="n">arrayOfPointers</span> <span class="o">=</span> <span class="nb">false</span><span class="p">,</span>
            <span class="p">.</span><span class="n">data</span> <span class="o">=</span> <span class="p">{.</span><span class="n">deviceAddress</span> <span class="o">=</span> <span class="n">instances_buffer</span><span class="p">.</span><span class="n">address</span><span class="p">},</span>
        <span class="p">},</span>
    <span class="p">},</span>
<span class="p">};</span>

<span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureBuildRangeInfoKHR</span> <span class="n">tlas_range</span><span class="p">{</span>
    <span class="p">.</span><span class="n">primitiveCount</span> <span class="o">=</span> <span class="n">instance_count</span><span class="p">,</span>
<span class="p">};</span>

<span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureBuildGeometryInfoKHR</span> <span class="n">tlas_build_info</span><span class="p">{</span>
    <span class="p">.</span><span class="n">type</span>          <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureTypeKHR</span><span class="o">::</span><span class="n">eTopLevel</span><span class="p">,</span>
    <span class="p">.</span><span class="n">flags</span>         <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">BuildAccelerationStructureFlagBitsKHR</span><span class="o">::</span><span class="n">ePreferFastBuild</span><span class="p">,</span>
    <span class="p">.</span><span class="n">mode</span>          <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">BuildAccelerationStructureModeKHR</span><span class="o">::</span><span class="n">eBuild</span><span class="p">,</span>
    <span class="p">.</span><span class="n">geometryCount</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
    <span class="p">.</span><span class="n">pGeometries</span>   <span class="o">=</span> <span class="o">&amp;</span><span class="n">instances_geometry</span><span class="p">,</span>
<span class="p">};</span>
</code></pre></div></div>

<p>TLAS 的 <code class="language-plaintext highlighter-rouge">geometryCount = 1</code>，<code class="language-plaintext highlighter-rouge">primitiveCount</code> 是实例数量，<code class="language-plaintext highlighter-rouge">arrayOfPointers = false</code> 表示连续数组。随后查询大小、分配 TLAS 和 scratch，再执行构建。</p>

<p>BLAS 构建与引用它的 TLAS 构建必须建立依赖，不能放在同一次 build 调用中。<a href="https://docs.vulkan.org/refpages/latest/refpages/source/vkCmdBuildAccelerationStructuresKHR.html">构建命令规则</a></p>

<h2 id="4-update-与重建">4. UPDATE 与重建</h2>

<p>初始构建包含 <code class="language-plaintext highlighter-rouge">eAllowUpdate</code> 时，可在满足兼容条件的前提下执行 UPDATE。更新输入数据后，沿用原有 geometry、range 和构建参数：</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">build_info</span><span class="p">.</span><span class="n">mode</span> <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">BuildAccelerationStructureModeKHR</span><span class="o">::</span><span class="n">eUpdate</span><span class="p">;</span>
<span class="n">build_info</span><span class="p">.</span><span class="n">srcAccelerationStructure</span> <span class="o">=</span> <span class="n">blas</span><span class="p">;</span>
<span class="n">build_info</span><span class="p">.</span><span class="n">dstAccelerationStructure</span> <span class="o">=</span> <span class="n">blas</span><span class="p">;</span>  <span class="c1">// 原地更新</span>
<span class="n">build_info</span><span class="p">.</span><span class="n">scratchData</span><span class="p">.</span><span class="n">deviceAddress</span> <span class="o">=</span> <span class="n">update_scratch_address</span><span class="p">;</span>

<span class="k">const</span> <span class="n">vk</span><span class="o">::</span><span class="n">AccelerationStructureBuildRangeInfoKHR</span><span class="o">*</span> <span class="n">ranges</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="o">&amp;</span><span class="n">range</span><span class="p">};</span>
<span class="n">command_buffer</span><span class="p">.</span><span class="n">buildAccelerationStructuresKHR</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">build_info</span><span class="p">,</span> <span class="n">ranges</span><span class="p">);</span>
</code></pre></div></div>

<p>更新 scratch 仍需对齐，大小至少为 <code class="language-plaintext highlighter-rouge">updateScratchSize</code>。</p>

<table>
  <thead>
    <tr>
      <th>场景变化</th>
      <th>通常需要处理的层级</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>物体平移、旋转或缩放，几何不变</td>
      <td>更新或重建 TLAS，复用 BLAS</td>
    </tr>
    <tr>
      <td>顶点位置改变，三角形连接关系不变</td>
      <td>符合限制时 UPDATE BLAS；若实例包围范围变化，再更新或重建 TLAS</td>
    </tr>
    <tr>
      <td>三角形连接关系、图元数量或 geometry 数量改变</td>
      <td>重新 BUILD 对应 BLAS，并处理受影响的 TLAS</td>
    </tr>
    <tr>
      <td>实例数量改变</td>
      <td>重新 BUILD TLAS</td>
    </tr>
  </tbody>
</table>

<p>UPDATE 受格式、数量、拓扑和活动状态等<a href="https://docs.vulkan.org/spec/latest/chapters/accelstructures.html">兼容条件</a>限制。大幅形变可能降低遍历效率，应同时评估重建成本与 trace 性能。</p>

<h2 id="5-blas-压缩">5. BLAS 压缩</h2>

<p>初始构建包含 <code class="language-plaintext highlighter-rouge">eAllowCompaction</code> 后，可以查询压缩大小，再用 COMPACT copy 生成更紧凑的 BLAS：</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>构建 BLAS（ALLOW_COMPACTION）
    → 写入 compacted-size query
    → 等待并读取查询结果
    → 分配目标存储并创建新 BLAS
    → 记录 COMPACT copy
    → 完成复制并切换引用
    → 安全回收旧 BLAS 与旧存储
</code></pre></div></div>

<h3 id="查询压缩后的大小">查询压缩后的大小</h3>

<p>创建 <code class="language-plaintext highlighter-rouge">eAccelerationStructureCompactedSizeKHR</code> query pool，确保 BLAS 构建结果可见后查询：</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">command_buffer</span><span class="p">.</span><span class="n">resetQueryPool</span><span class="p">(</span><span class="n">compaction_query_pool</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">);</span>
<span class="n">command_buffer</span><span class="p">.</span><span class="n">writeAccelerationStructuresPropertiesKHR</span><span class="p">(</span>
    <span class="mi">1</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">blas</span><span class="p">,</span>
    <span class="n">vk</span><span class="o">::</span><span class="n">QueryType</span><span class="o">::</span><span class="n">eAccelerationStructureCompactedSizeKHR</span><span class="p">,</span>
    <span class="n">compaction_query_pool</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
<span class="n">submitAndWait</span><span class="p">(</span><span class="n">command_buffer</span><span class="p">);</span>

<span class="n">vk</span><span class="o">::</span><span class="n">DeviceSize</span> <span class="n">compacted_size</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">const</span> <span class="n">vk</span><span class="o">::</span><span class="n">Result</span> <span class="n">query_result</span> <span class="o">=</span> <span class="n">device</span><span class="p">.</span><span class="n">getQueryPoolResults</span><span class="p">(</span>
    <span class="n">compaction_query_pool</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span>
    <span class="k">sizeof</span><span class="p">(</span><span class="n">compacted_size</span><span class="p">),</span> <span class="o">&amp;</span><span class="n">compacted_size</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">compacted_size</span><span class="p">),</span>
    <span class="n">vk</span><span class="o">::</span><span class="n">QueryResultFlagBits</span><span class="o">::</span><span class="n">e64</span> <span class="o">|</span> <span class="n">vk</span><span class="o">::</span><span class="n">QueryResultFlagBits</span><span class="o">::</span><span class="n">eWait</span><span class="p">);</span>
</code></pre></div></div>

<p>检查查询结果，按 <code class="language-plaintext highlighter-rouge">compacted_size</code> 分配存储并创建 <code class="language-plaintext highlighter-rouge">compacted_blas</code>；收益不明显时可跳过压缩。</p>

<h3 id="复制并切换引用">复制并切换引用</h3>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">vk</span><span class="o">::</span><span class="n">CopyAccelerationStructureInfoKHR</span> <span class="n">copy_info</span><span class="p">{</span>
    <span class="p">.</span><span class="n">src</span>  <span class="o">=</span> <span class="n">blas</span><span class="p">,</span>
    <span class="p">.</span><span class="n">dst</span>  <span class="o">=</span> <span class="n">compacted_blas</span><span class="p">,</span>
    <span class="p">.</span><span class="n">mode</span> <span class="o">=</span> <span class="n">vk</span><span class="o">::</span><span class="n">CopyAccelerationStructureModeKHR</span><span class="o">::</span><span class="n">eCompact</span><span class="p">,</span>
<span class="p">};</span>
<span class="n">command_buffer</span><span class="p">.</span><span class="n">copyAccelerationStructureKHR</span><span class="p">(</span><span class="n">copy_info</span><span class="p">);</span>
<span class="n">submitAndWait</span><span class="p">(</span><span class="n">command_buffer</span><span class="p">);</span>
</code></pre></div></div>

<p>COMPACT 是 AS 专用复制操作，不能用普通 buffer copy 代替。<a href="https://docs.vulkan.org/refpages/latest/refpages/source/vkCmdCopyAccelerationStructureKHR.html">复制命令说明</a></p>

<p><strong>压缩后 BLAS 地址改变。</strong> 最好先压缩，再构建 TLAS；已有 TLAS 则需换用新地址并更新或重建。复制和旧 AS 的在途操作结束后，才能回收旧存储。压缩期间新旧存储同时存在，需考虑显存峰值。</p>

<h2 id="延伸阅读">延伸阅读</h2>

<ul>
  <li><a href="https://docs.vulkan.org/tutorial/latest/courses/18_Ray_tracing/02_Acceleration_structures.html">Vulkan 官方教程：Acceleration Structures</a>：BLAS/TLAS 的基础构建流程。</li>
  <li><a href="https://nvpro-samples.github.io/vk_raytracing_tutorial_KHR/concepts/acceleration-structures/">NVIDIA Vulkan Ray Tracing Tutorial：Acceleration Structures</a>：结合 sample 理解构建与资源管理。</li>
  <li><a href="https://github.com/nvpro-samples/nvpro_core2/blob/main/nvvk/acceleration_structures.hpp">nvpro_core2 acceleration_structures.hpp</a>：构建、批处理与压缩的 helper 接口。</li>
  <li><a href="https://github.com/NVIDIA-RTX/RTXMU">NVIDIA RTXMU</a>：面向光追加速结构的内存管理库。</li>
</ul>]]></content><author><name></name></author><category term="ideas" /><summary type="html"><![CDATA[加速结构（AS）通过空间层次组织场景，减少射线求交测试。Vulkan 将其分为两层：BLAS 组织几何，TLAS 组织实例。 示例使用 Vulkan-Hpp，省略初始化和错误检查。createBuffer()、destroyBuffer()、submitAndWait() 为应用封装；buffer 封装负责分配、绑定和对齐，提供 .buffer 与 .address。 使用 C++20 designated initializer，按成员声明顺序初始化。首次包含 Vulkan-Hpp 前关闭构造函数： #define VULKAN_HPP_NO_CONSTRUCTORS #include &lt;vulkan/vulkan.hpp&gt; 1. BLAS 与 TLAS 一个 BLAS 可以包含多个 geometry。TLAS 的每个 instance 引用一个 BLAS，并指定变换、可见性 mask 等信息。 TLAS ├── instance 0：BLAS A，变换 T0 ├── instance 1：BLAS A，变换 T1 └── instance 2：BLAS B，变换 T2 多个实例可以共享 BLAS。只改变物体变换时处理 TLAS；几何形状变化时处理对应 BLAS。下面以三角形为例。 2. 构建 BLAS 流程：描述几何 → 查询大小 → 分配资源 → 执行构建。 描述输入几何 vk::AccelerationStructureGeometryKHR 描述几何类型，以及顶点、索引的地址和格式。 vk::AccelerationStructureGeometryTrianglesDataKHR triangles{ .vertexFormat = desc.vertex_format, .vertexData = {.deviceAddress = vertex_buffer.address + vertex_offset}, .vertexStride = desc.vertex_stride, .maxVertex = vertex_count - 1, .indexType = desc.index_type, .indexData = {.deviceAddress = index_buffer.address + index_offset}, .transformData = {.deviceAddress = 0}, // 不提供额外几何变换，使用单位变换 }; vk::AccelerationStructureGeometryKHR geometry{ .geometryType = vk::GeometryTypeKHR::eTriangles, .geometry = {.triangles = triangles}, .flags = vk::GeometryFlagBitsKHR::eOpaque, }; vk::AccelerationStructureBuildRangeInfoKHR range{ .primitiveCount = index_count / 3, }; 示例假设索引三角形列表非空，地址已包含数据偏移。maxVertex 是最大顶点索引，vertexStride 是顶点步长（字节）。 输入 buffer 需要 eAccelerationStructureBuildInputReadOnlyKHR、eShaderDeviceAddress 及设备地址分配支持。 eOpaque 用于不透明几何；使用 any-hit 做 alpha test 时，需要检查几何、实例和射线的不透明性标志。 查询构建大小 build_info 指定 AS 类型、构建模式、优化标志和输入几何。 vk::AccelerationStructureBuildGeometryInfoKHR build_info{ .type = vk::AccelerationStructureTypeKHR::eBottomLevel, .flags = vk::BuildAccelerationStructureFlagBitsKHR::ePreferFastTrace, .mode = vk::BuildAccelerationStructureModeKHR::eBuild, .geometryCount = 1, .pGeometries = &amp;geometry, }; vk::AccelerationStructureBuildSizesInfoKHR sizes_info{}; const uint32_t max_primitive_count = range.primitiveCount; device.getAccelerationStructureBuildSizesKHR( vk::AccelerationStructureBuildTypeKHR::eDevice, &amp;build_info, &amp;max_primitive_count, &amp;sizes_info); 多个 geometry 需要对应的 geometry、range 和最大图元数量数组。geometryCount 是几何数量，不是 buffer 数量。 查询返回三种大小： 字段 用途 accelerationStructureSize AS 构建结果所需的存储空间 buildScratchSize BUILD 操作所需的临时工作空间 updateScratchSize UPDATE 操作所需的临时工作空间 AS 内部布局由驱动管理。常见的构建标志选择如下： 类型 常见选择 原因 静态 BLAS ePreferFastTrace 构建少、遍历多 动态 BLAS ePreferFastBuild 几何频繁变化 TLAS ePreferFastBuild 实例通常频繁变化 实际选择取决于构建与遍历的总耗时。UPDATE 和 COMPACT 分别要求初始构建加入 eAllowUpdate、eAllowCompaction。 分配存储 auto as_buffer = createBuffer( sizes_info.accelerationStructureSize, vk::BufferUsageFlagBits::eAccelerationStructureStorageKHR | vk::BufferUsageFlagBits::eShaderDeviceAddress); vk::AccelerationStructureCreateInfoKHR create_info{ .buffer = as_buffer.buffer, .offset = 0, .size = sizes_info.accelerationStructureSize, .type = vk::AccelerationStructureTypeKHR::eBottomLevel, }; vk::AccelerationStructureKHR blas = device.createAccelerationStructureKHR(create_info); const auto scratch_alignment = as_properties.minAccelerationStructureScratchOffsetAlignment; auto scratch_buffer = createBuffer( sizes_info.buildScratchSize, vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eShaderDeviceAddress, scratch_alignment); 创建 AS 对象不等于完成构建。 AS buffer 保存结果，scratch 提供临时空间。最终 scratch 地址必须对齐；手动偏移地址时，要为偏移后的完整区间预留空间。 执行构建 build_info.dstAccelerationStructure = blas; build_info.scratchData.deviceAddress = scratch_buffer.address; const vk::AccelerationStructureBuildRangeInfoKHR* ranges[] = {&amp;range}; // 在记录构建命令前，建立输入数据写入 -&gt; AS 构建读取的依赖。 command_buffer.buildAccelerationStructuresKHR(1, &amp;build_info, ranges); // 后续使用 AS 前，还需要相应的构建写入 -&gt; 读取依赖。 submitAndWait(command_buffer); destroyBuffer(scratch_buffer); 命令提交并完成后才能回收 scratch。示例直接等待，实际渲染器可用 fence 或 timeline semaphore 延迟回收。 3. 构建 TLAS TLAS 的构建流程与 BLAS 相同，输入换成 vk::AccelerationStructureInstanceKHR 数组。 描述实例 vk::AccelerationStructureInstanceKHR instance{ .transform = desc.transform_matrix, .instanceCustomIndex = desc.mesh_index, .mask = 0xFF, .instanceShaderBindingTableRecordOffset = 0, .flags = static_cast&lt;VkGeometryInstanceFlagsKHR&gt;( vk::GeometryInstanceFlagBitsKHR::eTriangleFacingCullDisable), .accelerationStructureReference = device.getAccelerationStructureDeviceAddressKHR( vk::AccelerationStructureDeviceAddressInfoKHR{ .accelerationStructure = blas, }), }; 字段 含义 transform BLAS 局部坐标到场景坐标的 3×4 矩阵，注意存储顺序 instanceCustomIndex 应用定义的 24 位索引 mask 与射线的 cull mask 按位与，结果为 0 时跳过实例 instanceShaderBindingTableRecordOffset 命中组 SBT 索引计算中的记录偏移 accelerationStructureReference BLAS 的 AS 地址，不是 buffer 地址 将实例上传到具备 eAccelerationStructureBuildInputReadOnlyKHR 和 eShaderDeviceAddress 用途的 buffer，并完成上传同步。 描述实例数组并构建 vk::AccelerationStructureGeometryKHR instances_geometry{ .geometryType = vk::GeometryTypeKHR::eInstances, .geometry = { .instances = { .arrayOfPointers = false, .data = {.deviceAddress = instances_buffer.address}, }, }, }; vk::AccelerationStructureBuildRangeInfoKHR tlas_range{ .primitiveCount = instance_count, }; vk::AccelerationStructureBuildGeometryInfoKHR tlas_build_info{ .type = vk::AccelerationStructureTypeKHR::eTopLevel, .flags = vk::BuildAccelerationStructureFlagBitsKHR::ePreferFastBuild, .mode = vk::BuildAccelerationStructureModeKHR::eBuild, .geometryCount = 1, .pGeometries = &amp;instances_geometry, }; TLAS 的 geometryCount = 1，primitiveCount 是实例数量，arrayOfPointers = false 表示连续数组。随后查询大小、分配 TLAS 和 scratch，再执行构建。 BLAS 构建与引用它的 TLAS 构建必须建立依赖，不能放在同一次 build 调用中。构建命令规则 4. UPDATE 与重建 初始构建包含 eAllowUpdate 时，可在满足兼容条件的前提下执行 UPDATE。更新输入数据后，沿用原有 geometry、range 和构建参数： build_info.mode = vk::BuildAccelerationStructureModeKHR::eUpdate; build_info.srcAccelerationStructure = blas; build_info.dstAccelerationStructure = blas; // 原地更新 build_info.scratchData.deviceAddress = update_scratch_address; const vk::AccelerationStructureBuildRangeInfoKHR* ranges[] = {&amp;range}; command_buffer.buildAccelerationStructuresKHR(1, &amp;build_info, ranges); 更新 scratch 仍需对齐，大小至少为 updateScratchSize。 场景变化 通常需要处理的层级 物体平移、旋转或缩放，几何不变 更新或重建 TLAS，复用 BLAS 顶点位置改变，三角形连接关系不变 符合限制时 UPDATE BLAS；若实例包围范围变化，再更新或重建 TLAS 三角形连接关系、图元数量或 geometry 数量改变 重新 BUILD 对应 BLAS，并处理受影响的 TLAS 实例数量改变 重新 BUILD TLAS UPDATE 受格式、数量、拓扑和活动状态等兼容条件限制。大幅形变可能降低遍历效率，应同时评估重建成本与 trace 性能。 5. BLAS 压缩 初始构建包含 eAllowCompaction 后，可以查询压缩大小，再用 COMPACT copy 生成更紧凑的 BLAS： 构建 BLAS（ALLOW_COMPACTION） → 写入 compacted-size query → 等待并读取查询结果 → 分配目标存储并创建新 BLAS → 记录 COMPACT copy → 完成复制并切换引用 → 安全回收旧 BLAS 与旧存储 查询压缩后的大小 创建 eAccelerationStructureCompactedSizeKHR query pool，确保 BLAS 构建结果可见后查询： command_buffer.resetQueryPool(compaction_query_pool, 0, 1); command_buffer.writeAccelerationStructuresPropertiesKHR( 1, &amp;blas, vk::QueryType::eAccelerationStructureCompactedSizeKHR, compaction_query_pool, 0); submitAndWait(command_buffer); vk::DeviceSize compacted_size = 0; const vk::Result query_result = device.getQueryPoolResults( compaction_query_pool, 0, 1, sizeof(compacted_size), &amp;compacted_size, sizeof(compacted_size), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); 检查查询结果，按 compacted_size 分配存储并创建 compacted_blas；收益不明显时可跳过压缩。 复制并切换引用 vk::CopyAccelerationStructureInfoKHR copy_info{ .src = blas, .dst = compacted_blas, .mode = vk::CopyAccelerationStructureModeKHR::eCompact, }; command_buffer.copyAccelerationStructureKHR(copy_info); submitAndWait(command_buffer); COMPACT 是 AS 专用复制操作，不能用普通 buffer copy 代替。复制命令说明 压缩后 BLAS 地址改变。 最好先压缩，再构建 TLAS；已有 TLAS 则需换用新地址并更新或重建。复制和旧 AS 的在途操作结束后，才能回收旧存储。压缩期间新旧存储同时存在，需考虑显存峰值。 延伸阅读 Vulkan 官方教程：Acceleration Structures：BLAS/TLAS 的基础构建流程。 NVIDIA Vulkan Ray Tracing Tutorial：Acceleration Structures：结合 sample 理解构建与资源管理。 nvpro_core2 acceleration_structures.hpp：构建、批处理与压缩的 helper 接口。 NVIDIA RTXMU：面向光追加速结构的内存管理库。]]></summary></entry><entry><title type="html">Tackling PSO Explosion in Vulkan: From Pipeline Caches to Shader Objects</title><link href="https://penantumbra.github.io/pso/" rel="alternate" type="text/html" title="Tackling PSO Explosion in Vulkan: From Pipeline Caches to Shader Objects" /><published>2026-08-12T00:00:00+00:00</published><updated>2026-08-12T00:00:00+00:00</updated><id>https://penantumbra.github.io/pso</id><content type="html" xml:base="https://penantumbra.github.io/pso/"><![CDATA[<p>A renderer may use only a modest number of shaders and still end up managing thousands of graphics pipelines. Different combinations of shader stages, vertex formats, attachment formats, and fixed-function state can quickly multiply into a large collection of pipeline state objects.</p>

<p>Vulkan provides several ways to manage this cost. Pipeline caches reuse previous compilation work, dynamic state reduces the number of required variants, graphics pipeline libraries share work across pipelines, and shader objects let applications bind shader stages independently.</p>

<p>Each approach addresses a different part of the problem.</p>

<h2 id="why-pso-counts-grow-so-quickly">Why PSO Counts Grow So Quickly</h2>

<p>In this article, a <em>PSO</em> refers to a graphics <code class="language-plaintext highlighter-rouge">VkPipeline</code>. For a typical vertex-and-fragment rendering path, it combines shader stages with vertex input, rasterization, depth/stencil, multisampling, and blending state.</p>

<p>A simplified model is:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Graphics pipeline =
    shader stages
  + fixed-function state
  + resource interface
  + rendering compatibility information
</code></pre></div></div>

<p>Suppose a renderer needs 30 vertex shader variants, 40 fragment shader variants, and 25 fixed-function state combinations. If every combination is used, it needs:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>30 × 40 × 25 = 30,000 graphics pipelines
</code></pre></div></div>

<p>This is an illustrative upper bound: real renderers usually use only a subset of all possible combinations. Nevertheless, the multiplicative growth is the central problem.</p>

<p>Creating these pipelines through <code class="language-plaintext highlighter-rouge">vkCreateGraphicsPipelines()</code> can involve translating SPIR-V into GPU machine code and optimizing it for the pipeline configuration. If that work happens on the rendering thread when a new combination first appears, it can cause a visible hitch. Compilation cost varies with the shader, driver, hardware, and available caches.</p>

<p>MJP’s <a href="https://therealmjp.github.io/posts/shader-permutations-part1/">The Shader Permutation Problem</a> provides a useful explanation of how rendering features and material systems generate these combinations.</p>

<h2 id="pipeline-precaching-and-pipeline-caches">Pipeline Precaching and Pipeline Caches</h2>

<p>A common response is to move compilation out of gameplay.</p>

<p>During development and testing, the application records the pipeline configurations it encounters. On the player’s machine, it creates those pipelines during startup or loading screens. This approach, usually called <em>PSO precaching</em>, trades additional loading time for fewer compilation stalls during rendering.</p>

<p>Vulkan’s <code class="language-plaintext highlighter-rouge">VkPipelineCache</code> complements this process. It allows the driver to reuse implementation-specific data across pipeline creation calls. Applications can retrieve that data with <code class="language-plaintext highlighter-rouge">vkGetPipelineCacheData()</code>, save it to disk, and provide compatible data on a later run.</p>

<p>These mechanisms serve different purposes:</p>

<table>
  <thead>
    <tr>
      <th>Mechanism</th>
      <th>What it provides</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>PSO precaching</td>
      <td>Knowledge of which pipelines to create ahead of time</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">VkPipelineCache</code></td>
      <td>Reusable driver data that may make creation cheaper</td>
    </tr>
  </tbody>
</table>

<p>A pipeline cache does not restore live <code class="language-plaintext highlighter-rouge">VkPipeline</code> handles, and it does not eliminate the need to create the requested pipelines. Its data is also implementation-specific, so a saved cache should not be treated as a universally portable compiled asset. See the <a href="https://docs.vulkan.org/guide/latest/pipeline_cache.html">Vulkan pipeline cache guide</a>.</p>

<h2 id="dynamic-state-reducing-the-number-of-variants">Dynamic State: Reducing the Number of Variants</h2>

<p>Before making pipeline creation faster, it is worth reducing how many pipelines need to exist.</p>

<p>Extended dynamic state allows more state to be specified while recording commands instead of being fixed at pipeline creation. For example, when cull mode is dynamic, changing from back-face culling to no culling does not require a separate pipeline solely for that difference:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">vkCmdBindPipeline</span><span class="p">(</span><span class="n">cmd</span><span class="p">,</span> <span class="n">VK_PIPELINE_BIND_POINT_GRAPHICS</span><span class="p">,</span> <span class="n">pipeline</span><span class="p">);</span>

<span class="n">vkCmdSetCullMode</span><span class="p">(</span><span class="n">cmd</span><span class="p">,</span> <span class="n">VK_CULL_MODE_BACK_BIT</span><span class="p">);</span>
<span class="n">vkCmdDraw</span><span class="p">(</span><span class="n">cmd</span><span class="p">,</span> <span class="p">...);</span>

<span class="n">vkCmdSetCullMode</span><span class="p">(</span><span class="n">cmd</span><span class="p">,</span> <span class="n">VK_CULL_MODE_NONE</span><span class="p">);</span>
<span class="n">vkCmdDraw</span><span class="p">(</span><span class="n">cmd</span><span class="p">,</span> <span class="p">...);</span>
</code></pre></div></div>

<p>The pipeline must declare the relevant state as dynamic, and the required features must be supported and enabled. Extensions such as <code class="language-plaintext highlighter-rouge">VK_EXT_extended_dynamic_state</code>, <code class="language-plaintext highlighter-rouge">VK_EXT_extended_dynamic_state2</code>, and <code class="language-plaintext highlighter-rouge">VK_EXT_extended_dynamic_state3</code> expand the set of available controls. <a href="https://docs.vulkan.org/guide/latest/dynamic_state.html">Vulkan dynamic state guide</a></p>

<p><strong>Dynamic rendering is a separate feature.</strong> <code class="language-plaintext highlighter-rouge">VK_KHR_dynamic_rendering</code> removes the need to create traditional render pass and framebuffer objects for that rendering path. It does not, by itself, make rasterization, depth, or blending state dynamic.</p>

<p>Dynamic state reduces combinations caused by fixed-function settings. Shader permutations still need their own solution.</p>

<h2 id="graphics-pipeline-libraries-reusing-compilation-work">Graphics Pipeline Libraries: Reusing Compilation Work</h2>

<p><code class="language-plaintext highlighter-rouge">VK_EXT_graphics_pipeline_library</code>, commonly abbreviated as GPL, divides a graphics pipeline into four reusable subsets:</p>

<table>
  <thead>
    <tr>
      <th>Library</th>
      <th>Main contents</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Vertex Input Interface</td>
      <td>Vertex input and input assembly</td>
    </tr>
    <tr>
      <td>Pre-Rasterization Shaders</td>
      <td>Pre-rasterization shader stages and associated state</td>
    </tr>
    <tr>
      <td>Fragment Shader</td>
      <td>Fragment shader and associated state</td>
    </tr>
    <tr>
      <td>Fragment Output Interface</td>
      <td>Color blending, output compatibility, and associated multisample state</td>
    </tr>
  </tbody>
</table>

<p>This is a conceptual overview; the exact state ownership follows the extension’s rules. GPL libraries contain more than shader bytecode, so their cache keys must capture all relevant state. <a href="https://docs.vulkan.org/features/latest/features/proposals/VK_EXT_graphics_pipeline_library.html">GPL proposal</a></p>

<p>The application creates or retrieves the required libraries, then links them into an executable pipeline:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Simplified application-level flow.</span>
<span class="n">VkPipeline</span> <span class="n">libraries</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="n">getVertexInputLibrary</span><span class="p">(</span><span class="n">vertexInputKey</span><span class="p">),</span>
    <span class="n">getPreRasterLibrary</span><span class="p">(</span><span class="n">preRasterKey</span><span class="p">),</span>
    <span class="n">getFragmentShaderLibrary</span><span class="p">(</span><span class="n">fragmentKey</span><span class="p">),</span>
    <span class="n">getFragmentOutputLibrary</span><span class="p">(</span><span class="n">fragmentOutputKey</span><span class="p">),</span>
<span class="p">};</span>

<span class="n">VkPipeline</span> <span class="n">pipeline</span> <span class="o">=</span> <span class="n">linkLibraries</span><span class="p">(</span><span class="n">libraries</span><span class="p">,</span> <span class="n">enableLTO</span><span class="p">);</span>
</code></pre></div></div>

<p>For the earlier example, assume that:</p>

<ul>
  <li>Vertex input is shared by every pipeline.</li>
  <li>The 30 vertex variants require 30 pre-rasterization libraries.</li>
  <li>The 40 fragment variants require 40 fragment shader libraries.</li>
  <li>All 25 state combinations belong to the fragment output subset.</li>
</ul>

<p>The application can then reuse:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1 + 30 + 40 + 25 = 96 libraries
</code></pre></div></div>

<p>It may still need <strong>30,000 executable pipeline combinations</strong>, but those pipelines share their constituent libraries.</p>

<p>That distinction explains GPL’s value: it separates reusable compilation work from the final combination step. It does not automatically reduce the number of executable pipelines the application requests.</p>

<h3 id="fast-linking-and-link-time-optimization">Fast Linking and Link-Time Optimization</h3>

<p>GPL supports a tradeoff between link cost and optimization opportunity.</p>

<p>Setting <code class="language-plaintext highlighter-rouge">VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT</code> requests link-time optimization, or LTO. Libraries intended for this path must have been created with <code class="language-plaintext highlighter-rouge">VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT</code>.</p>

<p>The device property <code class="language-plaintext highlighter-rouge">graphicsPipelineLibraryFastLinking</code> describes the non-LTO path. When it is true, creating a pipeline entirely from libraries without LTO has a cost comparable to recording a command. It does <strong>not</strong> promise that LTO linking is equally cheap. <a href="https://docs.vulkan.org/refpages/latest/refpages/source/VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT.html">Fast-linking property</a></p>

<p>One strategy is to create a non-LTO pipeline when needed, then build an optimized replacement on a background thread. Khronos describes this approach in its <a href="https://www.khronos.org/blog/reducing-draw-time-hitching-with-vk-ext-graphics-pipeline-library">GPL integration article</a>.</p>

<p>This also explains why enabling GPL may produce a smaller improvement than expected: repeatedly rebuilding libraries, using overly broad cache keys, or performing LTO for every final combination can preserve much of the original cost.</p>

<h2 id="shader-objects-binding-stages-independently">Shader Objects: Binding Stages Independently</h2>

<p><code class="language-plaintext highlighter-rouge">VK_EXT_shader_object</code> changes the application-facing model more directly.</p>

<p>Instead of creating an executable graphics pipeline for each combination, the application creates <code class="language-plaintext highlighter-rouge">VkShaderEXT</code> objects and binds the required shader stages. Fixed-function state is supplied through command-buffer commands. Graphics shader objects are used with dynamic rendering. <a href="https://docs.vulkan.org/samples/latest/samples/extensions/shader_object/README.html">Khronos shader object sample</a></p>

<p>In the LVK sample, the draw setup becomes:</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">buf</span><span class="p">.</span><span class="n">cmdBindShaderEXT</span><span class="p">(</span><span class="n">VK_SHADER_STAGE_VERTEX_BIT</span><span class="p">,</span> <span class="n">vertex</span><span class="p">.</span><span class="n">get</span><span class="p">());</span>
<span class="n">buf</span><span class="p">.</span><span class="n">cmdBindShaderEXT</span><span class="p">(</span><span class="n">VK_SHADER_STAGE_FRAGMENT_BIT</span><span class="p">,</span> <span class="n">fragment</span><span class="p">.</span><span class="n">get</span><span class="p">());</span>

<span class="c1">// Application helper that establishes baseline dynamic state.</span>
<span class="n">buf</span><span class="p">.</span><span class="n">cmdSetShaderObjectDefaults</span><span class="p">();</span>

<span class="n">buf</span><span class="p">.</span><span class="n">cmdSetVertexInput</span><span class="p">(</span><span class="n">vertexInput_</span><span class="p">);</span>
<span class="n">buf</span><span class="p">.</span><span class="n">cmdSetCullMode</span><span class="p">(</span><span class="n">lvk</span><span class="o">::</span><span class="n">CullMode_Back</span><span class="p">);</span>
<span class="n">buf</span><span class="p">.</span><span class="n">cmdBindDepthState</span><span class="p">({</span>
    <span class="p">.</span><span class="n">compareOp</span> <span class="o">=</span> <span class="n">lvk</span><span class="o">::</span><span class="n">CompareOp_Less</span><span class="p">,</span>
    <span class="p">.</span><span class="n">isDepthWriteEnabled</span> <span class="o">=</span> <span class="nb">true</span><span class="p">,</span>
<span class="p">});</span>
<span class="n">buf</span><span class="p">.</span><span class="n">cmdSetDepthBiasEnable</span><span class="p">(</span><span class="nb">false</span><span class="p">);</span>
</code></pre></div></div>

<p>Here, <code class="language-plaintext highlighter-rouge">cmdSetShaderObjectDefaults()</code> is an application helper, not a Vulkan API. It initializes the required baseline state and explicitly unbinds unused shader stages.</p>

<p>The remaining setup—resource binding, push constants, vertex/index buffers, and drawing—still has to be recorded.</p>

<p>This model allows a vertex shader to be reused with multiple compatible fragment shaders without creating a graphics pipeline for every pairing. Shader compilation still exists, and stage interfaces and resource layouts must remain compatible. Shader objects can also be linked at creation time when the application wants a linked group rather than freely interchangeable stages. <a href="https://docs.vulkan.org/spec/latest/chapters/shaders.html">Shader object specification</a></p>

<h3 id="native-support-and-the-compatibility-layer">Native Support and the Compatibility Layer</h3>

<p>Khronos also provides a shader object implementation in <a href="https://github.com/KhronosGroup/Vulkan-ExtensionLayer/blob/main/layers/shader_object/shader_object.cpp">Vulkan-ExtensionLayer</a>.</p>

<p>The layer translates shader object operations into pipeline operations, using dynamic state and GPL where available. It can therefore simplify the application’s rendering interface even when the underlying implementation still manages pipelines.</p>

<p>Native support and layer-based support should be measured separately. Using the same API does not mean both paths have identical compilation or runtime costs. The base <code class="language-plaintext highlighter-rouge">VK_EXT_shader_object</code> extension also does not replace ray tracing pipelines. <a href="https://www.khronos.org/blog/you-can-use-vulkan-without-pipelines-today">Khronos shader object overview</a></p>

<h2 id="comparing-the-approaches">Comparing the Approaches</h2>

<table>
  <thead>
    <tr>
      <th>Approach</th>
      <th>Primary benefit</th>
      <th>Work that remains</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>PSO precaching</td>
      <td>Moves pipeline creation into loading periods</td>
      <td>Discovering and creating required combinations</td>
    </tr>
    <tr>
      <td>Pipeline cache</td>
      <td>Reuses previous driver compilation data</td>
      <td>Pipeline creation and cache misses</td>
    </tr>
    <tr>
      <td>Dynamic state</td>
      <td>Removes variants caused by selected state changes</td>
      <td>Shader permutations and remaining static state</td>
    </tr>
    <tr>
      <td>GPL</td>
      <td>Shares libraries across executable pipelines</td>
      <td>Library creation and final linking</td>
    </tr>
    <tr>
      <td>Shader objects</td>
      <td>Removes the application’s need for graphics PSO combinations</td>
      <td>Shader creation, interface compatibility, and dynamic state management</td>
    </tr>
  </tbody>
</table>

<p>For a useful benchmark, measure library creation and final linking separately, distinguish LTO from non-LTO, and report whether application and driver caches are warm. Passing <code class="language-plaintext highlighter-rouge">VK_NULL_HANDLE</code> as the <code class="language-plaintext highlighter-rouge">VkPipelineCache</code> only removes the explicit application-provided cache; it does not establish that the driver has no reusable internal data.</p>

<p>The practical target is predictable frame time. A renderer benefits most when expensive compilation happens early, reusable work stays reusable, and encountering a new draw configuration does not block the frame.</p>]]></content><author><name></name></author><category term="ideas" /><summary type="html"><![CDATA[A renderer may use only a modest number of shaders and still end up managing thousands of graphics pipelines. Different combinations of shader stages, vertex formats, attachment formats, and fixed-function state can quickly multiply into a large collection of pipeline state objects. Vulkan provides several ways to manage this cost. Pipeline caches reuse previous compilation work, dynamic state reduces the number of required variants, graphics pipeline libraries share work across pipelines, and shader objects let applications bind shader stages independently. Each approach addresses a different part of the problem. Why PSO Counts Grow So Quickly In this article, a PSO refers to a graphics VkPipeline. For a typical vertex-and-fragment rendering path, it combines shader stages with vertex input, rasterization, depth/stencil, multisampling, and blending state. A simplified model is: Graphics pipeline = shader stages + fixed-function state + resource interface + rendering compatibility information Suppose a renderer needs 30 vertex shader variants, 40 fragment shader variants, and 25 fixed-function state combinations. If every combination is used, it needs: 30 × 40 × 25 = 30,000 graphics pipelines This is an illustrative upper bound: real renderers usually use only a subset of all possible combinations. Nevertheless, the multiplicative growth is the central problem. Creating these pipelines through vkCreateGraphicsPipelines() can involve translating SPIR-V into GPU machine code and optimizing it for the pipeline configuration. If that work happens on the rendering thread when a new combination first appears, it can cause a visible hitch. Compilation cost varies with the shader, driver, hardware, and available caches. MJP’s The Shader Permutation Problem provides a useful explanation of how rendering features and material systems generate these combinations. Pipeline Precaching and Pipeline Caches A common response is to move compilation out of gameplay. During development and testing, the application records the pipeline configurations it encounters. On the player’s machine, it creates those pipelines during startup or loading screens. This approach, usually called PSO precaching, trades additional loading time for fewer compilation stalls during rendering. Vulkan’s VkPipelineCache complements this process. It allows the driver to reuse implementation-specific data across pipeline creation calls. Applications can retrieve that data with vkGetPipelineCacheData(), save it to disk, and provide compatible data on a later run. These mechanisms serve different purposes: Mechanism What it provides PSO precaching Knowledge of which pipelines to create ahead of time VkPipelineCache Reusable driver data that may make creation cheaper A pipeline cache does not restore live VkPipeline handles, and it does not eliminate the need to create the requested pipelines. Its data is also implementation-specific, so a saved cache should not be treated as a universally portable compiled asset. See the Vulkan pipeline cache guide. Dynamic State: Reducing the Number of Variants Before making pipeline creation faster, it is worth reducing how many pipelines need to exist. Extended dynamic state allows more state to be specified while recording commands instead of being fixed at pipeline creation. For example, when cull mode is dynamic, changing from back-face culling to no culling does not require a separate pipeline solely for that difference: vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); vkCmdSetCullMode(cmd, VK_CULL_MODE_BACK_BIT); vkCmdDraw(cmd, ...); vkCmdSetCullMode(cmd, VK_CULL_MODE_NONE); vkCmdDraw(cmd, ...); The pipeline must declare the relevant state as dynamic, and the required features must be supported and enabled. Extensions such as VK_EXT_extended_dynamic_state, VK_EXT_extended_dynamic_state2, and VK_EXT_extended_dynamic_state3 expand the set of available controls. Vulkan dynamic state guide Dynamic rendering is a separate feature. VK_KHR_dynamic_rendering removes the need to create traditional render pass and framebuffer objects for that rendering path. It does not, by itself, make rasterization, depth, or blending state dynamic. Dynamic state reduces combinations caused by fixed-function settings. Shader permutations still need their own solution. Graphics Pipeline Libraries: Reusing Compilation Work VK_EXT_graphics_pipeline_library, commonly abbreviated as GPL, divides a graphics pipeline into four reusable subsets: Library Main contents Vertex Input Interface Vertex input and input assembly Pre-Rasterization Shaders Pre-rasterization shader stages and associated state Fragment Shader Fragment shader and associated state Fragment Output Interface Color blending, output compatibility, and associated multisample state This is a conceptual overview; the exact state ownership follows the extension’s rules. GPL libraries contain more than shader bytecode, so their cache keys must capture all relevant state. GPL proposal The application creates or retrieves the required libraries, then links them into an executable pipeline: // Simplified application-level flow. VkPipeline libraries[] = { getVertexInputLibrary(vertexInputKey), getPreRasterLibrary(preRasterKey), getFragmentShaderLibrary(fragmentKey), getFragmentOutputLibrary(fragmentOutputKey), }; VkPipeline pipeline = linkLibraries(libraries, enableLTO); For the earlier example, assume that: Vertex input is shared by every pipeline. The 30 vertex variants require 30 pre-rasterization libraries. The 40 fragment variants require 40 fragment shader libraries. All 25 state combinations belong to the fragment output subset. The application can then reuse: 1 + 30 + 40 + 25 = 96 libraries It may still need 30,000 executable pipeline combinations, but those pipelines share their constituent libraries. That distinction explains GPL’s value: it separates reusable compilation work from the final combination step. It does not automatically reduce the number of executable pipelines the application requests. Fast Linking and Link-Time Optimization GPL supports a tradeoff between link cost and optimization opportunity. Setting VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT requests link-time optimization, or LTO. Libraries intended for this path must have been created with VK_PIPELINE_CREATE_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT. The device property graphicsPipelineLibraryFastLinking describes the non-LTO path. When it is true, creating a pipeline entirely from libraries without LTO has a cost comparable to recording a command. It does not promise that LTO linking is equally cheap. Fast-linking property One strategy is to create a non-LTO pipeline when needed, then build an optimized replacement on a background thread. Khronos describes this approach in its GPL integration article. This also explains why enabling GPL may produce a smaller improvement than expected: repeatedly rebuilding libraries, using overly broad cache keys, or performing LTO for every final combination can preserve much of the original cost. Shader Objects: Binding Stages Independently VK_EXT_shader_object changes the application-facing model more directly. Instead of creating an executable graphics pipeline for each combination, the application creates VkShaderEXT objects and binds the required shader stages. Fixed-function state is supplied through command-buffer commands. Graphics shader objects are used with dynamic rendering. Khronos shader object sample In the LVK sample, the draw setup becomes: buf.cmdBindShaderEXT(VK_SHADER_STAGE_VERTEX_BIT, vertex.get()); buf.cmdBindShaderEXT(VK_SHADER_STAGE_FRAGMENT_BIT, fragment.get()); // Application helper that establishes baseline dynamic state. buf.cmdSetShaderObjectDefaults(); buf.cmdSetVertexInput(vertexInput_); buf.cmdSetCullMode(lvk::CullMode_Back); buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less, .isDepthWriteEnabled = true, }); buf.cmdSetDepthBiasEnable(false); Here, cmdSetShaderObjectDefaults() is an application helper, not a Vulkan API. It initializes the required baseline state and explicitly unbinds unused shader stages. The remaining setup—resource binding, push constants, vertex/index buffers, and drawing—still has to be recorded. This model allows a vertex shader to be reused with multiple compatible fragment shaders without creating a graphics pipeline for every pairing. Shader compilation still exists, and stage interfaces and resource layouts must remain compatible. Shader objects can also be linked at creation time when the application wants a linked group rather than freely interchangeable stages. Shader object specification Native Support and the Compatibility Layer Khronos also provides a shader object implementation in Vulkan-ExtensionLayer. The layer translates shader object operations into pipeline operations, using dynamic state and GPL where available. It can therefore simplify the application’s rendering interface even when the underlying implementation still manages pipelines. Native support and layer-based support should be measured separately. Using the same API does not mean both paths have identical compilation or runtime costs. The base VK_EXT_shader_object extension also does not replace ray tracing pipelines. Khronos shader object overview Comparing the Approaches Approach Primary benefit Work that remains PSO precaching Moves pipeline creation into loading periods Discovering and creating required combinations Pipeline cache Reuses previous driver compilation data Pipeline creation and cache misses Dynamic state Removes variants caused by selected state changes Shader permutations and remaining static state GPL Shares libraries across executable pipelines Library creation and final linking Shader objects Removes the application’s need for graphics PSO combinations Shader creation, interface compatibility, and dynamic state management For a useful benchmark, measure library creation and final linking separately, distinguish LTO from non-LTO, and report whether application and driver caches are warm. Passing VK_NULL_HANDLE as the VkPipelineCache only removes the explicit application-provided cache; it does not establish that the driver has no reusable internal data. The practical target is predictable frame time. A renderer benefits most when expensive compilation happens early, reusable work stays reusable, and encountering a new draw configuration does not block the frame.]]></summary></entry><entry><title type="html">Normal Fix</title><link href="https://penantumbra.github.io/normalfix/" rel="alternate" type="text/html" title="Normal Fix" /><published>2026-07-28T00:00:00+00:00</published><updated>2026-07-28T00:00:00+00:00</updated><id>https://penantumbra.github.io/normalfix</id><content type="html" xml:base="https://penantumbra.github.io/normalfix/"><![CDATA[<h2 id="实时光线追踪法线修正和平滑">实时光线追踪：法线修正和平滑</h2>

<p>在玻璃光追中，法线处理的第一个问题是：Mesh 通常只记录朝向物体外部的法线，但光线既可能从空气进入玻璃，也可能从玻璃内部射向空气。</p>

<p>因此，每次命中表面时，都要先根据光线方向与几何法线的关系判断当前处于入射还是出射状态，再统一修正法线方向和折射率比例：</p>

<div class="language-glsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// 光线射入物体</span>
<span class="n">dir_refl</span> <span class="o">=</span> <span class="n">reflect</span><span class="p">(</span><span class="n">r</span><span class="p">,</span>  <span class="n">n</span><span class="p">);</span>
<span class="n">dir_refr</span> <span class="o">=</span> <span class="n">refract</span><span class="p">(</span><span class="n">r</span><span class="p">,</span> <span class="o">-</span><span class="n">n</span><span class="p">,</span> <span class="n">eta</span><span class="p">);</span>

<span class="c1">// 光线射出物体</span>
<span class="n">dir_refl</span> <span class="o">=</span> <span class="n">reflect</span><span class="p">(</span><span class="n">r</span><span class="p">,</span> <span class="o">-</span><span class="n">n</span><span class="p">);</span>
<span class="n">dir_refr</span> <span class="o">=</span> <span class="n">refract</span><span class="p">(</span><span class="n">r</span><span class="p">,</span>  <span class="n">n</span><span class="p">,</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span> <span class="o">/</span> <span class="n">eta</span><span class="p">);</span>
</code></pre></div></div>

<p>这里的关键不是单独翻转法线，而是让法线方向、入射介质和出射介质保持一致。否则可能得到错误的光线方向，甚至错误触发全反射。</p>

<h2 id="法线平滑">法线平滑</h2>

<p>法线处理的第二个问题来自低模曲面的平滑着色。玻璃侧面，尤其是在薄边和掠射角区域，三角形之间的法线变化较大；如果直接使用几何法线，容易出现明显的分面感。</p>

<blockquote>
  <p><strong>图片占位符</strong></p>
</blockquote>

<p>实时渲染通常会根据交点的重心坐标，对三角形三个顶点的法线进行插值，得到平滑的着色法线。同时，我们还会保留由三角形边叉乘得到的几何法线：</p>

<div class="language-glsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">geometricNormal</span> <span class="o">=</span> <span class="n">normalize</span><span class="p">(</span><span class="n">cross</span><span class="p">(</span><span class="n">p1</span> <span class="o">-</span> <span class="n">p0</span><span class="p">,</span> <span class="n">p2</span> <span class="o">-</span> <span class="n">p0</span><span class="p">));</span>
</code></pre></div></div>

<p>这里需要明确两类法线的分工：</p>

<ul>
  <li><strong>几何法线（Geometric Normal）</strong>：代表三角形的真实朝向，用于判断表面内外、处理自相交，并校验新生成光线的方向。</li>
  <li><strong>着色法线（Shading Normal）</strong>：用于材质计算，让低模曲面呈现平滑的视觉效果。</li>
</ul>

<p>在大多数情况下，使用着色法线计算光照没有问题。但在薄边、低模曲面或掠射角区域，着色法线可能与几何法线偏差较大。此时，根据着色法线生成的反射或折射方向，可能落到真实几何表面的错误一侧，进而产生黑点、漏光、自相交或边缘闪烁。</p>

<p>因此，生成候选方向后，还需要同时使用两类法线进行半球校验。在法线已经统一朝向入射侧的前提下：</p>

<div class="language-glsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">bool</span> <span class="n">validReflection</span> <span class="o">=</span>
    <span class="n">dot</span><span class="p">(</span><span class="n">direction</span><span class="p">,</span> <span class="n">shadingNormal</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span> <span class="o">&amp;&amp;</span>
    <span class="n">dot</span><span class="p">(</span><span class="n">direction</span><span class="p">,</span> <span class="n">geometricNormal</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">;</span>

<span class="kt">bool</span> <span class="n">validRefraction</span> <span class="o">=</span>
    <span class="n">dot</span><span class="p">(</span><span class="n">direction</span><span class="p">,</span> <span class="n">shadingNormal</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span> <span class="o">&amp;&amp;</span>
    <span class="n">dot</span><span class="p">(</span><span class="n">direction</span><span class="p">,</span> <span class="n">geometricNormal</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">;</span>
</code></pre></div></div>

<p>如果方向不合法，可以将该采样贡献置零或重新采样。Blender Cycles 的微表面采样也采用了类似的双法线校验，避免平滑几何产生错误的反射和折射方向。</p>

<p>这一部分可以总结为：几何法线负责保证光线方向在物理上合法，着色法线负责保证表面在视觉上平滑；两者需要分工使用，并在发射新光线前完成一致性校验。</p>

<blockquote>
  <p><strong>参考：</strong> Blender Cycles hemisphere validation</p>
</blockquote>]]></content><author><name></name></author><category term="ideas" /><summary type="html"><![CDATA[实时光线追踪：法线修正和平滑 在玻璃光追中，法线处理的第一个问题是：Mesh 通常只记录朝向物体外部的法线，但光线既可能从空气进入玻璃，也可能从玻璃内部射向空气。 因此，每次命中表面时，都要先根据光线方向与几何法线的关系判断当前处于入射还是出射状态，再统一修正法线方向和折射率比例： // 光线射入物体 dir_refl = reflect(r, n); dir_refr = refract(r, -n, eta); // 光线射出物体 dir_refl = reflect(r, -n); dir_refr = refract(r, n, 1.0 / eta); 这里的关键不是单独翻转法线，而是让法线方向、入射介质和出射介质保持一致。否则可能得到错误的光线方向，甚至错误触发全反射。 法线平滑 法线处理的第二个问题来自低模曲面的平滑着色。玻璃侧面，尤其是在薄边和掠射角区域，三角形之间的法线变化较大；如果直接使用几何法线，容易出现明显的分面感。 图片占位符 实时渲染通常会根据交点的重心坐标，对三角形三个顶点的法线进行插值，得到平滑的着色法线。同时，我们还会保留由三角形边叉乘得到的几何法线： geometricNormal = normalize(cross(p1 - p0, p2 - p0)); 这里需要明确两类法线的分工： 几何法线（Geometric Normal）：代表三角形的真实朝向，用于判断表面内外、处理自相交，并校验新生成光线的方向。 着色法线（Shading Normal）：用于材质计算，让低模曲面呈现平滑的视觉效果。 在大多数情况下，使用着色法线计算光照没有问题。但在薄边、低模曲面或掠射角区域，着色法线可能与几何法线偏差较大。此时，根据着色法线生成的反射或折射方向，可能落到真实几何表面的错误一侧，进而产生黑点、漏光、自相交或边缘闪烁。 因此，生成候选方向后，还需要同时使用两类法线进行半球校验。在法线已经统一朝向入射侧的前提下： bool validReflection = dot(direction, shadingNormal) &gt; 0.0 &amp;&amp; dot(direction, geometricNormal) &gt; 0.0; bool validRefraction = dot(direction, shadingNormal) &lt; 0.0 &amp;&amp; dot(direction, geometricNormal) &lt; 0.0; 如果方向不合法，可以将该采样贡献置零或重新采样。Blender Cycles 的微表面采样也采用了类似的双法线校验，避免平滑几何产生错误的反射和折射方向。 这一部分可以总结为：几何法线负责保证光线方向在物理上合法，着色法线负责保证表面在视觉上平滑；两者需要分工使用，并在发射新光线前完成一致性校验。 参考： Blender Cycles hemisphere validation]]></summary></entry><entry><title type="html">Self Intersection</title><link href="https://penantumbra.github.io/selfintersect/" rel="alternate" type="text/html" title="Self Intersection" /><published>2026-07-28T00:00:00+00:00</published><updated>2026-07-28T00:00:00+00:00</updated><id>https://penantumbra.github.io/selfintersect</id><content type="html" xml:base="https://penantumbra.github.io/selfintersect/"><![CDATA[<h2 id="ray-tracing-gems-a-fast-and-robust-method-for-avoiding--self--intersection">Ray Tracing Gems: A Fast and Robust Method for Avoiding  Self- Intersection</h2>

<p>在光线追踪中，从表面交点继续发射阴影、反射或折射光线时，新光线有时会立刻再次命中当前表面，从而产生异常黑斑、条纹等自遮挡现象。这通常不是真实的遮挡，而是浮点数误差引起的自相交（Self-Intersection）：自相交是原因，自遮挡是最终表现。</p>

<p>光线与三角形求交后，我们会根据交点参数或重心坐标重建交点位置 $p$。在精确数学中，$p$ 应当位于三角形平面上；但受浮点数精度限制，计算结果可能略高于或略低于真实表面。如果交点落在表面下方，从该点发射的次级光线就可能再次命中当前三角形或相邻三角形。</p>

<h2 id="常见方法及其局限">常见方法及其局限</h2>

<h3 id="1-忽略当前三角形">1. 忽略当前三角形</h3>

<p>记录当前命中的三角形 ID，并在次级光线再次命中相同 ID 时忽略该交点。这种方法实现简单，但存在以下问题：</p>

<ul>
  <li>在掠射角（Grazing Angle）下，光线可能命中相邻三角形，而不是原三角形；</li>
  <li>无法正确处理重叠、共面或距离非常近的几何体；</li>
  <li>某些情况下，光线本来就应该再次命中同一个三角形。</li>
</ul>

<h3 id="2-设置固定的-tmin">2. 设置固定的 <code class="language-plaintext highlighter-rouge">tMin</code></h3>

<p>将光线的有效区间设置为 $t \in [\varepsilon, t_{\max}]$，忽略距离原点小于 $\varepsilon$ 的交点。</p>

<p>固定的 $\varepsilon$ 不具备尺度不变性：对于大型或远离原点的场景，它可能太小；对于微小、紧密的几何结构，它又可能太大。此外，在掠射角下，光线沿几何法线方向产生的实际位移很小，因此光线仍可能位于表面下方。</p>

<h3 id="3-沿着色法线偏移">3. 沿着色法线偏移</h3>

<p>着色法线（Shading Normal）通常由顶点法线插值得到，主要用于获得平滑的光照效果。它不一定与真实三角形平面正交，因此沿着色法线偏移，可能无法以最短距离离开表面，甚至可能把交点移动到几何体内部。</p>

<h2 id="沿几何法线进行自适应偏移">沿几何法线进行自适应偏移</h2>

<p>几何法线（Geometric Normal）始终垂直于三角形平面。与其他方向相比，沿几何法线偏移能够以更小的位移离开表面，因此更适合用来修正次级光线的起点。</p>

<p>这里不能简单地使用固定偏移。浮点数保持的是近似固定的相对精度，而不是固定的绝对精度：坐标的绝对值越大，相邻可表示浮点数之间的间隔也越大。因此，交点离世界坐标原点越远，重建交点时的绝对误差通常越大；三角形尺寸越大，参与计算的数值越大，也可能进一步放大误差。</p>

<p>换句话说，可靠的偏移量应当同时适应交点坐标和几何尺寸的数量级，而不能依赖一个对所有场景都相同的固定 <code class="language-plaintext highlighter-rouge">Bias</code>。</p>

<blockquote>
  <p><strong>图片占位符</strong></p>
</blockquote>

<p>实现时，我们不直接给交点坐标加上固定的小数，而是将每个浮点分量的二进制表示重新解释为整数，再根据几何法线的方向移动若干个浮点刻度，也就是 ULP。</p>

<p>浮点数相邻刻度的间隔会随着数值大小自动变化，因此，同样的整数刻度偏移会产生不同的实际位移：</p>

<ul>
  <li>坐标较小时，实际偏移较小；</li>
  <li>坐标较大时，实际偏移也会相应增大。</li>
</ul>

<p>这样，偏移量便能自动适应交点坐标的数量级，无须针对不同场景手动调整参数。</p>

<p>接近零的位置需要单独处理。此时，通过整数表示移动若干刻度产生的位移可能小得不足以覆盖求交误差。因此，对于绝对值小于阈值的坐标分量，代码会直接沿几何法线增加一个很小的固定浮点偏移。三个坐标分量需要分别判断，因为同一个交点可能同时包含接近零和数值很大的分量。</p>

<p>下面代码中的常量来自实验测得的最大误差，并额外保留了一定的安全裕度：</p>

<div class="language-cpp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">constexpr</span> <span class="kt">float</span> <span class="nf">origin</span><span class="p">()</span>      <span class="p">{</span> <span class="k">return</span> <span class="mf">1.0</span><span class="n">f</span> <span class="o">/</span> <span class="mf">32.0</span><span class="n">f</span><span class="p">;</span> <span class="p">}</span>
<span class="k">constexpr</span> <span class="kt">float</span> <span class="nf">float_scale</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="mf">1.0</span><span class="n">f</span> <span class="o">/</span> <span class="mf">65536.0</span><span class="n">f</span><span class="p">;</span> <span class="p">}</span>
<span class="k">constexpr</span> <span class="kt">float</span> <span class="nf">int_scale</span><span class="p">()</span>   <span class="p">{</span> <span class="k">return</span> <span class="mf">256.0</span><span class="n">f</span><span class="p">;</span> <span class="p">}</span>

<span class="c1">// n 为朝向次级光线发射侧的几何法线</span>
<span class="n">float3</span> <span class="nf">offset_ray</span><span class="p">(</span><span class="k">const</span> <span class="n">float3</span> <span class="n">p</span><span class="p">,</span> <span class="k">const</span> <span class="n">float3</span> <span class="n">n</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">int3</span> <span class="n">of_i</span><span class="p">(</span>
        <span class="n">int_scale</span><span class="p">()</span> <span class="o">*</span> <span class="n">n</span><span class="p">.</span><span class="n">x</span><span class="p">,</span>
        <span class="n">int_scale</span><span class="p">()</span> <span class="o">*</span> <span class="n">n</span><span class="p">.</span><span class="n">y</span><span class="p">,</span>
        <span class="n">int_scale</span><span class="p">()</span> <span class="o">*</span> <span class="n">n</span><span class="p">.</span><span class="n">z</span>
    <span class="p">);</span>

    <span class="n">float3</span> <span class="n">p_i</span><span class="p">(</span>
        <span class="n">int_as_float</span><span class="p">(</span><span class="n">float_as_int</span><span class="p">(</span><span class="n">p</span><span class="p">.</span><span class="n">x</span><span class="p">)</span> <span class="o">+</span> <span class="p">((</span><span class="n">p</span><span class="p">.</span><span class="n">x</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="o">?</span> <span class="o">-</span><span class="n">of_i</span><span class="p">.</span><span class="n">x</span> <span class="o">:</span> <span class="n">of_i</span><span class="p">.</span><span class="n">x</span><span class="p">)),</span>
        <span class="n">int_as_float</span><span class="p">(</span><span class="n">float_as_int</span><span class="p">(</span><span class="n">p</span><span class="p">.</span><span class="n">y</span><span class="p">)</span> <span class="o">+</span> <span class="p">((</span><span class="n">p</span><span class="p">.</span><span class="n">y</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="o">?</span> <span class="o">-</span><span class="n">of_i</span><span class="p">.</span><span class="n">y</span> <span class="o">:</span> <span class="n">of_i</span><span class="p">.</span><span class="n">y</span><span class="p">)),</span>
        <span class="n">int_as_float</span><span class="p">(</span><span class="n">float_as_int</span><span class="p">(</span><span class="n">p</span><span class="p">.</span><span class="n">z</span><span class="p">)</span> <span class="o">+</span> <span class="p">((</span><span class="n">p</span><span class="p">.</span><span class="n">z</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="o">?</span> <span class="o">-</span><span class="n">of_i</span><span class="p">.</span><span class="n">z</span> <span class="o">:</span> <span class="n">of_i</span><span class="p">.</span><span class="n">z</span><span class="p">))</span>
    <span class="p">);</span>

    <span class="k">return</span> <span class="n">float3</span><span class="p">(</span>
        <span class="n">fabsf</span><span class="p">(</span><span class="n">p</span><span class="p">.</span><span class="n">x</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">origin</span><span class="p">()</span> <span class="o">?</span> <span class="n">p</span><span class="p">.</span><span class="n">x</span> <span class="o">+</span> <span class="n">float_scale</span><span class="p">()</span> <span class="o">*</span> <span class="n">n</span><span class="p">.</span><span class="n">x</span> <span class="o">:</span> <span class="n">p_i</span><span class="p">.</span><span class="n">x</span><span class="p">,</span>
        <span class="n">fabsf</span><span class="p">(</span><span class="n">p</span><span class="p">.</span><span class="n">y</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">origin</span><span class="p">()</span> <span class="o">?</span> <span class="n">p</span><span class="p">.</span><span class="n">y</span> <span class="o">+</span> <span class="n">float_scale</span><span class="p">()</span> <span class="o">*</span> <span class="n">n</span><span class="p">.</span><span class="n">y</span> <span class="o">:</span> <span class="n">p_i</span><span class="p">.</span><span class="n">y</span><span class="p">,</span>
        <span class="n">fabsf</span><span class="p">(</span><span class="n">p</span><span class="p">.</span><span class="n">z</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">origin</span><span class="p">()</span> <span class="o">?</span> <span class="n">p</span><span class="p">.</span><span class="n">z</span> <span class="o">+</span> <span class="n">float_scale</span><span class="p">()</span> <span class="o">*</span> <span class="n">n</span><span class="p">.</span><span class="n">z</span> <span class="o">:</span> <span class="n">p_i</span><span class="p">.</span><span class="n">z</span>
    <span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="方法的边界">方法的边界</h2>

<p>自适应几何法线偏移可以显著降低自相交的概率，但仍然无法覆盖所有极端情况。</p>

<p>例如，对于又深又窄的缝隙，如果缝隙宽度小于偏移距离，那么沿几何法线移动光线原点时，可能直接越过对面的表面，或者把新的光线原点移动到同一物体或相邻物体内部。</p>

<blockquote>
  <p><strong>图片占位符</strong></p>
</blockquote>

<p>这种问题体现了偏移策略本身的取舍：</p>

<ul>
  <li>偏移太小，无法可靠避开自相交；</li>
  <li>偏移太大，又可能跳过非常细小的几何结构。</li>
</ul>

<p>因此，该方法不能保证所有场景都绝对正确，但相比固定 <code class="language-plaintext highlighter-rouge">tMin</code>、忽略当前三角形或沿着色法线偏移，它具有更好的尺度适应性和稳定性。</p>]]></content><author><name></name></author><category term="ideas" /><summary type="html"><![CDATA[Ray Tracing Gems: A Fast and Robust Method for Avoiding Self- Intersection 在光线追踪中，从表面交点继续发射阴影、反射或折射光线时，新光线有时会立刻再次命中当前表面，从而产生异常黑斑、条纹等自遮挡现象。这通常不是真实的遮挡，而是浮点数误差引起的自相交（Self-Intersection）：自相交是原因，自遮挡是最终表现。 光线与三角形求交后，我们会根据交点参数或重心坐标重建交点位置 $p$。在精确数学中，$p$ 应当位于三角形平面上；但受浮点数精度限制，计算结果可能略高于或略低于真实表面。如果交点落在表面下方，从该点发射的次级光线就可能再次命中当前三角形或相邻三角形。 常见方法及其局限 1. 忽略当前三角形 记录当前命中的三角形 ID，并在次级光线再次命中相同 ID 时忽略该交点。这种方法实现简单，但存在以下问题： 在掠射角（Grazing Angle）下，光线可能命中相邻三角形，而不是原三角形； 无法正确处理重叠、共面或距离非常近的几何体； 某些情况下，光线本来就应该再次命中同一个三角形。 2. 设置固定的 tMin 将光线的有效区间设置为 $t \in [\varepsilon, t_{\max}]$，忽略距离原点小于 $\varepsilon$ 的交点。 固定的 $\varepsilon$ 不具备尺度不变性：对于大型或远离原点的场景，它可能太小；对于微小、紧密的几何结构，它又可能太大。此外，在掠射角下，光线沿几何法线方向产生的实际位移很小，因此光线仍可能位于表面下方。 3. 沿着色法线偏移 着色法线（Shading Normal）通常由顶点法线插值得到，主要用于获得平滑的光照效果。它不一定与真实三角形平面正交，因此沿着色法线偏移，可能无法以最短距离离开表面，甚至可能把交点移动到几何体内部。 沿几何法线进行自适应偏移 几何法线（Geometric Normal）始终垂直于三角形平面。与其他方向相比，沿几何法线偏移能够以更小的位移离开表面，因此更适合用来修正次级光线的起点。 这里不能简单地使用固定偏移。浮点数保持的是近似固定的相对精度，而不是固定的绝对精度：坐标的绝对值越大，相邻可表示浮点数之间的间隔也越大。因此，交点离世界坐标原点越远，重建交点时的绝对误差通常越大；三角形尺寸越大，参与计算的数值越大，也可能进一步放大误差。 换句话说，可靠的偏移量应当同时适应交点坐标和几何尺寸的数量级，而不能依赖一个对所有场景都相同的固定 Bias。 图片占位符 实现时，我们不直接给交点坐标加上固定的小数，而是将每个浮点分量的二进制表示重新解释为整数，再根据几何法线的方向移动若干个浮点刻度，也就是 ULP。 浮点数相邻刻度的间隔会随着数值大小自动变化，因此，同样的整数刻度偏移会产生不同的实际位移： 坐标较小时，实际偏移较小； 坐标较大时，实际偏移也会相应增大。 这样，偏移量便能自动适应交点坐标的数量级，无须针对不同场景手动调整参数。 接近零的位置需要单独处理。此时，通过整数表示移动若干刻度产生的位移可能小得不足以覆盖求交误差。因此，对于绝对值小于阈值的坐标分量，代码会直接沿几何法线增加一个很小的固定浮点偏移。三个坐标分量需要分别判断，因为同一个交点可能同时包含接近零和数值很大的分量。 下面代码中的常量来自实验测得的最大误差，并额外保留了一定的安全裕度： constexpr float origin() { return 1.0f / 32.0f; } constexpr float float_scale() { return 1.0f / 65536.0f; } constexpr float int_scale() { return 256.0f; } // n 为朝向次级光线发射侧的几何法线 float3 offset_ray(const float3 p, const float3 n) { int3 of_i( int_scale() * n.x, int_scale() * n.y, int_scale() * n.z ); float3 p_i( int_as_float(float_as_int(p.x) + ((p.x &lt; 0) ? -of_i.x : of_i.x)), int_as_float(float_as_int(p.y) + ((p.y &lt; 0) ? -of_i.y : of_i.y)), int_as_float(float_as_int(p.z) + ((p.z &lt; 0) ? -of_i.z : of_i.z)) ); return float3( fabsf(p.x) &lt; origin() ? p.x + float_scale() * n.x : p_i.x, fabsf(p.y) &lt; origin() ? p.y + float_scale() * n.y : p_i.y, fabsf(p.z) &lt; origin() ? p.z + float_scale() * n.z : p_i.z ); } 方法的边界 自适应几何法线偏移可以显著降低自相交的概率，但仍然无法覆盖所有极端情况。 例如，对于又深又窄的缝隙，如果缝隙宽度小于偏移距离，那么沿几何法线移动光线原点时，可能直接越过对面的表面，或者把新的光线原点移动到同一物体或相邻物体内部。 图片占位符 这种问题体现了偏移策略本身的取舍： 偏移太小，无法可靠避开自相交； 偏移太大，又可能跳过非常细小的几何结构。 因此，该方法不能保证所有场景都绝对正确，但相比固定 tMin、忽略当前三角形或沿着色法线偏移，它具有更好的尺度适应性和稳定性。]]></summary></entry><entry><title type="html">Q2RTX codepath</title><link href="https://penantumbra.github.io/q2rtx/" rel="alternate" type="text/html" title="Q2RTX codepath" /><published>2026-07-02T00:00:00+00:00</published><updated>2026-07-02T00:00:00+00:00</updated><id>https://penantumbra.github.io/q2rtx</id><content type="html" xml:base="https://penantumbra.github.io/q2rtx/"><![CDATA[<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#define MATERIAL_KIND_MASK           0xf0000000
#define MATERIAL_KIND_INVALID        0x00000000
#define MATERIAL_KIND_REGULAR        0x10000000
#define MATERIAL_KIND_CHROME         0x20000000
#define MATERIAL_KIND_WATER          0x30000000
#define MATERIAL_KIND_LAVA           0x40000000
#define MATERIAL_KIND_SLIME          0x50000000
#define MATERIAL_KIND_GLASS          0x60000000
#define MATERIAL_KIND_SKY            0x70000000
#define MATERIAL_KIND_INVISIBLE      0x80000000
#define MATERIAL_KIND_EXPLOSION      0x90000000
#define MATERIAL_KIND_TRANSPARENT    0xa0000000 // Transparent walls. Have a distortion effect applied.
#define MATERIAL_KIND_SCREEN         0xb0000000
#define MATERIAL_KIND_CAMERA         0xc0000000
#define MATERIAL_KIND_CHROME_MODEL   0xd0000000
#define MATERIAL_KIND_TRANSP_MODEL   0xe0000000 // Transparent models. No distortion, just "see through".


struct RayPayloadGeometry {
   vec2 barycentric;
   /* two packed 16 bit integers, buffer index in low 16 bits and
    * instance index in high 16 bits */
   int buffer_and_instance_idx;
   uint primitive_id;
   float hit_distance;
};

struct RayPayloadEffects {
   uvec2 transparency; // half4x16
   uint distances; // half2x16 - min and max
   uvec4 fog1; // half8x16: .xy = color.rgba; .z = t_min, t_max; .w = density: a and b for (a*t + b)
   uvec4 fog2; // same as fog1 but for a fog volume further away
#ifndef KHR_RAY_QUERY
   // Store TMax in the payload because gl_RayTmaxEXT changes while the ray is being traced.
   // See the GLSL_EXT_ray_tracing spec near "description for gl_RayTminEXT and gl_RayTmaxEXT"
   // https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GLSL_EXT_ray_tracing.txt 
   float rayTmax; 
#endif
};

layout(location = RT_PAYLOAD_GEOMETRY) rayPayloadEXT RayPayloadGeometry ray_payload_geometry;
layout(location = RT_PAYLOAD_EFFECTS) rayPayloadEXT RayPayloadEffects ray_payload_effects;
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// primary ray
vkpt_pt_trace_primary_rays(trace_cmd_buf);
// qvkCmdTraceRaysKHR(cmd_buf,
//  &amp;raygen,
//  &amp;miss_and_hit,
//  &amp;miss_and_hit,
//  &amp;callable,
//  width/2, height, depth); // 2 depth for checkerboard rendering, split
vkpt_submit_command_buffer();

// indirect reflection/refraction
if (ref_mode.reflect_refract &gt; 0)
    vkpt_pt_trace_reflections(trace_cmd_buf, 0);
    
// multiple reflection/refraction
if (ref_mode.reflect_refract &gt; 1)
    for (int pass = 0; pass &lt; ref_mode.reflect_refract - 1; pass++)
        vkpt_pt_trace_reflections(trace_cmd_buf, pass + 1);

// seperated svgf reprojected pass
vkpt_asvgf_gradient_reproject(trace_cmd_buf);

vkpt_pt_trace_lighting(trace_cmd_buf, ref_mode.num_bounce_rays);

vkpt_submit_command_buffer();

vkpt_asvgf_filter(post_cmd_buf, cvar_pt_num_bounce_rays-&gt;value &gt;= 0.5f);

vkpt_interleave(post_cmd_buf);

vkpt_taa(post_cmd_buf);

vkpt_bloom_record_cmd_buffer(post_cmd_buf);
vkpt_tone_mapping_record_cmd_buffer();
vkpt_fsr_do(post_cmd_buf);
vkpt_submit_command_buffer_simple();
</code></pre></div></div>

<p>primary_rays.rgen(path tracer overview的1)</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> // generate primary ray information, including bias offset to get depth of field
Ray ray = get_primary_ray(inUV);


// primary ray -&gt; path_tracer.rchit/path_tracer.rmiss
traceRayEXT( topLevelAS[TLAS_INDEX_GEOMETRY], rayFlags, instance_mask,
        SBT_RCHIT_GEOMETRY /*sbtRecordOffset*/, 0 /*sbtRecordStride*/, SBT_RMISS_EMPTY /*missIndex*/,
        ray.origin, ray.t_min, ray.direction, ray.t_max, RT_PAYLOAD_GEOMETRY);

Triangle triangle;

if (found_intersection(ray_payload_geometry)) // hit surface
{
    ray.t_max = ray_payload_geometry.hit_distance;
    triangle = get_hit_triangle(ray_payload_geometry);
}
// particle/explosion/sprite/beam
traceRayEXT( topLevelAS[TLAS_INDEX_EFFECTS], rayFlags, instance_mask,
        SBT_RCHIT_EFFECTS /*sbtRecordOffset*/, 0 /*sbtRecordStride*/, SBT_RMISS_EMPTY /*missIndex*/,
        ray.origin, ray.t_min, ray.direction, ray.t_max, RT_PAYLOAD_EFFECTS);

vec4 effects = get_payload_transparency_with_fog(ray_payload_effects, ray.t_max);

vec3 bary = get_hit_barycentric(ray_payload_geometry);

// store 2 visibility buffer
{
    uvec2 vis_buf;
    vis_buf.x = triangle.instance_index;
    vis_buf.y = triangle.instance_prim;
    imageStore(IMG_PT_VISBUF_PRIM_A, ipos, uvec4(vis_buf, 0, 0)); // rg32ui / R32G32_UINT
    imageStore(IMG_PT_VISBUF_BARY_A, ipos, vec4(bary.yz, 0, 0)); // rg16f / R16G16_SFLOAT
}

// get hit point information
vec3 position = triangle.positions * bary;
vec2 texcoord = triangle.texcoords * bary;
vec3 geo_normal = triangle.normals* bary;
vec3 flat_normal = normalize(cross(
        triangle.positions[1] - triangle.positions[0],
        triangle.positions[2] - triangle.positions[1]));

/* compute view-space derivatives of depth and motion vectors */
Ray ray_0 = get_primary_ray(inUV);
Ray ray_x = get_primary_ray(inUV + vec2(1.0 / float(global_ubo.width), 0));
Ray ray_y = get_primary_ray(inUV + vec2(0, 1.0 / float(global_ubo.height)));

// larger coneangle means high gradient, means higher mips
float half_cone_angle = sqrt(1.0 - square(min(
dot(ray_0.direction, ray_x.direction), 
dot(ray_0.direction, ray_y.direction))));

vec2 tex_coord_x, tex_coord_y;
float fwidth_depth;
// get texure lod
compute_anisotropic_texture_gradients(position, flat_normal, ray.direction, 
    ray_payload_geometry.hit_distance * half_cone_angle, triangle.positions, 
    triangle.tex_coords, tex_coord, tex_coord_x, tex_coord_y, fwidth_depth);

vec3 pos_ws_curr = position;
vec3 pos_ws_prev = triangle.positions_prev * bary;
vec2 screen_pos_curr, screen_pos_prev;
float distance_curr, distance_prev;
projection_view_to_screen((global_ubo.V * vec4(pos_ws_curr, 1)).xyz, screen_pos_curr, distance_curr, false);
projection_view_to_screen((global_ubo.V_prev * vec4(pos_ws_prev, 1)).xyz, screen_pos_prev, distance_prev, true);

// motion vector
vec3 motion;
motion.xy = screen_pos_prev - screen_pos_curr;
motion.z = distance_prev - distance_curr;

imageStore(IMG_PT_VIEW_DEPTH_A, ipos, vec4(distance_curr));
imageStore(IMG_PT_MOTION, ipos, vec4(motion, fwidth_depth));

// Get the primary surface material parameters
get_material(
    triangle,
    bary,
    tex_coord,
    tex_coord_x,
    tex_coord_y,
    -1,
    geo_normal,
    primary_base_color,
    normal,
    primary_metallic,
    primary_roughness,
    primary_emissive,
    primary_specular_factor);

// get mat id
uint material_id = triangle.material_id;
...

// handle various material one by one

// write to gbuffer
// shading normal
imageStore(IMG_PT_NORMAL_A, ipos, uvec4(encode_normal(normal)));
// geo normal
imageStore(IMG_PT_GEO_NORMAL_A, ipos, uvec4(encode_normal(geo_normal)));
//...
imageStore(IMG_PT_SHADING_POSITION, ipos, vec4(position.xyz, uintBitsToFloat(material_id)));
//...
imageStore(IMG_PT_VIEW_DIRECTION, ipos, vec4(direction, float(checkerboard_flags)));
imageStore(IMG_PT_THROUGHPUT, ipos, vec4(throughput, distance_curr));
imageStore(IMG_PT_BOUNCE_THROUGHPUT, ipos, vec4(1, 1, 1, half_cone_angle));
imageStore(IMG_PT_CLUSTER_A, ipos, ivec4(triangle.cluster));
imageStore(IMG_PT_BASE_COLOR_A, ipos, vec4(primary_base_color, primary_specular_factor));
imageStore(IMG_PT_METALLIC_A, ipos, vec4(primary_metallic, primary_roughness, 0, 0));
imageStore(IMG_PT_GODRAYS_THROUGHPUT_DIST, ipos, vec4(1, 1, 1, distance_curr));
transparent = alpha_blend_premultiplied(effects, transparent);

imageStore(IMG_PT_TRANSPARENT, ipos, transparent);
</code></pre></div></div>

<p>reflect_refract.rgen</p>

<p>reflect_refract.rgen 会在 G-buffer 当前 surface 是 water / slime / glass / chrome / screen / camera / transparent 等特殊材质时，每像素沿 reflection 或 refraction 方向继续追一条 ray，并用命中的 secondary surface 更新 G-buffer / throughput / medium / motion。下面的 IOR + checkerboard 代码是抽象伪码；真实代码会按 material kind 分支处理 thin/thick glass、water/slime medium、total internal reflection、chrome/screen 只反射、transparent see-through 等情况。</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// get shading pos
vec4 position_material = imageLoad(IMG_PT_SHADING_POSITION, ipos);

if(!( primary_is_water || 
      primary_is_slime || 
      primary_is_glass || 
      primary_is_chrome || 
      primary_is_screen || 
      primary_is_camera || 
      primary_is_transparent ))
    return;
    
index_of_refraction = get_mat_ior();
vec3 refracted_direction = refract(direction, normal, index_of_refraction);
float F = pow(1.0 - n_dot_v, 5.0);
do_refraction = is_odd_checkerboard &amp;&amp; F &lt; 1;
direction = do_refraction ? refract() : reflect();
correction_factor *= 2; // 补能量
throughput *= correction_factor;
primary_medium = new_medium;//更新介质

int reflection_cull_mask = REFLECTION_RAY_CULL_MASK|xxx;

Ray reflection_ray;
reflection_ray.origin = position;
reflection_ray.direction = direction;

trace_geometry_ray(reflection_ray, backface_culling, reflection_cull_mask);
Triangle triangle;

if (found_intersection(ray_payload_geometry))
{
    reflection_ray.t_max = ray_payload_geometry.hit_distance;
    triangle = get_hit_triangle(ray_payload_geometry);
}

vec4 effects = trace_effects_ray(reflection_ray, /* skip_procedural = */ false);

// almost same with primary ray
...
// update gbuffer
</code></pre></div></div>

<p>asvgf_gradient_reproject.comp</p>

<p>direct_lighting.rgen// direct diffuse + direct sun shadow</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vec3 high_freq, specular;
direct_lighting(ipos, is_odd_checkerboard, high_freq, specular);

vec4 view_direction = texelFetch(TEX_PT_VIEW_DIRECTION, ipos, 0);
vec3 normal = decode_normal(texelFetch(TEX_PT_NORMAL_A, ipos, 0).x);
vec3 geo_normal = decode_normal(texelFetch(TEX_PT_GEO_NORMAL_A, ipos, 0).x);
vec4 primary_base_color = texelFetch(TEX_PT_BASE_COLOR_A, ipos, 0);
float primary_specular_factor = primary_base_color.a;
vec2 metal_rough = texelFetch(TEX_PT_METALLIC_A, ipos, 0).xy;
float primary_metallic = metal_rough.x;
float primary_roughness = metal_rough.y;
uint cluster_idx = texelFetch(TEX_PT_CLUSTER_A, ipos, 0).x;

vec3 primary_albedo, primary_base_reflectivity;
get_reflectivity(primary_base_color.rgb, primary_metallic, primary_albedo, primary_base_reflectivity);

// precompute phong coeff
float alpha = square(roughness);
float phong_exp = RoughnessSquareToSpecPower(alpha);
float phong_scale = min(100, 1 / (M_PI * square(alpha)));
float phong_weight = clamp(specular_factor * luminance(base_reflectivity) / (luminance(base_reflectivity) + luminance(albedo)), 0, 0.9);

/*
get_direct_illumination(
    position, 
    normal, 
    geo_normal, 
    cluster_idx, 
    material_id, 
    shadow_cull_mask, 
    view_direction.xyz, 
    primary_albedo,
    primary_base_reflectivity,
    primary_specular_factor,
    primary_roughness, 
    primary_medium, 
    spec_enable_caustics != 0, 
    direct_specular_weight, 
    global_ubo.pt_direct_polygon_lights &gt; 0,
    global_ubo.pt_direct_dyn_lights &gt; 0,
    is_gradient,
    0,
    direct_diffuse,
    direct_specular);
*/

//  sample a static light
// 1. 重要性采样：从很多 polygon lights 里选一个 light
// float m = spherical_tri_area(light.positions, p, n, V, phong_exp, phong_scale, phong_weight);
// float light_lum = luminance(light.color);
// m *= abs(light_lum);
// 2. 几何采样：在这个 light 的三角形上选一个点
sample_polygonal_lights(
    cluster_idx,
    position, 
    normal, 
    geo_normal, 
    view_direction, 
    phong_exp, 
    phong_scale,
    phong_weight, 
    is_gradient, 
    pos_on_light_polygonal, 
    contrib_polygonal,
    polygonal_light_index,
    polygonal_light_pdfw,
    polygonal_light_is_sky,
    rng);
    // Limit the solid angle of sphere lights for indirect lighting 
    // in order to kill some fireflies in locations with many sphere lights.
    // Example: green wall-lamp corridor in the "train" map.
    float max_solid_angle = (bounce == 0) ? 2 * M_PI : 0.02;

// sample a dynamic light
// dynamic lights 内部是在 num_dyn_lights 中 uniform 选一个 light，pdf = 1 / num_dyn_lights，
// sample_dynamic_lights 里会乘 num_dyn_lights 做 1/pdf 补偿；sphere/spot 的能量用 analytic irradiance 近似。
sample_dynamic_lights(
    position,
    normal,
    geo_normal,
    max_solid_angle,
    pos_on_light_dynamic,
    contrib_dynamic,
    rng);

float spec_polygonal = phong(normal, normalize(pos_on_light_polygonal - position), view_direction, phong_exp) * phong_scale;
float spec_dynamic = phong(normal, normalize(pos_on_light_dynamic - position), view_direction, phong_exp) * phong_scale;

// compute luminance of two light
float l_polygonal  = luminance(abs(contrib_polygonal)) * mix(1, spec_polygonal, phong_weight);
float l_dynamic = luminance(abs(contrib_dynamic)) * mix(1, spec_dynamic, phong_weight);
float l_sum = l_polygonal + l_dynamic;

bool null_light = (l_sum == 0);

float w = null_light ? 0.5 : l_polygonal / (l_polygonal + l_dynamic);

// random chose one, polygon or dynamic
float rng2 = get_rng(RNG_NEE_LIGHT_TYPE(bounce));
is_polygonal = (rng2 &lt; w);
vis = is_polygonal ? (1 / w) : (1 / (1 - w));
vec3 pos_on_light = null_light ? position : (is_polygonal ? pos_on_light_polygonal : pos_on_light_dynamic);
vec3 contrib = is_polygonal ? contrib_polygonal : contrib_dynamic;

Ray shadow_ray = get_shadow_ray(position - view_direction * 0.01, pos_on_light, 0);

vis *= trace_shadow_ray(shadow_ray, null_light ? 0 : shadow_cull_mask);

// TODO, Adaptive Shadow Testing for Ray Tracing, Ward 1994 optimization

vec3 radiance = vis * contrib;

vec3 L = pos_on_light - position;
L = normalize(L);

// specular lighting

if(is_polygonal &amp;&amp; direct_specular_weight &gt; 0 &amp;&amp; polygonal_light_is_sky &amp;&amp; global_ubo.pt_specular_mis != 0)
{
    // MIS with direct specular and indirect specular.
    // Only applied to sky lights, for two reasons:
    //  1) Non-sky lights are trimmed to match the light texture, and indirect rays don't see that;
    //  2) Non-sky lights are usually away from walls, so the direct sampling issue is not as pronounced.

    direct_specular_weight *= get_specular_sampled_lighting_weight(roughness,
        normal, -view_direction, L, polygonal_light_pdfw);
}

vec3 F = vec3(0);

if(vis &gt; 0 &amp;&amp; direct_specular_weight &gt; 0)
{
    vec3 specular_brdf = GGX_times_NdotL(view_direction, normalize(pos_on_light - position),
        normal, roughness, base_reflectivity, 0.0, specular_factor, F);
    specular = radiance * specular_brdf * direct_specular_weight;
}

float NdotL = max(0, dot(normal, L));

// diffuse lighting

float diffuse_brdf = NdotL / M_PI;
diffuse = radiance * diffuse_brdf * (vec3(1.0) - F);

high_freq += direct_diffuse;
o_specular += direct_specular;
/*
get_sunlight(
    cluster_idx,
    material_id,
    position,
    normal,
    geo_normal,
    view_direction.xyz,
    primary_base_reflectivity,
    primary_specular_factor,
    primary_roughness,
    primary_medium,
    spec_enable_caustics != 0,
    direct_sun_diffuse,
    direct_sun_specular,
    shadow_cull_mask);
*/
// similar with polygon/dynamic light computation

high_freq += direct_sun_diffuse;
o_specular += direct_sun_specular;

o_specular = demodulate_specular(primary_base_reflectivity, o_specular);

high_freq = clamp_output(high_freq);
o_specular = clamp_output(o_specular);

high_freq *= STORAGE_SCALE_HF;//32
o_specular *= STORAGE_SCALE_SPEC;//32
imageStore(IMG_PT_COLOR_LF_SH, ipos, vec4(0));
imageStore(IMG_PT_COLOR_LF_COCG, ipos, vec4(0));
imageStore(IMG_PT_COLOR_HF, ipos, uvec4(packRGBE(high_freq))); // diffuse
imageStore(IMG_PT_COLOR_SPEC, ipos, uvec4(packRGBE(o_specular))); // specular
</code></pre></div></div>

<p>indirect_lighting.rgen</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// already have primary ray hit surface into
view_direction = texelFetch(TEX_PT_VIEW_DIRECTION, ipos, 0);
normal = decode_normal(texelFetch(TEX_PT_NORMAL_A, ipos, 0).x);
geo_normal = decode_normal(texelFetch(TEX_PT_GEO_NORMAL_A, ipos, 0).x);
primary_base_color = texelFetch(TEX_PT_BASE_COLOR_A, ipos, 0);
primary_specular_factor = primary_base_color.a;
vec2 metal_rough = texelFetch(TEX_PT_METALLIC_A, ipos, 0).xy;
primary_metallic = metal_rough.x;
primary_roughness = metal_rough.y;

get_reflectivity(primary_base_color.rgb, primary_metallic, primary_albedo, primary_base_reflectivity);
float NoV = max(0, -dot(normal, view_direction.xyz));
// 判断光线类型
bool is_specular_ray;

// compute the indirect ray direction towards ggx reflection lobe
if(spec_bounce_index == 0)
{
    specular_pdf = (primary_metallic == 1 &amp;&amp; fake_specular_weight == 0) ? 1.0 : 0.5;
    
    // 50%概率进，specular path
    if(rng_frensel &lt; specular_pdf) 
    {
        mat3 basis = construct_ONB_frisvad(normal);

        // Sampling of normal distribution function to compute the reflected ray.
        // See the paper "Sampling the GGX Distribution of Visible Normals" by E. Heitz, 
        // Journal of Computer Graphics Techniques Vol. 7, No. 4, 2018.
        // http://jcgt.org/published/0007/04/01/paper.pdf 

        vec3 N = normal;
        vec3 V = view_direction.xyz;
        vec3 H = ImportanceSampleGGX_VNDF(rng3, primary_roughness, V, basis);
        vec3 L = reflect(V, H);

        float NoL = max(0, dot(N, L));
        float NoH = max(0, dot(N, H));
        float VoH = max(0, -dot(V, H));

        if (NoL &gt; 0 &amp;&amp; NoV &gt; 0)
        {
            // See the Heitz paper referenced above for the estimator explanation.
            //   (BRDF / PDF) = F * G2(V, L) / G1(V)
            // Assume G2 = G1(V) * G1(L) here and simplify that expression to just G1(L).
            
            float G1_NoL = G1_Smith(primary_roughness, NoL);
            vec3 F = schlick_fresnel(primary_base_reflectivity, VoH, primary_specular_factor);

            bounce_throughput *= G1_NoL * F;

            bounce_throughput *= 1 / specular_pdf;
            is_specular_ray = true;
            bounce_direction = normalize(L);
        }
    }
}
// 发射diffuse光线
if(!is_specular_ray)
{
    vec3 basis_normal, dir_sphere;
#if ENABLE_SH
    if(spec_bounce_index == 0 &amp;&amp; global_ubo.flt_enable != 0)
    {
        dir_sphere = sample_cos_hemisphere_multi(0, 1, rng3, HEMISPHERE_UNIFORMISH);
        basis_normal = geo_normal;
    }
    else
#endif
    {
        dir_sphere = sample_cos_hemisphere(rng3);
        basis_normal = normal;
    }

    mat3 basis = construct_ONB_frisvad(basis_normal);
    bounce_direction = normalize(basis * dir_sphere);
    // diffuse 和 specular 是互斥采样；这里除以选择 diffuse 的概率 (1 - specular_pdf) 做 1/pdf 补偿。
    bounce_throughput *= 1 / (1 - specular_pdf);

    vec3 L = bounce_direction.xyz;
    vec3 V = -view_direction.xyz;
    vec3 H = normalize(V + L);
    float VoH = max(0, dot(V, H));

    vec3 F = schlick_fresnel(primary_base_reflectivity, VoH, primary_specular_factor);

    bounce_throughput *= vec3(1.0) - F;
}

Ray bounce_ray;
bounce_ray.origin = position;
bounce_ray.direction = bounce_direction;
bounce_ray.t_min = 0;
bounce_ray.t_max = 10000;

trace_geometry_ray(bounce_ray, true, bounce_cull_mask);

// specular ray 再 trace 特效
if(is_specular_ray)
{
    if (found_intersection(ray_payload_geometry))
        bounce_ray.t_max = ray_payload_geometry.hit_distance;

    vec4 transparency = trace_effects_ray(bounce_ray, /* skip_procedural = */ true);
    bounce_contrib += transparency.rgb * transparency.a * bounce_throughput * (1.0 - direct_specular_weight);
}
Triangle triangle = get_hit_triangle(ray_payload_geometry);

// hit surface properties
vec3 bary         = get_hit_barycentric(ray_payload_geometry);
vec2 tex_coord    = triangle.tex_coords * bary;
uint bounce_material_id = triangle.material_id;
position;
normal;
geo_normal;
basecolor;
...

 vec3 emissive = sample_emissive_texture(triangle.material_id, bounce_minfo, tex_coord, vec2(0), vec2(0), is_specular_ray ? 2 : 3);
 emissive += get_emissive_shell(triangle.material_id, triangle.shell) * bounce_base_color;
 // other emissive login
 
 // 1 bounce gi
 vec3 bounce_diffuse, bounce_specular;
get_direct_illumination(
    bounce_position, 
    bounce_geo_normal, 
    bounce_geo_normal, 
    bounce_cluster_idx, 
    bounce_material_id, 
    shadow_cull_mask, 
    bounce_direction, 
    bounce_base_color,
    vec3(0), // base_reflectivity
    0.0, // specular_factor
    1.0, // roughness
    MEDIUM_NONE, 
    false, // enable_caustics
    0.0, // direct_specular_weight
    global_ubo.pt_indirect_polygon_lights &gt; 0,
    global_ubo.pt_indirect_dyn_lights &gt; 0,
    is_gradient,
    1, // bounce
    bounce_diffuse,
    bounce_specular);

bounce_contrib += bounce_throughput * bounce_diffuse;

imageStore(IMG_PT_GEO_NORMAL2, ipos, uvec4(encode_normal(bounce_geo_normal)));
imageStore(IMG_PT_SHADING_POSITION, ipos, vec4(bounce_position.xyz, uintBitsToFloat(triangle.material_id)));
imageStore(IMG_PT_VIEW_DIRECTION2, ipos, vec4(bounce_direction, 0));
imageStore(IMG_PT_BOUNCE_THROUGHPUT, ipos, vec4(bounce_throughput, is_specular_ray ? 1 : 0));

// denoise without f0
if (is_specular_ray)
    bounce_contrib = demodulate_specular(primary_base_reflectivity, bounce_contrib); 

if(is_specular_ray)
{
    bounce_contrib *= STORAGE_SCALE_SPEC;

    vec3 specular = unpackRGBE(imageLoad(IMG_PT_COLOR_SPEC, ipos).x);
    specular += bounce_contrib;
    imageStore(IMG_PT_COLOR_SPEC, ipos, uvec4(packRGBE(specular)));
}
else
{
    bounce_contrib *= STORAGE_SCALE_LF;

    SH low_freq = load_SH(TEX_PT_COLOR_LF_SH, TEX_PT_COLOR_LF_COCG, ipos);

#if ENABLE_SH
    if(global_ubo.flt_enable == 0)
        low_freq.shY.xyz += bounce_contrib;
    else
    {
        accumulate_SH(low_freq, irradiance_to_SH(bounce_contrib, bounce_direction), 1.0);
    }
#else
    low_freq.shY.xyz += bounce_contrib;
#endif

    STORE_SH(IMG_PT_COLOR_LF_SH, IMG_PT_COLOR_LF_COCG, ipos, low_freq);
}

</code></pre></div></div>

<p>总结</p>

<p>Diffuse GI 比较低频，Q2RTX 的 LF 通道不是完整 RGB SH，而是压缩成：</p>
<ul>
  <li>PT_COLOR_LF_SH：一阶 SH，也就是 L0 + L1 的 4 个系数，只存 Y/luma 的方向性。</li>
  <li>PT_COLOR_LF_COCG：存 Co/Cg 色度，不存方向性，近似为平均 tint。</li>
  <li>RGB 会先转到 YCoCg：Co = R - B，t = B + Co * 0.5，Cg = G - t，Y = t + Cg * 0.5。</li>
  <li>SH 写入形式是：result.CoCg = vec2(Co, Cg)，result.shY = vec4(L11, L1_1, L10, L00) * Y。</li>
  <li>后续 ASVGF 滤波的是 SH + CoCg 这个 lighting representation；normal/depth 不被滤波，但会作为 edge-aware guide 参与滤波权重。最终 composite 前再用当前像素 normal 调用 project_SH_irradiance(filtered_lf, normal)，把 LF SH 投影回 RGB irradiance。</li>
</ul>

<p>Checkerboard field 不是单纯半分辨率优化
Q2RTX 把最终屏幕的 checkerboard pixels de-interleave 到左右半屏：左半是 even field，右半是 odd field。这样每个 field 都是 dense image，便于 denoiser 做空间滤波；同时 reflection/refraction 可以分到不同 field，例如一半 field 走 reflection，一半 field 走 refraction。后续再用 checkerboard_interleave.comp 合回 flat image。</p>

<p>Reflect/Refract pass 是 specular guide path，不只是视觉反射
reflect_refract.rgen 会把水、玻璃、chrome、screen 等特殊材质后面看到的 secondary surface 写回 G-buffer，包括 position、normal、base color、material、visbuffer、motion/depth 等。这样后续 direct/indirect lighting 和 denoiser 看到的是“镜子/玻璃后面的表面”，而不是只有 primary glass/mirror surface。</p>

<p>Ray cone / texture LOD 是 secondary ray 质量关键
Primary pass 用相邻像素 primary ray 的夹角估计 half_cone_angle，secondary hit 时用 hit_distance * half_cone_angle 估算 footprint，再调用 compute_anisotropic_texture_gradients 计算纹理 LOD。否则反射/间接命中后的贴图采样会过锐、闪烁或 alias。</p>

<p>Path throughput 是跨 pass 的能量账本
IMG_PT_THROUGHPUT / IMG_PT_BOUNCE_THROUGHPUT 记录 reflection/refraction、medium extinction、Fresnel sampling correction、BRDF sampling correction 等路径权重。后续 lighting pass 算到的 radiance 都要乘这个 throughput 才是对 camera pixel 的贡献。</p>

<p>Specular demodulation 提高 denoiser 稳定性
SPEC channel 在写入前会用 demodulate_specular(base_reflectivity, specular) 除掉材质 F0/specular color，滤波后 composite 再用 modulate_specular 乘回去。这样 denoiser 处理的是更像“光照强度”的信号，而不是光照和金属颜色/贴图细节混在一起的结果。</p>

<p>One-sample NEE + 重要性采样，比遍历所有灯更适合实时
get_direct_illumination 每个 shading point 通常只打一条 shadow ray：先在 polygon lights 中 importance sample 一个候选，再 uniform sample 一个 dynamic light 候选，然后按贡献估计在 polygon/dynamic 之间二选一，并用 1/pdf 补偿。这样一个样本统计上代表整个候选灯集合。</p>

<p>Light shadow statistics 是低成本的下一帧采样反馈
Q2RTX 会统计每个 cluster / light / surface orientation 上 shadow ray 是 unshadowed 还是 shadowed，下一帧在 sample_polygonal_lights 里降低经常被挡住的灯的 mass，但保留下限避免完全不采。</p>

<p>Geometry TLAS 和 Effects TLAS 分离
Q2RTX 把真实几何和粒子、爆炸、sprite、beam 等 effects 放到不同 TLAS。Primary/secondary geometry ray 先找 surface，再用 effects ray 累积透明特效。这样普通 visibility 不必总是遍历 effects，也能给 effects 使用不同 hit shader / any-hit 逻辑。</p>

<p>Half-res GI profile 不是简单降分辨率，而是降低路径复杂度
pt_num_bounce_rays == 0.5 时，indirect pass 只在隔行像素上跑，并且默认不读取真实 metallic/roughness，等价于低质量 diffuse GI profile，避免半分辨率 specular 带来闪烁和错误重建。</p>

<p>Ray Query / RT Pipeline 双路径值得保留抽象边界
Q2RTX 同一套 rgen 逻辑会编译成 .pipeline.spv 和 .query.spv。RT pipeline 路径使用 SBT/hit shaders；Ray Query 路径则在 compute shader 内手动执行查询和 hit 逻辑。上层 pass 调度基本通过同一组 pipeline index 抽象。</p>]]></content><author><name></name></author><category term="ideas" /><summary type="html"><![CDATA[#define MATERIAL_KIND_MASK 0xf0000000 #define MATERIAL_KIND_INVALID 0x00000000 #define MATERIAL_KIND_REGULAR 0x10000000 #define MATERIAL_KIND_CHROME 0x20000000 #define MATERIAL_KIND_WATER 0x30000000 #define MATERIAL_KIND_LAVA 0x40000000 #define MATERIAL_KIND_SLIME 0x50000000 #define MATERIAL_KIND_GLASS 0x60000000 #define MATERIAL_KIND_SKY 0x70000000 #define MATERIAL_KIND_INVISIBLE 0x80000000 #define MATERIAL_KIND_EXPLOSION 0x90000000 #define MATERIAL_KIND_TRANSPARENT 0xa0000000 // Transparent walls. Have a distortion effect applied. #define MATERIAL_KIND_SCREEN 0xb0000000 #define MATERIAL_KIND_CAMERA 0xc0000000 #define MATERIAL_KIND_CHROME_MODEL 0xd0000000 #define MATERIAL_KIND_TRANSP_MODEL 0xe0000000 // Transparent models. No distortion, just "see through". struct RayPayloadGeometry { vec2 barycentric; /* two packed 16 bit integers, buffer index in low 16 bits and * instance index in high 16 bits */ int buffer_and_instance_idx; uint primitive_id; float hit_distance; }; struct RayPayloadEffects { uvec2 transparency; // half4x16 uint distances; // half2x16 - min and max uvec4 fog1; // half8x16: .xy = color.rgba; .z = t_min, t_max; .w = density: a and b for (a*t + b) uvec4 fog2; // same as fog1 but for a fog volume further away #ifndef KHR_RAY_QUERY // Store TMax in the payload because gl_RayTmaxEXT changes while the ray is being traced. // See the GLSL_EXT_ray_tracing spec near "description for gl_RayTminEXT and gl_RayTmaxEXT" // https://github.com/KhronosGroup/GLSL/blob/master/extensions/ext/GLSL_EXT_ray_tracing.txt float rayTmax; #endif }; layout(location = RT_PAYLOAD_GEOMETRY) rayPayloadEXT RayPayloadGeometry ray_payload_geometry; layout(location = RT_PAYLOAD_EFFECTS) rayPayloadEXT RayPayloadEffects ray_payload_effects; // primary ray vkpt_pt_trace_primary_rays(trace_cmd_buf); // qvkCmdTraceRaysKHR(cmd_buf, // &amp;raygen, // &amp;miss_and_hit, // &amp;miss_and_hit, // &amp;callable, // width/2, height, depth); // 2 depth for checkerboard rendering, split vkpt_submit_command_buffer(); // indirect reflection/refraction if (ref_mode.reflect_refract &gt; 0) vkpt_pt_trace_reflections(trace_cmd_buf, 0); // multiple reflection/refraction if (ref_mode.reflect_refract &gt; 1) for (int pass = 0; pass &lt; ref_mode.reflect_refract - 1; pass++) vkpt_pt_trace_reflections(trace_cmd_buf, pass + 1); // seperated svgf reprojected pass vkpt_asvgf_gradient_reproject(trace_cmd_buf); vkpt_pt_trace_lighting(trace_cmd_buf, ref_mode.num_bounce_rays); vkpt_submit_command_buffer(); vkpt_asvgf_filter(post_cmd_buf, cvar_pt_num_bounce_rays-&gt;value &gt;= 0.5f); vkpt_interleave(post_cmd_buf); vkpt_taa(post_cmd_buf); vkpt_bloom_record_cmd_buffer(post_cmd_buf); vkpt_tone_mapping_record_cmd_buffer(); vkpt_fsr_do(post_cmd_buf); vkpt_submit_command_buffer_simple(); primary_rays.rgen(path tracer overview的1) // generate primary ray information, including bias offset to get depth of field Ray ray = get_primary_ray(inUV); // primary ray -&gt; path_tracer.rchit/path_tracer.rmiss traceRayEXT( topLevelAS[TLAS_INDEX_GEOMETRY], rayFlags, instance_mask, SBT_RCHIT_GEOMETRY /*sbtRecordOffset*/, 0 /*sbtRecordStride*/, SBT_RMISS_EMPTY /*missIndex*/, ray.origin, ray.t_min, ray.direction, ray.t_max, RT_PAYLOAD_GEOMETRY); Triangle triangle; if (found_intersection(ray_payload_geometry)) // hit surface { ray.t_max = ray_payload_geometry.hit_distance; triangle = get_hit_triangle(ray_payload_geometry); } // particle/explosion/sprite/beam traceRayEXT( topLevelAS[TLAS_INDEX_EFFECTS], rayFlags, instance_mask, SBT_RCHIT_EFFECTS /*sbtRecordOffset*/, 0 /*sbtRecordStride*/, SBT_RMISS_EMPTY /*missIndex*/, ray.origin, ray.t_min, ray.direction, ray.t_max, RT_PAYLOAD_EFFECTS); vec4 effects = get_payload_transparency_with_fog(ray_payload_effects, ray.t_max); vec3 bary = get_hit_barycentric(ray_payload_geometry); // store 2 visibility buffer { uvec2 vis_buf; vis_buf.x = triangle.instance_index; vis_buf.y = triangle.instance_prim; imageStore(IMG_PT_VISBUF_PRIM_A, ipos, uvec4(vis_buf, 0, 0)); // rg32ui / R32G32_UINT imageStore(IMG_PT_VISBUF_BARY_A, ipos, vec4(bary.yz, 0, 0)); // rg16f / R16G16_SFLOAT } // get hit point information vec3 position = triangle.positions * bary; vec2 texcoord = triangle.texcoords * bary; vec3 geo_normal = triangle.normals* bary; vec3 flat_normal = normalize(cross( triangle.positions[1] - triangle.positions[0], triangle.positions[2] - triangle.positions[1])); /* compute view-space derivatives of depth and motion vectors */ Ray ray_0 = get_primary_ray(inUV); Ray ray_x = get_primary_ray(inUV + vec2(1.0 / float(global_ubo.width), 0)); Ray ray_y = get_primary_ray(inUV + vec2(0, 1.0 / float(global_ubo.height))); // larger coneangle means high gradient, means higher mips float half_cone_angle = sqrt(1.0 - square(min( dot(ray_0.direction, ray_x.direction), dot(ray_0.direction, ray_y.direction)))); vec2 tex_coord_x, tex_coord_y; float fwidth_depth; // get texure lod compute_anisotropic_texture_gradients(position, flat_normal, ray.direction, ray_payload_geometry.hit_distance * half_cone_angle, triangle.positions, triangle.tex_coords, tex_coord, tex_coord_x, tex_coord_y, fwidth_depth); vec3 pos_ws_curr = position; vec3 pos_ws_prev = triangle.positions_prev * bary; vec2 screen_pos_curr, screen_pos_prev; float distance_curr, distance_prev; projection_view_to_screen((global_ubo.V * vec4(pos_ws_curr, 1)).xyz, screen_pos_curr, distance_curr, false); projection_view_to_screen((global_ubo.V_prev * vec4(pos_ws_prev, 1)).xyz, screen_pos_prev, distance_prev, true); // motion vector vec3 motion; motion.xy = screen_pos_prev - screen_pos_curr; motion.z = distance_prev - distance_curr; imageStore(IMG_PT_VIEW_DEPTH_A, ipos, vec4(distance_curr)); imageStore(IMG_PT_MOTION, ipos, vec4(motion, fwidth_depth)); // Get the primary surface material parameters get_material( triangle, bary, tex_coord, tex_coord_x, tex_coord_y, -1, geo_normal, primary_base_color, normal, primary_metallic, primary_roughness, primary_emissive, primary_specular_factor); // get mat id uint material_id = triangle.material_id; ... // handle various material one by one // write to gbuffer // shading normal imageStore(IMG_PT_NORMAL_A, ipos, uvec4(encode_normal(normal))); // geo normal imageStore(IMG_PT_GEO_NORMAL_A, ipos, uvec4(encode_normal(geo_normal))); //... imageStore(IMG_PT_SHADING_POSITION, ipos, vec4(position.xyz, uintBitsToFloat(material_id))); //... imageStore(IMG_PT_VIEW_DIRECTION, ipos, vec4(direction, float(checkerboard_flags))); imageStore(IMG_PT_THROUGHPUT, ipos, vec4(throughput, distance_curr)); imageStore(IMG_PT_BOUNCE_THROUGHPUT, ipos, vec4(1, 1, 1, half_cone_angle)); imageStore(IMG_PT_CLUSTER_A, ipos, ivec4(triangle.cluster)); imageStore(IMG_PT_BASE_COLOR_A, ipos, vec4(primary_base_color, primary_specular_factor)); imageStore(IMG_PT_METALLIC_A, ipos, vec4(primary_metallic, primary_roughness, 0, 0)); imageStore(IMG_PT_GODRAYS_THROUGHPUT_DIST, ipos, vec4(1, 1, 1, distance_curr)); transparent = alpha_blend_premultiplied(effects, transparent); imageStore(IMG_PT_TRANSPARENT, ipos, transparent); reflect_refract.rgen reflect_refract.rgen 会在 G-buffer 当前 surface 是 water / slime / glass / chrome / screen / camera / transparent 等特殊材质时，每像素沿 reflection 或 refraction 方向继续追一条 ray，并用命中的 secondary surface 更新 G-buffer / throughput / medium / motion。下面的 IOR + checkerboard 代码是抽象伪码；真实代码会按 material kind 分支处理 thin/thick glass、water/slime medium、total internal reflection、chrome/screen 只反射、transparent see-through 等情况。 // get shading pos vec4 position_material = imageLoad(IMG_PT_SHADING_POSITION, ipos); if(!( primary_is_water || primary_is_slime || primary_is_glass || primary_is_chrome || primary_is_screen || primary_is_camera || primary_is_transparent )) return; index_of_refraction = get_mat_ior(); vec3 refracted_direction = refract(direction, normal, index_of_refraction); float F = pow(1.0 - n_dot_v, 5.0); do_refraction = is_odd_checkerboard &amp;&amp; F &lt; 1; direction = do_refraction ? refract() : reflect(); correction_factor *= 2; // 补能量 throughput *= correction_factor; primary_medium = new_medium;//更新介质 int reflection_cull_mask = REFLECTION_RAY_CULL_MASK|xxx; Ray reflection_ray; reflection_ray.origin = position; reflection_ray.direction = direction; trace_geometry_ray(reflection_ray, backface_culling, reflection_cull_mask); Triangle triangle; if (found_intersection(ray_payload_geometry)) { reflection_ray.t_max = ray_payload_geometry.hit_distance; triangle = get_hit_triangle(ray_payload_geometry); } vec4 effects = trace_effects_ray(reflection_ray, /* skip_procedural = */ false); // almost same with primary ray ... // update gbuffer asvgf_gradient_reproject.comp direct_lighting.rgen// direct diffuse + direct sun shadow vec3 high_freq, specular; direct_lighting(ipos, is_odd_checkerboard, high_freq, specular); vec4 view_direction = texelFetch(TEX_PT_VIEW_DIRECTION, ipos, 0); vec3 normal = decode_normal(texelFetch(TEX_PT_NORMAL_A, ipos, 0).x); vec3 geo_normal = decode_normal(texelFetch(TEX_PT_GEO_NORMAL_A, ipos, 0).x); vec4 primary_base_color = texelFetch(TEX_PT_BASE_COLOR_A, ipos, 0); float primary_specular_factor = primary_base_color.a; vec2 metal_rough = texelFetch(TEX_PT_METALLIC_A, ipos, 0).xy; float primary_metallic = metal_rough.x; float primary_roughness = metal_rough.y; uint cluster_idx = texelFetch(TEX_PT_CLUSTER_A, ipos, 0).x; vec3 primary_albedo, primary_base_reflectivity; get_reflectivity(primary_base_color.rgb, primary_metallic, primary_albedo, primary_base_reflectivity); // precompute phong coeff float alpha = square(roughness); float phong_exp = RoughnessSquareToSpecPower(alpha); float phong_scale = min(100, 1 / (M_PI * square(alpha))); float phong_weight = clamp(specular_factor * luminance(base_reflectivity) / (luminance(base_reflectivity) + luminance(albedo)), 0, 0.9); /* get_direct_illumination( position, normal, geo_normal, cluster_idx, material_id, shadow_cull_mask, view_direction.xyz, primary_albedo, primary_base_reflectivity, primary_specular_factor, primary_roughness, primary_medium, spec_enable_caustics != 0, direct_specular_weight, global_ubo.pt_direct_polygon_lights &gt; 0, global_ubo.pt_direct_dyn_lights &gt; 0, is_gradient, 0, direct_diffuse, direct_specular); */ // sample a static light // 1. 重要性采样：从很多 polygon lights 里选一个 light // float m = spherical_tri_area(light.positions, p, n, V, phong_exp, phong_scale, phong_weight); // float light_lum = luminance(light.color); // m *= abs(light_lum); // 2. 几何采样：在这个 light 的三角形上选一个点 sample_polygonal_lights( cluster_idx, position, normal, geo_normal, view_direction, phong_exp, phong_scale, phong_weight, is_gradient, pos_on_light_polygonal, contrib_polygonal, polygonal_light_index, polygonal_light_pdfw, polygonal_light_is_sky, rng); // Limit the solid angle of sphere lights for indirect lighting // in order to kill some fireflies in locations with many sphere lights. // Example: green wall-lamp corridor in the "train" map. float max_solid_angle = (bounce == 0) ? 2 * M_PI : 0.02; // sample a dynamic light // dynamic lights 内部是在 num_dyn_lights 中 uniform 选一个 light，pdf = 1 / num_dyn_lights， // sample_dynamic_lights 里会乘 num_dyn_lights 做 1/pdf 补偿；sphere/spot 的能量用 analytic irradiance 近似。 sample_dynamic_lights( position, normal, geo_normal, max_solid_angle, pos_on_light_dynamic, contrib_dynamic, rng); float spec_polygonal = phong(normal, normalize(pos_on_light_polygonal - position), view_direction, phong_exp) * phong_scale; float spec_dynamic = phong(normal, normalize(pos_on_light_dynamic - position), view_direction, phong_exp) * phong_scale; // compute luminance of two light float l_polygonal = luminance(abs(contrib_polygonal)) * mix(1, spec_polygonal, phong_weight); float l_dynamic = luminance(abs(contrib_dynamic)) * mix(1, spec_dynamic, phong_weight); float l_sum = l_polygonal + l_dynamic; bool null_light = (l_sum == 0); float w = null_light ? 0.5 : l_polygonal / (l_polygonal + l_dynamic); // random chose one, polygon or dynamic float rng2 = get_rng(RNG_NEE_LIGHT_TYPE(bounce)); is_polygonal = (rng2 &lt; w); vis = is_polygonal ? (1 / w) : (1 / (1 - w)); vec3 pos_on_light = null_light ? position : (is_polygonal ? pos_on_light_polygonal : pos_on_light_dynamic); vec3 contrib = is_polygonal ? contrib_polygonal : contrib_dynamic; Ray shadow_ray = get_shadow_ray(position - view_direction * 0.01, pos_on_light, 0); vis *= trace_shadow_ray(shadow_ray, null_light ? 0 : shadow_cull_mask); // TODO, Adaptive Shadow Testing for Ray Tracing, Ward 1994 optimization vec3 radiance = vis * contrib; vec3 L = pos_on_light - position; L = normalize(L); // specular lighting if(is_polygonal &amp;&amp; direct_specular_weight &gt; 0 &amp;&amp; polygonal_light_is_sky &amp;&amp; global_ubo.pt_specular_mis != 0) { // MIS with direct specular and indirect specular. // Only applied to sky lights, for two reasons: // 1) Non-sky lights are trimmed to match the light texture, and indirect rays don't see that; // 2) Non-sky lights are usually away from walls, so the direct sampling issue is not as pronounced. direct_specular_weight *= get_specular_sampled_lighting_weight(roughness, normal, -view_direction, L, polygonal_light_pdfw); } vec3 F = vec3(0); if(vis &gt; 0 &amp;&amp; direct_specular_weight &gt; 0) { vec3 specular_brdf = GGX_times_NdotL(view_direction, normalize(pos_on_light - position), normal, roughness, base_reflectivity, 0.0, specular_factor, F); specular = radiance * specular_brdf * direct_specular_weight; } float NdotL = max(0, dot(normal, L)); // diffuse lighting float diffuse_brdf = NdotL / M_PI; diffuse = radiance * diffuse_brdf * (vec3(1.0) - F); high_freq += direct_diffuse; o_specular += direct_specular; /* get_sunlight( cluster_idx, material_id, position, normal, geo_normal, view_direction.xyz, primary_base_reflectivity, primary_specular_factor, primary_roughness, primary_medium, spec_enable_caustics != 0, direct_sun_diffuse, direct_sun_specular, shadow_cull_mask); */ // similar with polygon/dynamic light computation high_freq += direct_sun_diffuse; o_specular += direct_sun_specular; o_specular = demodulate_specular(primary_base_reflectivity, o_specular); high_freq = clamp_output(high_freq); o_specular = clamp_output(o_specular); high_freq *= STORAGE_SCALE_HF;//32 o_specular *= STORAGE_SCALE_SPEC;//32 imageStore(IMG_PT_COLOR_LF_SH, ipos, vec4(0)); imageStore(IMG_PT_COLOR_LF_COCG, ipos, vec4(0)); imageStore(IMG_PT_COLOR_HF, ipos, uvec4(packRGBE(high_freq))); // diffuse imageStore(IMG_PT_COLOR_SPEC, ipos, uvec4(packRGBE(o_specular))); // specular indirect_lighting.rgen // already have primary ray hit surface into view_direction = texelFetch(TEX_PT_VIEW_DIRECTION, ipos, 0); normal = decode_normal(texelFetch(TEX_PT_NORMAL_A, ipos, 0).x); geo_normal = decode_normal(texelFetch(TEX_PT_GEO_NORMAL_A, ipos, 0).x); primary_base_color = texelFetch(TEX_PT_BASE_COLOR_A, ipos, 0); primary_specular_factor = primary_base_color.a; vec2 metal_rough = texelFetch(TEX_PT_METALLIC_A, ipos, 0).xy; primary_metallic = metal_rough.x; primary_roughness = metal_rough.y; get_reflectivity(primary_base_color.rgb, primary_metallic, primary_albedo, primary_base_reflectivity); float NoV = max(0, -dot(normal, view_direction.xyz)); // 判断光线类型 bool is_specular_ray; // compute the indirect ray direction towards ggx reflection lobe if(spec_bounce_index == 0) { specular_pdf = (primary_metallic == 1 &amp;&amp; fake_specular_weight == 0) ? 1.0 : 0.5; // 50%概率进，specular path if(rng_frensel &lt; specular_pdf) { mat3 basis = construct_ONB_frisvad(normal); // Sampling of normal distribution function to compute the reflected ray. // See the paper "Sampling the GGX Distribution of Visible Normals" by E. Heitz, // Journal of Computer Graphics Techniques Vol. 7, No. 4, 2018. // http://jcgt.org/published/0007/04/01/paper.pdf vec3 N = normal; vec3 V = view_direction.xyz; vec3 H = ImportanceSampleGGX_VNDF(rng3, primary_roughness, V, basis); vec3 L = reflect(V, H); float NoL = max(0, dot(N, L)); float NoH = max(0, dot(N, H)); float VoH = max(0, -dot(V, H)); if (NoL &gt; 0 &amp;&amp; NoV &gt; 0) { // See the Heitz paper referenced above for the estimator explanation. // (BRDF / PDF) = F * G2(V, L) / G1(V) // Assume G2 = G1(V) * G1(L) here and simplify that expression to just G1(L). float G1_NoL = G1_Smith(primary_roughness, NoL); vec3 F = schlick_fresnel(primary_base_reflectivity, VoH, primary_specular_factor); bounce_throughput *= G1_NoL * F; bounce_throughput *= 1 / specular_pdf; is_specular_ray = true; bounce_direction = normalize(L); } } } // 发射diffuse光线 if(!is_specular_ray) { vec3 basis_normal, dir_sphere; #if ENABLE_SH if(spec_bounce_index == 0 &amp;&amp; global_ubo.flt_enable != 0) { dir_sphere = sample_cos_hemisphere_multi(0, 1, rng3, HEMISPHERE_UNIFORMISH); basis_normal = geo_normal; } else #endif { dir_sphere = sample_cos_hemisphere(rng3); basis_normal = normal; } mat3 basis = construct_ONB_frisvad(basis_normal); bounce_direction = normalize(basis * dir_sphere); // diffuse 和 specular 是互斥采样；这里除以选择 diffuse 的概率 (1 - specular_pdf) 做 1/pdf 补偿。 bounce_throughput *= 1 / (1 - specular_pdf); vec3 L = bounce_direction.xyz; vec3 V = -view_direction.xyz; vec3 H = normalize(V + L); float VoH = max(0, dot(V, H)); vec3 F = schlick_fresnel(primary_base_reflectivity, VoH, primary_specular_factor); bounce_throughput *= vec3(1.0) - F; } Ray bounce_ray; bounce_ray.origin = position; bounce_ray.direction = bounce_direction; bounce_ray.t_min = 0; bounce_ray.t_max = 10000; trace_geometry_ray(bounce_ray, true, bounce_cull_mask); // specular ray 再 trace 特效 if(is_specular_ray) { if (found_intersection(ray_payload_geometry)) bounce_ray.t_max = ray_payload_geometry.hit_distance; vec4 transparency = trace_effects_ray(bounce_ray, /* skip_procedural = */ true); bounce_contrib += transparency.rgb * transparency.a * bounce_throughput * (1.0 - direct_specular_weight); } Triangle triangle = get_hit_triangle(ray_payload_geometry); // hit surface properties vec3 bary = get_hit_barycentric(ray_payload_geometry); vec2 tex_coord = triangle.tex_coords * bary; uint bounce_material_id = triangle.material_id; position; normal; geo_normal; basecolor; ... vec3 emissive = sample_emissive_texture(triangle.material_id, bounce_minfo, tex_coord, vec2(0), vec2(0), is_specular_ray ? 2 : 3); emissive += get_emissive_shell(triangle.material_id, triangle.shell) * bounce_base_color; // other emissive login // 1 bounce gi vec3 bounce_diffuse, bounce_specular; get_direct_illumination( bounce_position, bounce_geo_normal, bounce_geo_normal, bounce_cluster_idx, bounce_material_id, shadow_cull_mask, bounce_direction, bounce_base_color, vec3(0), // base_reflectivity 0.0, // specular_factor 1.0, // roughness MEDIUM_NONE, false, // enable_caustics 0.0, // direct_specular_weight global_ubo.pt_indirect_polygon_lights &gt; 0, global_ubo.pt_indirect_dyn_lights &gt; 0, is_gradient, 1, // bounce bounce_diffuse, bounce_specular); bounce_contrib += bounce_throughput * bounce_diffuse; imageStore(IMG_PT_GEO_NORMAL2, ipos, uvec4(encode_normal(bounce_geo_normal))); imageStore(IMG_PT_SHADING_POSITION, ipos, vec4(bounce_position.xyz, uintBitsToFloat(triangle.material_id))); imageStore(IMG_PT_VIEW_DIRECTION2, ipos, vec4(bounce_direction, 0)); imageStore(IMG_PT_BOUNCE_THROUGHPUT, ipos, vec4(bounce_throughput, is_specular_ray ? 1 : 0)); // denoise without f0 if (is_specular_ray) bounce_contrib = demodulate_specular(primary_base_reflectivity, bounce_contrib); if(is_specular_ray) { bounce_contrib *= STORAGE_SCALE_SPEC; vec3 specular = unpackRGBE(imageLoad(IMG_PT_COLOR_SPEC, ipos).x); specular += bounce_contrib; imageStore(IMG_PT_COLOR_SPEC, ipos, uvec4(packRGBE(specular))); } else { bounce_contrib *= STORAGE_SCALE_LF; SH low_freq = load_SH(TEX_PT_COLOR_LF_SH, TEX_PT_COLOR_LF_COCG, ipos); #if ENABLE_SH if(global_ubo.flt_enable == 0) low_freq.shY.xyz += bounce_contrib; else { accumulate_SH(low_freq, irradiance_to_SH(bounce_contrib, bounce_direction), 1.0); } #else low_freq.shY.xyz += bounce_contrib; #endif STORE_SH(IMG_PT_COLOR_LF_SH, IMG_PT_COLOR_LF_COCG, ipos, low_freq); } 总结 Diffuse GI 比较低频，Q2RTX 的 LF 通道不是完整 RGB SH，而是压缩成： PT_COLOR_LF_SH：一阶 SH，也就是 L0 + L1 的 4 个系数，只存 Y/luma 的方向性。 PT_COLOR_LF_COCG：存 Co/Cg 色度，不存方向性，近似为平均 tint。 RGB 会先转到 YCoCg：Co = R - B，t = B + Co * 0.5，Cg = G - t，Y = t + Cg * 0.5。 SH 写入形式是：result.CoCg = vec2(Co, Cg)，result.shY = vec4(L11, L1_1, L10, L00) * Y。 后续 ASVGF 滤波的是 SH + CoCg 这个 lighting representation；normal/depth 不被滤波，但会作为 edge-aware guide 参与滤波权重。最终 composite 前再用当前像素 normal 调用 project_SH_irradiance(filtered_lf, normal)，把 LF SH 投影回 RGB irradiance。 Checkerboard field 不是单纯半分辨率优化 Q2RTX 把最终屏幕的 checkerboard pixels de-interleave 到左右半屏：左半是 even field，右半是 odd field。这样每个 field 都是 dense image，便于 denoiser 做空间滤波；同时 reflection/refraction 可以分到不同 field，例如一半 field 走 reflection，一半 field 走 refraction。后续再用 checkerboard_interleave.comp 合回 flat image。 Reflect/Refract pass 是 specular guide path，不只是视觉反射 reflect_refract.rgen 会把水、玻璃、chrome、screen 等特殊材质后面看到的 secondary surface 写回 G-buffer，包括 position、normal、base color、material、visbuffer、motion/depth 等。这样后续 direct/indirect lighting 和 denoiser 看到的是“镜子/玻璃后面的表面”，而不是只有 primary glass/mirror surface。 Ray cone / texture LOD 是 secondary ray 质量关键 Primary pass 用相邻像素 primary ray 的夹角估计 half_cone_angle，secondary hit 时用 hit_distance * half_cone_angle 估算 footprint，再调用 compute_anisotropic_texture_gradients 计算纹理 LOD。否则反射/间接命中后的贴图采样会过锐、闪烁或 alias。 Path throughput 是跨 pass 的能量账本 IMG_PT_THROUGHPUT / IMG_PT_BOUNCE_THROUGHPUT 记录 reflection/refraction、medium extinction、Fresnel sampling correction、BRDF sampling correction 等路径权重。后续 lighting pass 算到的 radiance 都要乘这个 throughput 才是对 camera pixel 的贡献。 Specular demodulation 提高 denoiser 稳定性 SPEC channel 在写入前会用 demodulate_specular(base_reflectivity, specular) 除掉材质 F0/specular color，滤波后 composite 再用 modulate_specular 乘回去。这样 denoiser 处理的是更像“光照强度”的信号，而不是光照和金属颜色/贴图细节混在一起的结果。 One-sample NEE + 重要性采样，比遍历所有灯更适合实时 get_direct_illumination 每个 shading point 通常只打一条 shadow ray：先在 polygon lights 中 importance sample 一个候选，再 uniform sample 一个 dynamic light 候选，然后按贡献估计在 polygon/dynamic 之间二选一，并用 1/pdf 补偿。这样一个样本统计上代表整个候选灯集合。 Light shadow statistics 是低成本的下一帧采样反馈 Q2RTX 会统计每个 cluster / light / surface orientation 上 shadow ray 是 unshadowed 还是 shadowed，下一帧在 sample_polygonal_lights 里降低经常被挡住的灯的 mass，但保留下限避免完全不采。 Geometry TLAS 和 Effects TLAS 分离 Q2RTX 把真实几何和粒子、爆炸、sprite、beam 等 effects 放到不同 TLAS。Primary/secondary geometry ray 先找 surface，再用 effects ray 累积透明特效。这样普通 visibility 不必总是遍历 effects，也能给 effects 使用不同 hit shader / any-hit 逻辑。 Half-res GI profile 不是简单降分辨率，而是降低路径复杂度 pt_num_bounce_rays == 0.5 时，indirect pass 只在隔行像素上跑，并且默认不读取真实 metallic/roughness，等价于低质量 diffuse GI profile，避免半分辨率 specular 带来闪烁和错误重建。 Ray Query / RT Pipeline 双路径值得保留抽象边界 Q2RTX 同一套 rgen 逻辑会编译成 .pipeline.spv 和 .query.spv。RT pipeline 路径使用 SBT/hit shaders；Ray Query 路径则在 compute shader 内手动执行查询和 hit 逻辑。上层 pass 调度基本通过同一组 pipeline index 抽象。]]></summary></entry><entry><title type="html">SVGF</title><link href="https://penantumbra.github.io/svgf/" rel="alternate" type="text/html" title="SVGF" /><published>2026-07-02T00:00:00+00:00</published><updated>2026-07-02T00:00:00+00:00</updated><id>https://penantumbra.github.io/svgf</id><content type="html" xml:base="https://penantumbra.github.io/svgf/"><![CDATA[<h2 id="svgf">SVGF</h2>

<h3 id="demodulation">Demodulation</h3>

<p>计算光照时忽略 BRDF 中的材质信息，避免引入高频变化。以 diffuse 为例：</p>

\[\text{diffuse} = L \cdot \rho \cdot n \cdot l / \pi\]

\[\text{demodulate albedo} = L \cdot n \cdot l / \pi\]

<h3 id="temporal-accumulation">Temporal Accumulation</h3>

<p>和 TAA 的重投影类似，通过深度、法线和 Mesh ID 来 reject。</p>

<h3 id="variance-esitimation">Variance Esitimation</h3>

<p>在时间上积累像素亮度的一阶矩和二阶矩 $\mu_1$、$\mu_2$。</p>

<p>计算方差：</p>

\[\operatorname{Var} = \mu_2 - \mu_1^2\]

<h3 id="edge-avoiding-atrous-wavelets">Edge-Avoiding Atrous Wavelets</h3>

<p>Wavelet filter 用于大范围滤波。法线和深度作为 edge avoiding 算法的输入，避免模糊掉几何边缘。</p>

\[\hat{c}_{i+1}(p)
=
\frac{
    \sum_{q \in \Omega}
    h(q)\, w(p,q)\, \hat{c}_i(q)
}{
    \sum_{q \in \Omega}
    h(q)\, w(p,q)
}\]

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vec3 sum = vec3(0);
float weight_sum = 0;

for q in neighborhood:
    float weight = wavelet_kernel(q) // atrous wavelelt
                 * depth_weight(p, q) // edge stopping
                 * normal_weight(p, q)
                 * luminance_weight(p, q);

    sum += weight * color[q];
    weight_sum += weight;

color_out[p] = sum / weight_sum;
</code></pre></div></div>

<blockquote>
  <p>墙壁的几何边缘不会被模糊掉。</p>
</blockquote>

<h3 id="luminance-edge-stopping-function">Luminance Edge Stopping Function</h3>

<p>通过上面计算的 variance，避免模糊掉阴影细节：</p>

\[w(p,q)
=
\exp\left(
    -
    \frac{
        \left| l_i(p) - l_i(q) \right|
    }{
        \sqrt{
            g_{3 \times 3}\left(
                \operatorname{Var}\left(l_i(p)\right)
            \right)
        }
    }
\right)\]

<ul>
  <li>Variance 大 → 噪声多 → 增大模糊，降低噪点。</li>
  <li>Variance 小 → 噪声小 → 减小模糊，保留细节。</li>
</ul>

<p>不过由于 filter 中对 variance 提前做了一遍高斯模糊来降低空域的噪声，一些阴影的细节会出现被模糊的情况。</p>

<blockquote>
  <p>阴影区域不会被模糊掉。</p>
</blockquote>

<h2 id="asvgf">ASVGF</h2>

<p>ASVGF 解决拖影和细节丢失问题，生成一张 temporal gradient 图，估计当前帧和历史帧的变化梯度。</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>asvgf_gradient_reproject.comp
    -&gt; 生成 gradient sample positions
path tracer
    -&gt; 对这些位置产生 gradient samples
asvgf_gradient_img.comp
    -&gt; 根据当前/历史亮度差生成 gradient image
asvgf_gradient_atrous.comp
    -&gt; 把稀疏 gradient 扩散成可用的低分辨率 gradient field
asvgf_temporal.comp
    -&gt; 读取 gradient，做 anti-lag
</code></pre></div></div>

<h3 id="temporal-accumulation--antilag">Temporal Accumulation &amp; AntiLag</h3>

<p>以 primary ray HF 为例，权重 alpha 受 temporal gradient 的变化影响：</p>

<div class="language-glsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span><span class="p">(</span><span class="n">temporal_sample_valid_diff</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// Compute the antilag factors based on the gradients</span>
    <span class="kt">float</span> <span class="n">antilag_alpha_hf</span> <span class="o">=</span> <span class="n">clamp</span><span class="p">(</span><span class="n">mix</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="n">global_ubo</span><span class="p">.</span><span class="n">flt_antilag_hf</span> <span class="o">*</span> <span class="n">grad_hf_spec</span><span class="p">.</span><span class="n">x</span><span class="p">,</span> <span class="n">global_ubo</span><span class="p">.</span><span class="n">flt_temporal_hf</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">);</span>

    <span class="c1">// Adjust the history length, taking the antilag factors into account</span>
    <span class="c1">// gradient大，hist_len_hf小，历史帧越容易被丢弃</span>
    <span class="kt">float</span> <span class="n">hist_len_hf</span> <span class="o">=</span> <span class="n">min</span><span class="p">(</span><span class="n">temporal_moments_histlen_hf</span><span class="p">.</span><span class="n">b</span> <span class="o">*</span> <span class="n">pow</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="mi">0</span> <span class="o">-</span> <span class="n">antilag_alpha_hf</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="mi">256</span><span class="p">.</span><span class="mi">0</span><span class="p">);</span>

    <span class="c1">// Compute the blending weights based on history length, so that the filter</span>
    <span class="c1">// converges faster. I.e. the first frame has weight of 1.0, the second frame 1/2, third 1/3 and so on.</span>
    <span class="kt">float</span> <span class="n">alpha_color_hf</span> <span class="o">=</span> <span class="n">max</span><span class="p">(</span><span class="n">global_ubo</span><span class="p">.</span><span class="n">flt_min_alpha_color_hf</span><span class="p">,</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span> <span class="o">/</span> <span class="n">hist_len_hf</span><span class="p">);</span>
    <span class="kt">float</span> <span class="n">alpha_moments_hf</span> <span class="o">=</span> <span class="n">max</span><span class="p">(</span><span class="n">global_ubo</span><span class="p">.</span><span class="n">flt_min_alpha_moments_hf</span><span class="p">,</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span> <span class="o">/</span> <span class="n">hist_len_hf</span><span class="p">);</span>

    <span class="c1">// Adjust the blending factors, taking the antilag factors into account again</span>
    <span class="n">alpha_color_hf</span> <span class="o">=</span> <span class="n">mix</span><span class="p">(</span><span class="n">alpha_color_hf</span><span class="p">,</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="n">antilag_alpha_hf</span><span class="p">);</span>
    <span class="n">alpha_moments_hf</span> <span class="o">=</span> <span class="n">mix</span><span class="p">(</span><span class="n">alpha_moments_hf</span><span class="p">,</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="n">antilag_alpha_hf</span><span class="p">);</span>

    <span class="c1">// Blend!</span>
    <span class="n">out_color_hf</span><span class="p">.</span><span class="n">rgb</span> <span class="o">=</span> <span class="n">mix</span><span class="p">(</span><span class="n">temporal_color_hf</span><span class="p">.</span><span class="n">rgb</span><span class="p">,</span> <span class="n">color_curr_hf</span><span class="p">.</span><span class="n">rgb</span><span class="p">,</span> <span class="n">alpha_color_hf</span><span class="p">);</span>

    <span class="n">out_moments_histlen_hf</span><span class="p">.</span><span class="n">rg</span> <span class="o">=</span> <span class="n">mix</span><span class="p">(</span><span class="n">temporal_moments_histlen_hf</span><span class="p">.</span><span class="n">rg</span><span class="p">,</span> <span class="n">spatial_moments_hf</span><span class="p">.</span><span class="n">rg</span><span class="p">,</span> <span class="n">alpha_moments_hf</span><span class="p">);</span>
    <span class="n">out_moments_histlen_hf</span><span class="p">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">hist_len_hf</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="q2rtx-impl">q2rtx impl</h3>

<p>在 G-Buffer 生成后，一个 compute shader pass reproject 到上一帧生成：</p>

<div class="language-glsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">imageStore</span><span class="p">(</span><span class="n">IMG_ASVGF_GRAD_SMPL_POS_A</span><span class="p">,</span> <span class="n">pos_grad</span><span class="p">,</span> <span class="kt">uvec4</span><span class="p">(</span><span class="n">gradient_idx</span><span class="p">));</span>

<span class="n">imageStore</span><span class="p">(</span><span class="n">IMG_ASVGF_GRAD_HF_SPEC_PING</span><span class="p">,</span> <span class="n">pos_grad</span><span class="p">,</span> <span class="kt">vec4</span><span class="p">(</span><span class="n">found_prev_lum</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">));</span>

<span class="n">imageStore</span><span class="p">(</span><span class="n">IMG_ASVGF_RNG_SEED_A</span><span class="p">,</span> <span class="n">ipos</span><span class="p">,</span> <span class="n">texelFetch</span><span class="p">(</span><span class="n">TEX_ASVGF_RNG_SEED_B</span><span class="p">,</span> <span class="n">found_pos_prev</span><span class="p">,</span> <span class="mi">0</span><span class="p">));</span>
<span class="n">imageStore</span><span class="p">(</span><span class="n">IMG_PT_NORMAL_A</span><span class="p">,</span> <span class="n">ipos</span><span class="p">,</span> <span class="n">texelFetch</span><span class="p">(</span><span class="n">TEX_PT_NORMAL_B</span><span class="p">,</span> <span class="n">found_pos_prev</span><span class="p">,</span> <span class="mi">0</span><span class="p">));</span>
<span class="n">imageStore</span><span class="p">(</span><span class="n">IMG_PT_BASE_COLOR_A</span><span class="p">,</span> <span class="n">ipos</span><span class="p">,</span> <span class="n">texelFetch</span><span class="p">(</span><span class="n">TEX_PT_BASE_COLOR_B</span><span class="p">,</span> <span class="n">found_pos_prev</span><span class="p">,</span> <span class="mi">0</span><span class="p">));</span>
<span class="n">imageStore</span><span class="p">(</span><span class="n">IMG_PT_METALLIC_A</span><span class="p">,</span> <span class="n">ipos</span><span class="p">,</span> <span class="n">texelFetch</span><span class="p">(</span><span class="n">TEX_PT_METALLIC_B</span><span class="p">,</span> <span class="n">found_pos_prev</span><span class="p">,</span> <span class="mi">0</span><span class="p">));</span>
</code></pre></div></div>]]></content><author><name></name></author><category term="ideas" /><summary type="html"><![CDATA[SVGF Demodulation 计算光照时忽略 BRDF 中的材质信息，避免引入高频变化。以 diffuse 为例： \[\text{diffuse} = L \cdot \rho \cdot n \cdot l / \pi\] \[\text{demodulate albedo} = L \cdot n \cdot l / \pi\] Temporal Accumulation 和 TAA 的重投影类似，通过深度、法线和 Mesh ID 来 reject。 Variance Esitimation 在时间上积累像素亮度的一阶矩和二阶矩 $\mu_1$、$\mu_2$。 计算方差： \[\operatorname{Var} = \mu_2 - \mu_1^2\] Edge-Avoiding Atrous Wavelets Wavelet filter 用于大范围滤波。法线和深度作为 edge avoiding 算法的输入，避免模糊掉几何边缘。 \[\hat{c}_{i+1}(p) = \frac{ \sum_{q \in \Omega} h(q)\, w(p,q)\, \hat{c}_i(q) }{ \sum_{q \in \Omega} h(q)\, w(p,q) }\] vec3 sum = vec3(0); float weight_sum = 0; for q in neighborhood: float weight = wavelet_kernel(q) // atrous wavelelt * depth_weight(p, q) // edge stopping * normal_weight(p, q) * luminance_weight(p, q); sum += weight * color[q]; weight_sum += weight; color_out[p] = sum / weight_sum; 墙壁的几何边缘不会被模糊掉。 Luminance Edge Stopping Function 通过上面计算的 variance，避免模糊掉阴影细节： \[w(p,q) = \exp\left( - \frac{ \left| l_i(p) - l_i(q) \right| }{ \sqrt{ g_{3 \times 3}\left( \operatorname{Var}\left(l_i(p)\right) \right) } } \right)\] Variance 大 → 噪声多 → 增大模糊，降低噪点。 Variance 小 → 噪声小 → 减小模糊，保留细节。 不过由于 filter 中对 variance 提前做了一遍高斯模糊来降低空域的噪声，一些阴影的细节会出现被模糊的情况。 阴影区域不会被模糊掉。 ASVGF ASVGF 解决拖影和细节丢失问题，生成一张 temporal gradient 图，估计当前帧和历史帧的变化梯度。 asvgf_gradient_reproject.comp -&gt; 生成 gradient sample positions path tracer -&gt; 对这些位置产生 gradient samples asvgf_gradient_img.comp -&gt; 根据当前/历史亮度差生成 gradient image asvgf_gradient_atrous.comp -&gt; 把稀疏 gradient 扩散成可用的低分辨率 gradient field asvgf_temporal.comp -&gt; 读取 gradient，做 anti-lag Temporal Accumulation &amp; AntiLag 以 primary ray HF 为例，权重 alpha 受 temporal gradient 的变化影响： if(temporal_sample_valid_diff) { // Compute the antilag factors based on the gradients float antilag_alpha_hf = clamp(mix(1.0, global_ubo.flt_antilag_hf * grad_hf_spec.x, global_ubo.flt_temporal_hf), 0, 1); // Adjust the history length, taking the antilag factors into account // gradient大，hist_len_hf小，历史帧越容易被丢弃 float hist_len_hf = min(temporal_moments_histlen_hf.b * pow(1.0 - antilag_alpha_hf, 10) + 1.0, 256.0); // Compute the blending weights based on history length, so that the filter // converges faster. I.e. the first frame has weight of 1.0, the second frame 1/2, third 1/3 and so on. float alpha_color_hf = max(global_ubo.flt_min_alpha_color_hf, 1.0 / hist_len_hf); float alpha_moments_hf = max(global_ubo.flt_min_alpha_moments_hf, 1.0 / hist_len_hf); // Adjust the blending factors, taking the antilag factors into account again alpha_color_hf = mix(alpha_color_hf, 1.0, antilag_alpha_hf); alpha_moments_hf = mix(alpha_moments_hf, 1.0, antilag_alpha_hf); // Blend! out_color_hf.rgb = mix(temporal_color_hf.rgb, color_curr_hf.rgb, alpha_color_hf); out_moments_histlen_hf.rg = mix(temporal_moments_histlen_hf.rg, spatial_moments_hf.rg, alpha_moments_hf); out_moments_histlen_hf.b = hist_len_hf; } q2rtx impl 在 G-Buffer 生成后，一个 compute shader pass reproject 到上一帧生成： imageStore(IMG_ASVGF_GRAD_SMPL_POS_A, pos_grad, uvec4(gradient_idx)); imageStore(IMG_ASVGF_GRAD_HF_SPEC_PING, pos_grad, vec4(found_prev_lum, 0, 0)); imageStore(IMG_ASVGF_RNG_SEED_A, ipos, texelFetch(TEX_ASVGF_RNG_SEED_B, found_pos_prev, 0)); imageStore(IMG_PT_NORMAL_A, ipos, texelFetch(TEX_PT_NORMAL_B, found_pos_prev, 0)); imageStore(IMG_PT_BASE_COLOR_A, ipos, texelFetch(TEX_PT_BASE_COLOR_B, found_pos_prev, 0)); imageStore(IMG_PT_METALLIC_A, ipos, texelFetch(TEX_PT_METALLIC_B, found_pos_prev, 0));]]></summary></entry></feed>