Raycast missing shapes

I've been working in a small program where the sun should illuminate plants to make then grow. I thought of using the raycasts to accomplish this, but when I was trying to use them they would miss shapes all the time, the problem was completely solved when I switched the raycasting to segment testing. I don't know if this is really a bug or me doing something stupid, but I couldn't figure why the raycasts wouldn't work.

Here's the code for the same thing using the two different methods:

RaycastOne:
Code:
for(int i=0; i<lightLength; i++)
   {
      light[i].p1 = b2Vec2 (i*1.0f - worldHalfSize, worldHalfSize);
      light[i].p2 = b2Vec2 (i*1.0f - worldHalfSize, -worldHalfSize);

      
      float lambda = 1;
      b2Vec2 normal;
      b2Shape* shape = world->RaycastOne(light[i],&lambda,&normal,true,NULL);
      
   
      if(shape)
      {
         light[i].p2 = (1 - lambda) * light[i].p1 + lambda * light[i].p2;
         
      }   
   }



Segment Testing:
Code:
for(int i=0; i<lightLength; i++)
   {      
      
      light[i].p1 = b2Vec2 (i*1.0f - worldHalfSize, worldHalfSize);
      light[i].p2 = b2Vec2 (i*1.0f - worldHalfSize, -worldHalfSize);

      float lambda = 1;
      b2Vec2 normal;

      float menorLambda = 1;   
      
      for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
      {
         for (b2Shape* s = b->GetShapeList(); s; s = s->GetNext())
         {
            bool hit = s->TestSegment( b->GetXForm(), &lambda, &normal, light[i], 1 );

            if(lambda  < menorLambda)
            {
               menorLambda = lambda;               
            }

         }
      }
      
      light[i].p2 = (1 - menorLambda) * light[i].p1 + menorLambda * light[i].p2;
   }
Hi, Hellekin. I cannot see anything wrong with your code, and the Raycast code is relatively new, it is quite likely there is a bug. I shall look into this, but it would help a lot if you could prepare some code that reproduces the problem. At least, could you try the following code and see if it is fixed:
Code:
      light[i].p1 = b2Vec2 (i*1.0f - worldHalfSize, worldHalfSize);
      light[i].p2 = b2Vec2 (i*1.0f - worldHalfSize+0.001, -worldHalfSize);

This is because vertical (and horizontal) rays are a special case, and I would like to confirm my intuition that it is only in this case that there is a problem.
I made an example for the testbed, just replace it for the raycastTest.h:

