There have been threads like this before, but I’m not sure my own problem has
been covered and/or solved (in fact, since it’s OpenGL-related, I’m not even
sure if this is the right place for this question - if not, please feel free
to point me in the right direction).
I’m writing a 2D game based on MySDL with OpenGL. For my sprites, I load PNGs
into SDL surfaces from which I create both GL textures and bitmasks (from
alpha data, where needed) before freeing the SDL surface (not needed once I
have the texture and bitmask). Since I also calculate and outer and and inner
bounding box for each bitmask, and the latter is a comparably lengthy
procedure (perhaps my algorithm is suboptimal, but I don’t see how I could
optimize it further), loading all the animated sprite images for the game
takes a while (about 15 seconds on my current system).
So what I’d like to do is first load the graphics for the title screen, then
display the starfield (which is displayed both in-game and in the menu), the
logo and a progress bar, and load the in-game graphics in the background.
Which would mean:
- drawing the actual screen in the main thread
- loading PNG files into texture memory in another thread
glGenTextures in the second thread crashes, not surprisingly, since video
memory in SDL should not be accessed from more than one thread. However, I
can see only two solutions to this problem, and I don’t like either of them:
only one thread - load the images in the main thread, e.g. one per frame,
during the normal main loop. For larger textures this might noticeable slow
down the framerate though.
use the second thread for loading, but use a system of flags to do the
actual video memory transfers in the main thread.
Both solutions would mean that I could either load only one or two (or at
least a fixed number of) images per frame (meaning it would take even
longer), or I would have to estimate how many images I can load in the
remaining time for each frame.
Of course, I could just load all the video data first, and then do only the
bitmask calculations in the second thread, but that would mean having to keep
the SDL surface for bitmap generation, while I currently only need it during
the load() method. Also, I would like to keep the possibility of
swapping/re-loading images on the fly in my engine.
Ultimately, my question is: Is there absolutely no way to access OpenGL video
memory from two different SDL threads, even if the data from the secondary
thread is never used by the first thread while the secondary thread is alive?
Hofstadter’s law: “It always takes longer than you think, even when you take
account of Hofstadter’s law”.