# Optimizing black and white matrix block drawing

Disclaimer: I am uncertain if this is the best place to post this question, so please advise me of how I can best find the answer if I am doing something wrong. I am asking this question because I am trying to optimize a drawing function of a PC game I am programming.

Preface: There is a matrix of blocks, that can be either on (black) or off (white). There will be different colors, but for the sake of simplicity I am presenting the problem to you as black and white only, so please imagine this matrix forming some random pattern like a QR code which would be a good example.

Problem: Instead of drawing each black block individually, I want to determine how to draw all black blocks using as minimum calls to my draw black rectangle function as possible.

Question: Is there any existing process that I can refer to so as to make my drawing process as efficient as possible, or how would I logically go about tackling this conundrum?

Edit: Tried to produce some example code for us to play with

std::vector<std::vector<bool>> matrix;

int width = 100;
int height = 100;

matrix.resize(height);

for(int h = 0; h < height; h++)
{
matrix[h].resize(width);
for(int w = 0; w < width; w++)
{
matrix[h][w] = random 1/0
}
}

void draw()
{
.. draw matrix using a minimum amount of calls to draw_rectangle
}

void draw_rectangle(int x, int y, int width, int height)
{
.. draws a set of black blocks
}

• You can put all your squares in a single VBO and draw it with a single call. It's going to be 2000 triangles, which is very small amount. Jun 11, 2016 at 13:01
• Would that be just as efficient as putting fewer rectangles in a VBO to make the same image and drawing it with a single call? Jun 11, 2016 at 13:04
• I think difference would be insignificant. The problem here is only an amount of draw calls, not polygons. Jun 11, 2016 at 13:07
• Thank you for your answer, I accept your method as I believe passing this to the GPU will be quicker than performing calculations in a CPU thread and then passing it to the GPU. Jun 11, 2016 at 13:08
• Possible duplicate of Algorithm for "healing" multiple rectangles into a smaller number of rectangles? Sep 18, 2016 at 23:17