0
\$\begingroup\$

I am using a texture of a world map and I am trying to put that image on a sphere made up of many triangles. Each triangle has points a,b,c with their own (x,y,z) coordinates.

I am trying to use the coordinate system conversions formula from Wikipedia. This is my world to spherical coordinates function:

function worldToSpherical(p) {   

  const r = Math.sqrt(Math.pow(p[0],2)+ Math.pow(p[1],2) + Math.pow(p[2],2));
  const u = Math.atan2(p[1],p[0]);
  const i = Math.atan2(Math.sqrt(Math.pow(p[0],2)+Math.pow(p[1],2)),p[2]);

  const s =  r * Math.sin(i) * Math.cos(u);
  const t =  r * Math.sin(i) * Math.sin(u);  
  return [s, t];

}

But this is what my output looks like:

Sample of what my planet looks like

It seems to be wrapping around twice. Am I using the wrong formula, or using it wrong?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You just went to a lot of trouble to undo the trig on your u and i variables! Don't re-trig them with cos and sin! Just compress the range from the radian angles to your 0...1 texture coordinate space.

function worldToSpherical(p) {

   const radius = Math.sqrt(p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);
   const longitudeRadians = Math.atan2(p[1], p[0]);
   const latitudeRadians = Math.asin(p[2]/radius);

   // Convert range -PI...PI to 0...1
   const s =  longitudeRadians/(2 * Math.PI) + 0.5;

   // Convert range -PI/2...PI/2 to 0...1
   const t =  latitudeRadians/Math.PI + 0.5;  
   return [s, t];
}
\$\endgroup\$
3
  • \$\begingroup\$ Note that if you compute your UV coordinate per vertex, you'll end up with artifacts - especially close to the poles. As demonstrated in this answer, you can fix this by computing your texture coordinates per pixel/per fragment in your shader \$\endgroup\$
    – DMGregory
    Apr 21, 2020 at 19:52
  • \$\begingroup\$ Thank you I see where I went wrong on my calculation. The only thing I see problematic currently is the North Pole is looking right at me and not on top of the sphere. \$\endgroup\$ Apr 21, 2020 at 20:01
  • \$\begingroup\$ Then you should edit your question to describe the coordinate system you're using. Your initial formula was set up as though z / p[2] is your vertical axis. If that's not the case, we'll need to swap a couple of the axes around, and potentially negate something depending on your handedness. \$\endgroup\$
    – DMGregory
    Apr 21, 2020 at 20:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .