# OpenGL Using SDL for OpenGL context is slower than GLFW

This topic is 2456 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I've been cleaning up my code a bit making sure that if I were to switch graphics APIs it wouldn't be a huge deal. So I decided to switch to SDL for context creation and input since I was using GLFW.

Unfortunately I experienced a severe performance degradation when using SDL. FPS dropped from 180-200 (GLFW) to 40-70 (SDL) and the framerate is choppy and less continuous. I'm not too familiar with OpenGL context management (hence why I'm using GLFW and SDL) and I found little information regarding performance between SDL and GLFW so I decided to ask here.

Here is the GLFW code:
 if (!glfwOpenWindow(width, height, 8, 8, 8, 8, bytesPerPixel * 8, 0, fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOW)) { throw Exception("Failed to create window."); } glfwDisable(GLFW_MOUSE_CURSOR); glfwSetWindowTitle(getName().c_str()); glfwSetKeyCallback(keyCallback); glfwSetMousePosCallback(mousePosCallback); glfwSetMouseButtonCallback(mouseButtonCallback); setMouseOrigin(Vector<2, int>(width/2, height/2)); if (verticleSync) { glfwSwapInterval(1); } else { glfwSwapInterval(0); } 

And the SDL code:
 int videoFlags; const SDL_VideoInfo *videoInfo; videoInfo = SDL_GetVideoInfo(); if (!videoInfo) { String error(SDL_GetError()); SDL_Quit(); throw Exception("Failed: " + error); } videoFlags = SDL_OPENGL; videoFlags |= SDL_GL_DOUBLEBUFFER; videoFlags |= SDL_HWPALETTE; SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); if (videoInfo->hw_available) { videoFlags |= SDL_HWSURFACE; } else { videoFlags |= SDL_SWSURFACE; } if (videoInfo->blit_hw) { videoFlags |= SDL_HWACCEL; } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if (!SDL_SetVideoMode(width, height, bytesPerPixel * 8, videoFlags)) { String error(SDL_GetError()); SDL_Quit(); throw Exception("Failed: " + error); } SDL_ShowCursor(0); 

Note that my renderer uses deferred shading and therefore heavily relies on frame buffer objects. I am currently developing on Windows 7. Any help is appreciated.

##### Share on other sites
are you relying on the libraries' own 2D drawing stuff?

if so performance penalty might be because SDL's internal 2D drawing doesn't rely on OpenGL.

##### Share on other sites
Can you post a minimal program reproducing this behaviour?

Your SDL code is quite unusual, when dealing with OpenGL you generally just pass SDL_OPENGL (possibly with SDL_FULLSCREEN) to SDL_SetVideoMode(). Most of the other flags you are setting probably shouldn't be used.

##### Share on other sites
My engine isnt using FBO's yet, but when I did a quick speedtest before starting I found SDL to be MUCH faster that GLFW

##### Share on other sites
You could try taking a look at your SDL event snippet of your code. When I first started using SDL, I made the mistake of not specifying all the events that I wanted to have actually be taken for the program. Instead, it checked all events, keyboard, mouse, OS specific, joypad, etc. Optimizing the code for only the events I wanted, it reduced resource usage dramatically.

##### Share on other sites
Thanks for the quick replies everyone.

are you relying on the libraries' own 2D drawing stuff?

if so performance penalty might be because SDL's internal 2D drawing doesn't rely on OpenGL.

No.

Can you post a minimal program reproducing this behaviour?

That is quite impossible as my engine is fairly complex.

Can you post a minimal program reproducing this behaviour?

Your SDL code is quite unusual, when dealing with OpenGL you generally just pass SDL_OPENGL (possibly with SDL_FULLSCREEN) to SDL_SetVideoMode(). Most of the other flags you are setting probably shouldn't be used.

I tried getting rid of everything else and just calling SDL_SetVideoMode with SDL_OPENGL and saw no observable difference. At least the code is considerably shorter.

