Drawing 2D stuff with SDL_Renderer and OpenGL stuff with SDL_GLContext

房东的猫 提交于 2019-11-26 22:05:07

问题


I have been learning about SDL 2D programming for a while and now I wanted to create a program using SDL and OpenGL combined. I set it up like this:

SDL_Init(SDL_INIT_VIDEO);

window = SDL_CreateWindow("SDL and OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL);

context = SDL_GL_CreateContext(window);

The program is for now just a black window with a white line displayed using OpenGl. Here is the code for the rendering:

glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);         

glBegin(GL_LINES);     
glVertex2d(1, 0);
glVertex2d(-1, 0);
glEnd();

SDL_GL_SwapWindow(window);  

So the thing is, I would like to render textures additionally using pure SDL and a SDL_Renderer object, as I did before without OpenGL. I tried that out but it didn't work. Is it even possible to do that and how? What I did is creating a SDL_Renderer and then after drawing OpenGL stuff doing this:

SDL_Rect fillRect;
fillRect.w = 50;
fillRect.h = 50;
fillRect.x = 0;
fillRect.y = 0; 

SDL_SetRenderDrawColor(renderer, 100, 200, 100, 0);
SDL_RenderFillRect(renderer, &fillRect);

SDL_RenderPresent(renderer);    

But this does not work. The rectangle is not shown, although for some milliseconds it appears slightly. I feel like the OpenGL rendering is overwriting it.


回答1:


SDL uses OpenGL (or in some cases Direct3D) and OpenGL has internal state which affects the GL calls in your program. The current version of SDL does not clearly indicate which states it changes or depends upon for any call and it does not include functions to reset to a known state. That means you should not mix SDL_Renderer with OpenGL yet.

However, if you really want this functionality now, you can try SDL_gpu (note: I'm the author). It does support mixing with OpenGL calls and custom shaders. You would want to specify which version of the OpenGL API you need (e.g. with GPU_InitRenderer(GPU_RENDERER_OPENGL_1, ...)) and reset the GL state that SDL_gpu uses each frame (GPU_ResetRendererState()). Check out the 3d demo in the SDL_gpu source repository for more.

https://github.com/grimfang4/sdl-gpu/blob/master/demos/3d/main.c




回答2:


You can render to an SDL_Surface with SDL, and then convert it to a texture & upload it to the GPU using OpenGL.



来源:https://stackoverflow.com/questions/28307814/drawing-2d-stuff-with-sdl-renderer-and-opengl-stuff-with-sdl-glcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!