c++openglsfml

How to draw n vertices of a VertexArray in SFML?


I have a line-strip of say N vertices sf::VertexArray vArr(sf::PrimitiveType::Lines, N);. Now when i draw it, it draws the entire line-strip of N vertices... How do I draw n (such that n < N) vertices similar to void glDrawArrays(GLenum mode, GLint first, GLsizei count); in OpenGL.

For example if N = 20, and n = 4, the RenderTarget should draw 4 vertices of the given vertex array. In raw OpenGL, I would have just called glDrawArrays(GL_LINE_STRIP, 0, 4);... how to do it in SFML?

I tried to use raw OpenGL calls after reading this, but could not figure out how to draw the VertexArray from the SFML graphics module.


Solution

  • target.draw(array) calls the draw (const Drawable &drawable, const RenderStates &states=RenderStates::Default) overload of RenderTarget. This in turn calls array.draw(target, states), which has the following implementation:

    void VertexArray::draw(RenderTarget& target, const RenderStates& states) const
    {
        if (!m_vertices.empty())
            target.draw(m_vertices.data(), m_vertices.size(), m_primitiveType, states);
    }
    

    You do not have access to m_vertices directly, but you can calculate the correct addresses by grabbing the address of the desired start. So, you can write a selective drawing function like so:

    void drawPartialVertexArray(sf::RenderTarget& target, const sf::VertexArray& va, size_t start, size_t count, const RenderStates& states = RenderStates::Default) const {
      target.draw(&va[start], count, va.getPrimitiveType(), states);
    }
    

    It is of course up to you to make sure that start and start+count are within the boundaries of va, and that count is a multiple of the vertex count as required by the primitive type.