0

I am writing a ray tracing program in C++ to get better at the language. However I am having some troubles implementing my ray-cube intersection functionality.

Here is my class

class Cube {
public:
    Cube() {};
    ~Cube() {};

    float Intersection(Ray ray) {
        // Intersection Code Here
    }

public:
    glm::vec3 Position;
    glm::vec3 Size;
    int MaterialIndex = 0;
};

I can't find any good references anywhere that fit my need (using vec3s for size and position). I need to return a float that is the distance to the Cube or -1 if it does not hit.

For reference here is my Sphere class


class Sphere {
public: 
    Sphere() {};
    ~Sphere() {};

    float Intersection(Ray ray) {
        glm::vec3 origin = ray.Origin - Position;

        float a = glm::dot(ray.Direction, ray.Direction);
        float b = 2.0f * glm::dot(origin, ray.Direction);
        float c = glm::dot(origin, origin) - Radius * Radius;

        // Quadratic forumula discriminant:
        // b^2 - 4ac

        float discriminant = b * b - 4.0f * a * c;


        // Quadratic formula:
        // (-b +- sqrt(discriminant)) / 2a

        // float t0 = (-b + glm::sqrt(discriminant)) / (2.0f * a); // Second hit distance (currently unused)
        float closestT = (-b - glm::sqrt(discriminant)) / (2.0f * a);
        
        return closestT;
    };

public:
    float Radius = 0.5f;
    glm::vec3 Position;
    int MaterialIndex = 0;
};

Can anyone help me?

cade
  • 563
  • 4
  • 15
DevStuffz
  • 19
  • 9
  • [This](https://gamedev.stackexchange.com/questions/18436/most-efficient-aabb-vs-ray-collision-algorithms) looks like it might be relevant. – pmacfarlane Dec 21 '22 at 20:36
  • see my [GLSL 3D Mesh back raytracer](https://stackoverflow.com/a/45140313/2521214) and pay attention to the vertex code starting with: `if (id==_fac_triangles) for (;num>0;num--)` its ray triangle intersection that can be rewrited to ray cube ... either by testing all 12 triangles of cube or converting the triangle stuff to square and check just 6 quads instead (that should be faster because it does not need the barycentric stuff anymore). Also you can extract the stuf from here [`line closest(triangle t0,axis a0)`](https://stackoverflow.com/a/62257945/2521214) – Spektre Dec 29 '22 at 09:58
  • PS having triangle support in ray tracer is much better than having indinvidual flat face primitives as you can do any of them with just triangles also 3D meshes like STL,OBJ,... – Spektre Dec 29 '22 at 10:02

0 Answers0