Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Manual mip level for cubemaps

Discussion in 'Shaders' started by flogelz, Jul 29, 2023.

  1. flogelz

    flogelz

    Joined:
    Aug 10, 2018
    Posts:
    141
    I'm trying to calculate the mip map level of a cubemap manually. I'm using the cubemap for reflection influenced by roughness, so i need to sample the lods manually, which sadly removes auto mip level selection on glancing angles, so all the good "no-mipmap" artifacts appear.

    Now I found this function in the Common.hlsl of the URP, which I think could solve this, but I am not sure about the input parts- (and sadly also haven't found one line where this gets used in the source code)

    Code (CSharp):
    1. float ComputeTextureLOD(float3 duvw_dx, float3 duvw_dy, float3 duvw_dz, float scale, float bias = 0.0)
    2. {
    3.     float d = Max3(dot(duvw_dx, duvw_dx), dot(duvw_dy, duvw_dy), dot(duvw_dz, duvw_dz));
    4.  
    5.     return max(0.5f * log2(d * (scale * scale)) - bias, 0.0);
    6. }
    I know ddx and ddy a bit, but I'm not sure how to apply this concept to 3 dimensions? Because the input to sampling would be the reflection direction, a float3.

    Does anybody has a clue about this?
     
  2. Rukhanka

    Rukhanka

    Joined:
    Dec 14, 2022
    Posts:
    177
    This function is strange, because screen space partial derivatives exist only for x and y coordinates (screen is 2D space). Maybe it is for some form of 3D texrure mip map level calculation. As for cubemap the situation is simpler. Texture coordinate for it calculated very sumple: with given 3D direction vector, maximum by magnitude component (u, v or w) is used to select cube face. UV coordinates of pixel in given face can be calculated by simple division of other two component by found highest one. So, your algithm is follows: calculate UV by given algorithm, an then use it for ordinary mipmap level calculation with ddx and ddy.

    More info about cubemap internals: https://developer.download.nvidia.com/assets/gamedev/docs/GDC2K_Cube_Maps.pdf
     
    flogelz likes this.
  3. flogelz

    flogelz

    Joined:
    Aug 10, 2018
    Posts:
    141
    Thanks for the answer! I tried getting it to work, but I always had to fight some artifacts on the way, but by chance I actually just stumbled upon a way easier solution, because there is actually an in-built function in hlsl that does exactly that! Calculating the mip map level the builtin way as a value I can modify afterwards to my liking!

    For anyone who wants to use it too, here ya go: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-calculate-lod