You could try taking a look at your SDL event snippet of your code. When I first started using SDL, I made the mistake of not specifying all the events that I wanted to have actually be taken for the program. Instead, it checked all events, keyboard, mouse, OS specific, joypad, etc. Optimizing the code for only the events I wanted, it reduced resource usage dramatically.

This might be on the right track. I added an event filter and got smoother framerate but it is still hovering around 70 which is concerning. Here is my event code. It is just translating keyboard and mouse events to internally represented events and put into the queue.

 int filter(SDL_Event* event) { switch(event->type) { case SDL_KEYDOWN: case SDL_KEYUP: case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: case SDL_QUIT: return 1; default: return 0; } } SDL_SetEventFilter((SDL_EventFilter)&filter); // Called on window creation. void SDLWindow::swapBuffers() { SDL_GL_SwapBuffers(); SDL_Event event; Vector<2, int> mouseOrigin = getMouseOrigin(); while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYDOWN: pushInputEvent(InputEvent(InputEventType::KeyDown, mouseOrigin, (Key::Enum)(int)event.key.keysym.sym)); break; case SDL_KEYUP: pushInputEvent(InputEvent(InputEventType::KeyUp, mouseOrigin, (Key::Enum)(int)event.key.keysym.sym)); break; case SDL_MOUSEMOTION: pushInputEvent(InputEvent(InputEventType::MouseMove, Vector<2, int>((int)event.motion.x, (int)event.motion.y))); break; case SDL_MOUSEBUTTONDOWN: pushInputEvent(InputEvent(InputEventType::KeyDown, mouseOrigin, (Key::Enum)(int)event.button.button)); break; case SDL_MOUSEBUTTONUP: pushInputEvent(InputEvent(InputEventType::KeyUp, mouseOrigin, (Key::Enum)(int)event.button.button)); break; case SDL_QUIT: break; default: break; } } } 

##### Share on other sites
Not quite sure if this will work, but you could try removing the default case in that event switch statement. If I recall, that was the resource-hungry checker in my code in one of my first projects using SDL. I believe the theory I had behind it was "I told it to check these events, but I'm guessing that if none of the events that I've specified are the event that has occurred, then default must be being called for every single event that's possible excluding the ones that I've already specified in my cases.". Sorry if that doesn't make much sense, I'm in a room of very loud people, and it's hard to think when your head is pounding .

Tell us if that works ( cross your fingers! ).

EDIT: You might also check for your games refresh timer/loop. See if you have already limited your frame rate ( or just the amount of times your main loop is refreshed ). I usually keep mine at 20 for small 2D games, and 60 for everything else.

##### Share on other sites
Thanks for the reply.

Not quite sure if this will work, but you could try removing the default case in that event switch statement. If I recall, that was the resource-hungry checker in my code in one of my first projects using SDL. I believe the theory I had behind it was "I told it to check these events, but I'm guessing that if none of the events that I've specified are the event that has occurred, then default must be being called for every single event that's possible excluding the ones that I've already specified in my cases.". Sorry if that doesn't make much sense, I'm in a room of very loud people, and it's hard to think when your head is pounding .

Tell us if that works ( cross your fingers! ).

I tried this and it had no effect. Which makes sense because with my event filter in place I am only receiving 0-3 events per frame.

EDIT: You might also check for your games refresh timer/loop. See if you have already limited your frame rate ( or just the amount of times your main loop is refreshed ). I usually keep mine at 20 for small 2D games, and 60 for everything else.

My main-loop should not having anything to do with it since when I use GLFW I am not having this problem.

##### Share on other sites
With that kind of framerate drop, you're doing something wrong.

First thing is - as always with framerates in that kind of region - check for vsync.

