Search code examples
graphicsshaderblenderhlsldirectx-9

Un/pack additional set of UV coordinates into a 32bit RGBA field


I'm modding a game called Mount&Blade, currently trying to implement lightmapping through custom shaders.

As the in-game format doesn't allows more than one UV map per model and I need to carry the info of a second, non-overlapping parametrization somewhere, a field of four uints (RGBA, used for per-vertex coloring) is my only possibility.

At first thought about just using U,V=R,G but the precision isn't good enough. Now I'm trying to encode them with the maximum precision available, using two fields (16bit) per coordinate. Snip of my Python exporter:

def decompose(a):
  a=int(a*0xffff)     #fill the entire range to get the maximum precision
  aa  =(a&0xff00)>>8  #decompose the first half and save it as an 8bit uint
  ab  =(a&0x00ff)     #decompose the second half
  return aa,ab

def compose(na,nb):
    return (na<<8|nb)/0xffff

I'd like to know how to do the second part (composing, or unpacking it) in HLSL (DX9, shader model 2.0). Here's my try, close, but doesn't works:

  //compose UV from n=(na<<8|nb)/0xffff
  float2 thingie = float2(
      float( ((In.Color.r*255.f)*256.f)+
               (In.Color.g*255.f)        )/65535.f,
      float( ((In.Color.b*255.f)*256.f)+
               (In.Color.w*255.f)        )/65535.f
  );
  //sample the lightmap at that position
  Output.RGBColor = tex2D(MeshTextureSamplerHQ, thingie);

Any suggestion or ingenious alternative is welcome.


Solution

  • Remember to normalize aa and ab after you decompose a. Something like this:

    (u1, u2) = decompose(u)
    (v1, v2) = decompose(v)
    color.r = float(u1) / 255.f
    color.g = float(u2) / 255.f
    color.b = float(v1) / 255.f
    color.a = float(v2) / 255.f
    

    The pixel shader:

    float2 texc;
    texc.x = (In.Color.r * 256.f + In.Color.g) / 257.f;
    texc.y = (In.Color.b * 256.f + In.Color.a) / 257.f;