Skip to content

Pixel perfect DrawRectangleLines under OpenGL 1.1 #7

@debiatan

Description

@debiatan

Currently, several pixel-based routines in RayLib are not pixel-perfect. I have picked DrawRectangleLines because I am using it in a program of mine.

DrawRectangleLines takes four arguments that define the shape of the rectangle to draw (int posX, int posY, int width, int height) and generates eight rlVertex2i calls to draw lines that define a square with corners in(posX+1, posY+1), (posX+width, posY+1), (posX+width, posY+height) and (posX+1, posY+height). Those corners are offset by one pixel, in both the horizontal and the vertical axis, from the intended behavior of the call.

Leaving aside that superficial mistake, in order to get pixel-perfect results, care must be taken to recompile the library after uncommenting the following line from core.c:BeginDrawing:

//  rlTranslatef(0.375, 0.375, 0);  // HACK to have 2D pixel-perfect drawing on OpenGL 1.1

Since that solution is less than ideal, and given that the initial orthographic projection is set as

rlOrtho(0, width - offsetX, height - offsetY, 0, 0, 1);   // top-left corner --> (0,0)

inside rlgl.c:rlglInitGraphics, I would suggest offsetting the corners of the rectangle by half a pixel so that they fall on their intended position. DrawRectangleLines would then read:

void DrawRectangleLines(int posX, int posY, int width, int height, Color color)
{
    rlBegin(RL_LINES);
        rlColor4ub(color.r, color.g, color.b, color.a);
        rlVertex2f(posX + .5, posY + .5);
        rlVertex2f(posX + width - .5, posY + .5);

        rlVertex2f(posX + width - .5, posY + .5);
        rlVertex2f(posX + width, posY + height - .5);

        rlVertex2f(posX + width - .5, posY + height - .5);
        rlVertex2f(posX + .5, posY + height - .5);

        rlVertex2f(posX + .5, posY + height - .5);
        rlVertex2f(posX + .5, posY + - .5);
    rlEnd();
}

I understand that working with non-integer coordinates can get cumbersome quickly, but only the rest of the 2D primitives of shapes.c would need to be adapted and users of RayLib would be blissfully shielded from having to think in terms of floating-point coordinates or from recompiling the library.

What do you think?

Cheers!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions