/*
Source code from,
https://renderman.pixar.com/forum/showthread.php?s=&threadid=29732&highlight=osl+UDIM
  
Author: Larry Gritz
*/
  
  
color linearizeColor(color texColor,
                     int linearize)
{
    if (!linearize) 
    {
        return texColor;
    }
    else
    {
        color result = texColor;
        for (int i=0;i<3;i++) 
        {
            if (result[i] < .04045)
            {
                result[i] = result[i] * .07739938;
            }
            else
            {
                result[i] = pow((result[i] + .055)*0.947867299, 2.4);
            }
        }
        return result;
    } 
}
  
shader
texatlas (string filename = "",
          float s = 0 [[int lockgeom = 0]],
          float t = 0 [[int lockgeom = 0]],
          int alpha = 0,
          int linearize = 0,
          float blur = 0,
          output color resultC = 0,
          output float resultF = 0)
{
    int thisUMap, thisVMap;
  
    thisUMap = int(s);
    thisVMap = int(t);
  
  
#define NAME(i) format("%s%d.tex",filename,i+1001)
#define TENNAME(j)  NAME(10*j+0),NAME(10*j+1),NAME(10*j+2),NAME(10*j+3),NAME(10*j+4), \
                    NAME(10*j+5),NAME(10*j+6),NAME(10*j+7),NAME(10*j+8),NAME(10*j+9)
#define TENROW      TENNAME(0),TENNAME(1),TENNAME(2),TENNAME(3),TENNAME(4), \
                    TENNAME(5),TENNAME(6),TENNAME(7),TENNAME(8),TENNAME(9)
  
    string filenames[100] = { TENROW };
  
#undef NAME
#undef TENNAME
#undef TENROW
  
    int udim = thisVMap*10 + thisUMap;
    string atlasname = filenames[udim];
  
    float sM = s - thisUMap;
    float tM = 1.0 - (t - thisVMap);
    if (alpha)
    {
        resultF = (float) texture(atlasname, sM, tM, "firstchannel", alpha-1, "blur", blur);
    }
    else
    {
        color texColor = (color) texture (atlasname, sM, tM, "blur", blur);
        resultC = linearizeColor(texColor, linearize);
    }
}