2017-02-14 53 views
0

我有以下片段和頂點着色器。線性深度到世界位置

HLSL代碼 ` //頂點着色器 // ---------------------------------- -------------------------------------------------

void mainVP( 
    float4 position  : POSITION, 
    out float4 outPos : POSITION, 
    out float2 outDepth : TEXCOORD0, 
    uniform float4x4 worldViewProj, 
    uniform float4 texelOffsets, 
    uniform float4 depthRange) //Passed as float4(minDepth, maxDepth,depthRange,1/depthRange) 
{ 
    outPos = mul(worldViewProj, position); 
    outPos.xy += texelOffsets.zw * outPos.w; 
    outDepth.x = (outPos.z - depthRange.x)*depthRange.w;//value [0..1] 
    outDepth.y = outPos.w; 
} 

// Fragment shader 
void mainFP(float2 depth: TEXCOORD0, out float4 result : COLOR) { 
    float finalDepth = depth.x; 
    result = float4(finalDepth, finalDepth, finalDepth, 1); 
} 

`

此着色器產生的深度圖。

然後必須使用此深度圖來重建深度值的世界位置。我已經搜索了其他帖子,但他們似乎沒有使用我使用的相同公式存儲深度。唯一類似的帖子是以下內容 Reconstructing world position from linear depth

因此,我很難用深度圖和相應深度的x和y座標重建點。

我需要一些幫助來構建着色器來獲取特定紋理座標深度的世界視圖位置。

回答

0

它看起來不像你正在規範你的深度。試試這個。在你的VS,這樣做:

outDepth.xy = outPos.zw;

而在你的PS渲染的深度,你可以這樣做:

float finalDepth = depth.x/depth.y;

這裏是一個函數,然後提取的觀看空間中的位置來自深度紋理的特定像素。我假設你正在渲染屏幕對齊的四邊形,並在像素着色器中執行位置提取。

// Function for converting depth to view-space position 
// in deferred pixel shader pass. vTexCoord is a texture 
// coordinate for a full-screen quad, such that x=0 is the 
// left of the screen, and y=0 is the top of the screen. 
float3 VSPositionFromDepth(float2 vTexCoord) 
{ 
    // Get the depth value for this pixel 
    float z = tex2D(DepthSampler, vTexCoord); 
    // Get x/w and y/w from the viewport position 
    float x = vTexCoord.x * 2 - 1; 
    float y = (1 - vTexCoord.y) * 2 - 1; 
    float4 vProjectedPos = float4(x, y, z, 1.0f); 
    // Transform by the inverse projection matrix 
    float4 vPositionVS = mul(vProjectedPos, g_matInvProjection); 
    // Divide by w to get the view-space position 
    return vPositionVS.xyz/vPositionVS.w; 
} 

對於減少參與計算的數量,但使用view frustum並呈現在屏幕對準四的一種特殊的方式涉及到一個更先進的方法,請參閱here

+0

看來你的解決方案不是爲了線性深度。我有一個着色器按照你所說的方式工作,但我需要有另一個着色器以線性深度工作。 – nickygs