Search code examples
cmathgeometrytexturesraytracing

Raytracing spherical texture


I'm trying to fit a world texture on a sphere. It's almost working, but texture is repeated twice. This is my mapping code:

v = acosf(sp->coll->z / (double)sp->radius) / M_PI ;
u = asinf(sp->coll->y / ((double)sp->radius * sinf(v * M_PI))) / M_PI;
u += 0.5;
// u and v are between 0 and 1
i = (int)((float)texture->xsize * (v - ((int)v)));
j = (int)((float)texture->ysize * (u - ((int)u)));
this->color = texture->map[j][i];

What might be causing this issue?


Solution

  • I think the problem is that you've lost some sign information in the u calculation.

    There are points on the sphere for a given z and y pair. To resolve this ambiguity you should use atan2 instead of asin. The code would look roughly like this:

    u = atan2(sp->coll->y, sp->coll->x)/(2*PI);
    

    You may need to normalise the arguments to atan2 - but in most implementations you do not need to.