Search code examples
cmathvectortuplespoint

How should I implement point and vector in C?


I am trying to implement mathematical concepts point and vector in C, using struct.

I've seen someone else's C++ implementation of it.

Tuple Point(float x, float y, float z)
{
    return {x, y, z, 1.0f};
}

Tuple Vector(float x, float y, float z)
{
    return { x, y, z, 0.0f };
}

Tuple::Tuple()
    : m_x(0.f)
    , m_y(0.f)
    , m_z(0.f)
    , m_w(0.f)
{
}

Tuple::Tuple(float x, float y, float z, float w)
    : m_x(x)
    , m_y(y)
    , m_z(z)
    , m_w(w)
{
}

I'm not sure how should I be implementing it in C. Here's what I've done.

typedef struct s_tuple
{
    double x;
    double y;
    double z;
    double w;
}              t_tuple;

typedef struct s_point
{
    double x;
    double y;
    double z;
    double w = 1.0;
}              t_point

typedef struct s_vector
{
    double x;
    double y;
    double z;
    double w = 0.0;
}              t_vector

I'm not sure if I'm doing it right. I'm not even sure if t_tuple exists for a reason in this implementation. How should I fix it?


Solution

  • One possible way is to have factory functions that create the tuple structure with the correct values for each "type" of tuple:

    typedef struct s_tuple
    {
        double x;
        double y;
        double z;
        double w;
    }              t_tuple;
    
    t_tuple create_tuple(double x, double y, double z, double w)
    {
        t_tuple tuple = {
            x, y, z, w
        };
        return tuple;
    }
    
    t_tuple create_point(double x, double y, double z)
    {
        return create_tuple(x, y, z, 1.0);
    }
    
    t_tuple create_vector(double x, double y, double z)
    {
        return create_tuple(x, y, z, 0.0);
    }