float3 unproject(const float2& screen_position, float VSdepth, const float2& viewport_position, const float2& viewport_dimensions, const float4x4& proj) { float2 screen_texcoord = (screen_position.xy() - viewport_position) / (viewport_dimensions - 1.0f); screen_texcoord.y = 1.0f - screen_texcoord.y; float4 clip = float4(VSdepth * (screen_texcoord * 2.0f - 1.0f), VSdepth * proj[2].z, VSdepth); float4 result = mul(invert(proj), clip); return result.xyz(); }