SFML community forums

General => Feature requests => Topic started by: Kojay on August 25, 2013, 07:31:04 pm

Title: A simple sf::Line (segment)
Post by: Kojay on August 25, 2013, 07:31:04 pm
This has been asked for here and on irc. The tutorial claims a line with no thickness is simply two sf::Vertex, whereas a line with thickness is a rotated rectangle.
However, there's a difference: if the user has two points and he wants a line segment between them with thickness, then boilerplate code needs to be written for said rectangle to achieve desired effect.

A simple class for line segments could look like this:

class sfLine : public sf::Drawable
{
public:
    sfLine(const sf::Vector2f& point1, const sf::Vector2f& point2):
        color(sf::Color::Yellow), thickness(5.f)
    {
        sf::Vector2f direction = point2 - point1;
        sf::Vector2f unitDirection = direction/std::sqrt(direction.x*direction.x+direction.y*direction.y);
        sf::Vector2f unitPerpendicular(-unitDirection.y,unitDirection.x);

        float halfThick = thickness/2;

        vertices[0].position = point1 + halfThick*unitPerpendicular;
        vertices[1].position = point2 + halfThick*unitPerpendicular;
        vertices[2].position = point2 - halfThick*unitPerpendicular;
        vertices[3].position = point1 - halfThick*unitPerpendicular;

        for (auto& vertex : vertices)
            vertex.color = color;
    }

    void draw(sf::RenderTarget &target, sf::RenderStates states) const
    {
        target.draw(vertices.data(),4,sf::Quads);
    }


private:
    std::array<sf::Vertex,4> vertices;
    float thickness;
    sf::Color color;
};
 

The c++11 keywords can be done away with, setters for color and thickness added, assert that the points are distinct.

Note how Thor library offers a line shape and given point1 and point2 a segment could be obtained this way:

auto myLine = thor::Shapes::line(point2-point1,sf::Color::Yellow, 3.f);
myLine.setPosition(point1);
 

But I do think this results in a 'heavier' myLine than the class presented above.



Title: Re: A simple sf::Line (segment)
Post by: Kojay on August 26, 2013, 09:41:57 am
Since it's not clear what the proposed class does, it it basically this:

(https://dl.dropboxusercontent.com/u/105214643/segment.png)

Given point1 and point2, it draws a quad between vertices 0-3.
Title: Re: A simple sf::Line (segment)
Post by: Laurent on August 27, 2013, 03:57:47 pm
Such a shape class created from scratch would not fit very well in the current design, it'd rather be a derived class of sf::Shape. But in this case, as you already noticed, the thickness would also be applied on the small edges.

So you should keep your class, even share it on the wiki, but I don't think it can be integrated to the SFML API.