Implementing a Fast OpenGL Tilemap

A thoroughly documented implementation of an OpenGL tilemap
opengltilemapdraft • 2021-10-02

To learn OpenGL, I wanted to make a tilemap all on my own. However, I didn't want to render potentially billions of triangles for an extremely large world (100,000 by 100,000). Thus, I saught out various implementations and blogposts, but they all had their faults:

Thus, marks the goals of this post:

  1. Provide clean, thoroughly explained code
  2. Explain the technique

Without further ado, I present to you:

The Code

All the code can be found on GitHub. The code itself is the content of this article. This article is merely supplementary for search engine optimization reasons.

While showing off additional features like multiple layers, parallax scrolling, or a ton of mutations would be cool, they also distract from the main point being shown. Thus, all additional features are left as an exercise to the reader.

The Technique

For this section, the overall abstract of the technique will be explained. Do note that the code provides a much more in-depth explanation of the specifics of what is being done.

The goal is to render a quad that acts as a tilemap. To render a quad, we will perform the following for every pixel:

  1. Figure out the tile it's suppose to be
  2. Pick the right color

Assume we're running some code for the pixel P in the following image:

+--------------+
|              |
|           P  |
|              |
|              |
|              |
+--------------+

The first step is to figure out what block the pixel should be. Let's assume we've figured that out:

+----+----+----+
|0   |1   |1   |
|    |    | P  |
+----+----+----+
|0   |0   |1   |
|    |    |    |
+----+----+----+

Here, the numbers in the upper left corner represent the "id" of the block in question.

Finally, the goal is to take a texture atlas, something like so (where the numbers represent both the ID and the texture):

+---+---+
|000|111|
|000|111|
+---+---+

figure out where our pixel lies in that atlas

+---+---+
|000|111|
|000|1P1|
+---+---+

and to copy over the color our pixel lies on in the texture atlas into the final image:

+----+----+----+
|    |    |    |
|    |    | 1  |
+----+----+----+
|    |    |    |
|    |    |    |
+----+----+----+

Conclusion

In conclusion, check out the code. It is the entire meat of this, and it is thoroughly commented on what it does.