I note that you're asking for a 16-bit depth buffer. Double check what you actually get (SDL_GL_GetAttribute) and also double-check that you're not getting stencil as well. It's common enough (not widespread but I've seen it happen a few times) for OpenGL context creation to give you stencil even if you didn't ask for it (or asked for 0 bits), and if so, you should be clearing stencil at the same time as you clear depth. That will only account for a ~10% to ~20% perf drop, but it's still significant enough.

If you're doing an SDL_Sleep at the end of each frame, then stop doing it now. SDL's timer is quite coarse with poor resolution, and SDL_Sleep guarantees a minimum sleep time, not a maximum or exact. You may be sleeping for a lot longer than you think you are.

Any reason for the SDL_HWPALETTE? You're not trying to use OpenGL in color index mode are you? Take it out back and shoot it, you might be getting some weird pixel format that's dropping stuff to software emulation. While you're at it, drop your startup flags to the bare minimum. Rip out everything that's not needed - start with what was suggested above and only add in what you actually need to support your program.

So start with that, see how you get on, and report back.

##### Share on other sites
Thanks for the reply. The SDL init code is a copy paste from the old NEHE tutorials. I did try removing all flags but SDL_OPENGL and I got the same results. Vsync is turned off. I don't use the stencil buffer but I don't really care if there is one or not. In GLFW I tried using 8 bits-per-pixel, 24 bit depth, and 24 bit stencil and it worked great. I tried the exact same options in SDL and got the same frame-rate drop and stuttering:

 SDL_SetEventFilter((SDL_EventFilter)&filter); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 0); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if (!SDL_SetVideoMode(width, height, bytesPerPixel * 8, SDL_OPENGL)) { String error(SDL_GetError()); SDL_Quit(); throw Exception("Failed: " + error); } SDL_ShowCursor(0); 

I have tried messing with the values and commenting out lines and nothing seems to affect my results. My OpenGL code does not generate any OpenGL errors and I have run it with gDEbugger and removed all deprecated, redundant, and erroneous calls. I really have no idea how I could be having such dramatically differing results. I am considering digging through SDL and GLFW to see how the native code differs between the two.

##### Share on other sites
Sorry what I said didn't work. Other than what I said, I'm out of ideas .

##### Share on other sites
You don't need to post your entire engine. Just the basic OpenGL/SDL initialisation code, the event code and a drawing loop that does nothing. Enough to demonstrate the problem, nothing more.

##### Share on other sites

You don't need to post your entire engine. Just the basic OpenGL/SDL initialisation code, the event code and a drawing loop that does nothing. Enough to demonstrate the problem, nothing more.

I see. I have shown all of my SDL code and my OpenGL code is fairly minimal (just VBOs, FBOs, Textures, and shaders). However I'm not sure if the change in frame-rate would be apparent with no drawing. In fact I'm pretty sure it will not be observable as my main menu GUI is not considerably slower with SDL, only when the in-game scene is rendered which is rather complex.

Thanks for the reply; I appreciate the help. I'm considering sticking with GLFW for awhile since graphics API independence is not super important right now and perhaps as my engine matures this issue will disappear as it seems that the slow down may not be directly related to SDL.

• 12
• 10
• 10
• 11
• 18
• ### Similar Content

• Good Evening,
I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
I am really stucked right now because of the fundamental question:
Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on.
In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
Should I treat those debug objects as entities/components?
For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
Regards,
LifeArtist
• By QQemka
Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
Let's go:
Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
There were several more but i forgot/solved them at time of writing
• By RenanRR
Hi All,
I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
#version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);
So, some doubts:
- Why use it like that?
- Is it okay to manipulate the camera that way?
-in this way, are not the vertex's positions that changes instead of the camera?
- I need to pass MVP to all shaders of object in my scenes ?

What it seems, is that the camera stands still and the scenery that changes...
it's right?

Thank you

• Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

int rgbValue = int(textureSample.w);//4 bytes of data packed as color
// algorithm might not be correct and endianness might need switching.
vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
extractedData /= 255.0f;

• While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
Anyone has any idea .. what should I do?