Code:
/*
* Copyright (c) 2007 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#ifndef RAYCAST_TEST_H
#define RAYCAST_TEST_H

class RaycastTest : public Test
{
public:
   RaycastTest()
   {
      //m_world->SetGravity(b2Vec2(0,0));

      b2Body* ground = NULL;
   
      b2BodyDef bd;
      bd.position.Set(0.0f, -10.0f);
      ground = m_world->CreateBody(&bd);

      b2PolygonDef sd;
      sd.SetAsBox(50.0f, 10.0f);
      ground->CreateShape(&sd);
   

            
      b2PolygonDef sd_bottom;
      sd_bottom.SetAsBox( 1.5f, 0.15f );
      sd_bottom.density = 4.0f;

      b2PolygonDef sd_left;
      sd_left.SetAsBox(0.15f, 2.7f, b2Vec2(-1.45f, 2.35f), 0.2f);
      sd_left.density = 4.0f;

      b2PolygonDef sd_right;
      sd_right.SetAsBox(0.15f, 2.7f, b2Vec2(1.45f, 2.35f), -0.2f);
      sd_right.density = 4.0f;
      
      bd.position.Set( 0.0f, 15.0f );
      b2Body* body = m_world->CreateBody(&bd);
      body->CreateShape(&sd_bottom);
      body->CreateShape(&sd_left);
      body->CreateShape(&sd_right);
      body->SetMassFromShapes();

      lightLength = 100;
      light = new b2Segment[100];
      
   }

   void Keyboard(unsigned char key)
   {
      switch (key)
      {
      case 0:
         break;
      }
   }

   void Step(Settings* settings)
   {
      Test::Step(settings);
      
      b2Color laserColor(255,0,0);
   
      for(int i=0; i<lightLength; i++)
      {
         light[i].p1 = b2Vec2 (i*2.0f - 100.0f, i-25.0f);
         light[i].p2 = b2Vec2 (i*2.0f - 100.0f+100.0f, -100.0f);
         
         float lambda = 1;
         b2Vec2 normal;
         b2Shape* shape = m_world->RaycastOne(light[i],&lambda,&normal,true,NULL);         
      
         if(shape)
         {
            light[i].p2 = (1 - lambda) * light[i].p1 + lambda * light[i].p2;            
         }   

         m_debugDraw.DrawSegment(light[i].p1, light[i].p2,laserColor);
      }

      
   }

   static Test* Create()
   {
      return new RaycastTest;
   }

   b2Segment* light;
   int lightLength;

};

#endif


The vertical and horizontal segments seem to have some effect, but it's not the only thing because even adding 100.0f where boris suggested 0.001f still have the same crazy results.

Move the body around and you will see whats happens, the effect I expected from this code is what happens when you place the body very close to the beginning of the rays.

Anyway, hope it helps
Fixed. Your sample was very helpful.
The problem was that raycasting would always fail if the starting point was outside the bounding AABB of all the shapes, something that could never occur with my laser attached to a body example.
I still need to check that the code will work for starting points outside the world AABB, though, I'm not sure I accounted for that either originally.
Nice work, now the raycast is working much better... however vertical rays can still cause problems =/. You can see that removing the +100.0f from my example in the:

Quote:
light[i].p1 = b2Vec2 (i*2.0f - 100.0f, i-25.0f);
light[i].p2 = b2Vec2 (i*2.0f - 100.0f, -100.0f);



But that problem can be "solved" by not making completely vertical rays for now.
Agh, yes, my bugfix introduced that. Try the attached fix, I think that solves it.
Sorry, I'm not good at this bug-patch-discuss cycle.
Yep, now it seems to work flawlessly =D. Nice job, thanks a lot.
So, I having problems with rays passing between the gaps in edge shapes. I found this post but I'm already up to date with the code Boris posted. So I put together a raycast blaster test to visualize the problem. This code will blasts out a crap ton of rays to look for errors. Start points are randomized within a box. You can just paste this code right into the class body of the StaticEdges test. It should be pretty easy to see the glitches when you place the rayblaster anywhere in the edge loop.

Code:
void Step(Settings* settings)
{
   Test::Step(settings);

   if (m_mouseWorld.x < -100 || m_mouseWorld.x > 100 || m_mouseWorld.y < -100 || m_mouseWorld.y > 100)
      return;

   float laserRandomness = 1.0f;
   b2Color laserColor(255,0,0);

   // do a super laser blast
   for(int i = 0; i < 1000; ++i)
   {
      // randomize the angle
      float32 laserAngle = RandomFloat(0, 2*b2_pi);
      b2Segment segment = {m_mouseWorld, m_mouseWorld};
      segment.p2 += 100 * b2Vec2(cosf(laserAngle), sinf(laserAngle));

      // randomize start and end points
      b2Segment segmentRandom = segment;
      segmentRandom.p1.x += RandomFloat(-laserRandomness, laserRandomness);
      segmentRandom.p1.y += RandomFloat(-laserRandomness, laserRandomness);
      segmentRandom.p2.x += RandomFloat(-laserRandomness, laserRandomness);
      segmentRandom.p2.y += RandomFloat(-laserRandomness, laserRandomness);

      // cast the ray
      float32 lambda;
      b2Vec2 normal;
      b2Shape* shape = m_world->RaycastOne(segmentRandom,&lambda,&normal,false,NULL);
      if(shape)
         m_debugDraw.DrawSegment(segmentRandom.p1,(1-lambda)*segmentRandom.p1+lambda*segmentRandom.p2,laserColor);
      else
         m_debugDraw.DrawSegment(segmentRandom.p1,segmentRandom.p2,laserColor);
   }

   b2Color boxColor(0,0,255);
   b2AABB randomBox = {m_mouseWorld - b2Vec2(laserRandomness, laserRandomness), m_mouseWorld + b2Vec2(laserRandomness, laserRandomness)};
   m_debugDraw.DrawAABB(&randomBox, boxColor);
}


To fix the problem I rewrote the edges shape TestSegment function to be more like the algorithm I use. Then I tweaked it to allow for an extra distance for the edge segment. This seems to fix the problem. Here is my modified b2EdgeShape::TestSegment function.

EDIT - I update the fix to put normals in world space, ignore back facing tris and divide by d last.

Code:
b2SegmentCollide b2EdgeShape::TestSegment(const b2XForm& transform,
                        float32* lambda,
                        b2Vec2* normal,
                        const b2Segment& segment,
                        float32 maxLambda) const
{
   const b2Vec2& v1 = segment.p1;
   const b2Vec2& v2 = segment.p2;
   const b2Vec2 v3 = b2Mul(transform, m_v1);
   const b2Vec2 v4 = b2Mul(transform, m_v2);

   const b2Vec2 delta1 = v2 - v1;
   const b2Vec2 delta2 = v4 - v3;
   const float d =   b2Cross(delta1,delta2);

   if (d > 0)
      return e_missCollide;   // ignore parallel and back faces

   const b2Vec2 delta3 = v1 - v3;
   const float uad = b2Cross(delta2,delta3);
   if (uad > 0 || uad < d*maxLambda)
      return e_missCollide;   // intersection outside bounds of line segment

   // To fix problem with ray casts going through edges we allow some
   // extra length for the edge to ensure there are no gaps
   // this value should be tweaked depending on other physics parameters
   const float extraEdgeLength = 0.1f;
   const float ubd = b2Cross(delta1,delta3);
   if (ubd > -d*extraEdgeLength || ubd < d*(1 + extraEdgeLength))
      return e_missCollide;
   
   // transform the normal and calculate lambda
   *normal = b2Mul(transform.R, m_normal);
   *lambda = uad/d;
   return e_hitCollide;
}
I'm not sure I understand. Your fix seems to work by extending by a small amount the starting segment, which suggests that the problem you are having is that TestSegment can "miss" a edge segment if it starts very near it. But your example at the beginning doesn't seem to be demonstrating that.

I'm somewhat dubious on the fix, too. It seems ugly to arbitrarily extend segments like that, and doubly so by a percentage. It'll just generate more confusion, for stuff on the *other* side of the edge. At least only extend it backwards. Instead, I recommend people with this problem to set up their worlds in such a way that raycasts can never get too near an edge - such as by embedding the start of the raycast inside a shape.

Your code, however, is beautifully written compared with the current function. Might be good to replace it anyway. Though it has a bug in it, and the division by d should be deferred for as long as possible.
Did you try the example I posted? If so did you see the error I was reporting of a where a few of thousands of rays cast will end up passing through the edge loops? If you did not see the error then we need to find out why. You seem to indicate you didn't see the glitch so that's why I'm confused. If you did see the error that means it does exist and it would be good to have a workaround of some sort for people that run into it. Mine is not great but in my case it's better then the rays missing the edges totally. I tend to use a lot of raycasts for gameplay stuff so it is of highest technical priority that I have a rock solid raycast in the engine I am developing.

I didn't see the division by d opt until you mentioned it, thanks! So whats the bug in my code that you see?

Original thread: https://box2d.org/forum/viewtopic.php?t=1967