Ray to sphere intersection math...

Problems building or running the engine, queries about how to use features etc.
Post Reply
User avatar
Ogre Magi
Posts: 1260
Joined: Mon Aug 07, 2006 6:16 am
Location: Colorado Springs, CO USA

Ray to sphere intersection math...

Post by Zeal »

I am rendering a atmosphere for my spherical terrain, and I have a little math question. I use a insideout sphere for the geometry itself, and I need to calculate the distance light travels form the camera to the sphere. This is easy to do on the vertex shader (since all the vertices are equal to the atmospheres radius), but it only looks good with a very highly tesselated sphere mesh.

So, I was thinking I could solve this by doing my 'light distance' equation in the fragment shader. To do this however, I need to do a 'ray to sphere' calculation, and I am a little lost. I ripped a ray to sphere function from HexiDave's spherical atmosphere shader...

Code: Select all

getNearIntersection( camPos, camToAtmoRay, camHeightSqr, atmoRadiusSqr );

float getNearIntersection(float3 v3Pos, float3 v3Ray, float fDistance2, float fRadius2)
   float B = 2.0 * dot(v3Pos, v3Ray);
   float C = fDistance2 - fRadius2;
   float fDet = max(0.0, B*B - 4.0 * C);
   return 0.5 * (-B - sqrt(fDet));
...which seems to work for calculating a intersection if the camera is OUTSIDE the sphere. I need a modified version that calculates the intersection when the camera is INSIDE the sphere.

Thanks for any help!

User avatar
OGRE Retired Moderator
OGRE Retired Moderator
Posts: 4011
Joined: Fri Sep 19, 2003 6:28 pm
Location: Burgos, Spain
x 2

Post by Kencho »

Can't do the calculations myself at this moment, but I would start looking at this. After a brief lecture that seems to return the line segment inside a sphere, given the sphere and the line (in your case, defined by the base point -camera position- and directing vector -camera direction). If the camera is inside the sphere (and thus, the segment), you should construct a new segment with the camera position and one of the intersection points (the other is behind the camera) and calculate its length.

Probably not optimal, but it's the best I can figure right now :)

Post Reply