SDL_LockTexture returning black pixels - c++

I'm currently following LazyFoo's SDL tutorial and I've reached the Texture Manipulation part but I'm running into a problem. The first time I call SDL_LockTexture it works fine to update the texture. However, after SDL_UnlockTexture, if I attempt to lock the texture again it now returns a pointer to a set of zeroed pixels, instead of what they were set to after the last unlock.
SDL_LockTexture(newTexture, NULL, &pixels, &pitch);
memcpy(pixels, formattedSurface->pixels, formattedSurface->pitch * formattedSurface->h);
SDL_UnlockTexture(newTexture);
pixels = NULL;
This is the initial code that copies the pixels of a loaded surface to an empty texture, and if rendered at this point it displays the correct image.
However, if the texture is locked and unlocked again then the image displayed is a black box (the value of each pixel being 0)
I'm completely stumped. Please let me know if any more is needed.

As stated on the wiki here the pixel data made available by SDL_LockTexture is intended only for writing data to a texture. It may not actually contain the current data for that texture. If you need a copy of a texture's pixel data you need to keep that stored somewhere else.

Related

Is it possible to have a display framebuffer in OpenGL

I want to display a 2D array of pixels directly to the screen. The pixel-data is not static and changes on user triggered event like a mousemove. I wish to have a display framebuffer to which I could write directly to the screen.
I have tried to create a texture with glTexImage2D(). I then render this texture to a QUAD. And then I update the texture with glTexSubImage2D() whenever a pixel is modified.
It works!
But this is not the efficient way I guess. The glTexSubImage2D copies whole array including the unmodified pixels back to the texture which is not good performance wise.
Is there any other way, like having a "display-framebuffer" to which I could write only the modified pixels and change will reflect on the screen.
glBlitFramebuffer is what you want.
Copies a rectangular block of pixels from one frame buffer to another. Can stretch or compress, but doesn't go through shaders and whatnot.
You'll probably also need some combination of glBindFramebuffer, glFramebufferTexture, glReadBuffer to set up the source and destination.

GL_COLOR_BUFFER_BIT regenerating which memory?

This is the code that probably all libgdx apps have:
Gdx.gl.glClearColor( 1, 0, 0, 1 );
Gdx.gl.glClear( GL20.GL_COLOR_BUFFER_BIT );
or
Gdx.gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);
This sets the color with witch the screen will be flushed(first line) and than flush it(second line). But what is the meaning of the GL20.GL_COLOR_BUFFER_BIT? From the docs I got that GL is an interface wrapping all the methods of OpenGL ES 2.0 and it is there so I can call methods. The meaning of GL_COLOR_BUFFER_BIT is puzzling to me. It should regenerate memory currently enabled for color writing... Does it mean that it would erase all images? Will it erase ShapeRenderer objects? Is anything on the screen that isn't part of color writing and will not be erased when this constant is used? Does GL_DEPTH_BUFFER_BIT erases the Z-position of textures?
When you draw things on the screen you dont draw them directly. Instead they are first drawn to a so called "back-buffer". This is a block of memory (a buffer) that contains four bytes for every pixel of the screen, one byte for each color component (red, green, blue and alpha) of each pixel. When you are ready drawing (when your render method finishes) this buffer is presented at once on the screen.
The existing value of the buffer is important. For example when you draw an image on the screen and then draw a semi transparent image on top of that, then the result is a mix of the two images. The first image is drawn to the back-buffer causing the memory of the back-buffer to contain the pixel data of that image. Next the second image is drawn and is blended on top of the existing data of the back-buffer.
Each byte of the block of memory always has a value, e.g. 0 for black, 255 for white, etc. Even if you havent drawn anything to the buffer it has to have some value. Calling glClear(GL20.GL_COLOR_BUFFER_BIT) instructs the GPU to fill the entire back buffer with some specified value (color). This value can be set using the call to glClearColor. Note that you don't have to call glClearColor each time glClear is called, the driver will remember the previous value.
Besides the back-buffer for the color values of the screen (the color buffer), the GPU can have other type of buffers, one of which is the depth buffer. This is again a block of memory of a few bytes per pixel, but this time it contains a depth value for each pixel. This makes it possible, e.g. when 3D rendering, to make sure that objects which are behind other objects are not being drawn. This buffer needs to be cleared using GL20.GL_DEPTH_BUFFER_BIT.
Note that you can clear both of them together using a bitwise or operation: Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
In practice, calling glClear should be the first thing you do in your render method (or when binding a FBO for example). This is because it tells the driver that you don't care about the existing values of the buffer. This allows the driver to do optimizations because it doesn't have to reconstruct (copy) the original memory block.

Zoom window in OpenGL

I've implemented Game of Life using OpenGL buffers (as specified here: http://www.glprogramming.com/red/chapter14.html#name20). In this implementation each pixel is a cell in the game.
My program receives the initial state of the game (2d array). The size array ,in my implementation, is the size of the window. This of course makes it "unplayable" if the array is 5x5 or some other small values.
At each iteration I'm reading the content of the framebuffer into a 2D array (its size is the window size):
glReadPixels(0, 0, win_x, win_y, GL_RGB, GL_UNSIGNED_BYTE, image);
Then, I'm doing the necessary steps to calculate the living and dead cells, and then draw a rectangle which covers the whole window, using:
glRectf(0, 0, win_x, win_y);
I want to zoom (or enlarge) the window without affecting the correctness of my code. If I resize the window, then the framebuffer content won't fit inside image(the array). Is there a way of zooming the window(so that each pixel be drawn as several pixels) without affecting the framebuffer?
First, you seem to be learning opengl 2, I would suggest instead learning a newer version, as it is more powerful and efficient. A good tutorial can be found here http://www.opengl-tutorial.org/
If i understand this correctly, you read in an initial state and draw it, then continuously read in the pixels on the screen, update the array based on the game of life logic then draw it back? this seems overly complicated.
The reading of the pixels on the screen is unnecessary, and will cause complications if you try to enlarge the rects to more than a pixel.
I would say a good solution would be to keep a bit array (1 is a organism, 0 is not), possibly as a 2d array in memory, updating the logic every say 30 iterations (for 30 fps), then drawing all the rects to the screen, black for 1, white for 0 using glColor(r,g,b,a) tied to an in statement in a nested for loop.
Then, if you give your rects a negative z coord, you can "zoom in" using glTranslate(x,y,z) triggered by a keyboard button.
Of course in a newer version of opengl, vertex buffers would make the code much cleaner and efficient.
You can't store your game state directly the window framebuffer and then resize it for rendering, since what is stored in the framebuffer is by definition what is about to be rendered. (You could overwrite it, but then you lose your game state...) The simplest solution would just to store the game state in an array (on the client side) and then update a texture based on that. Thus for each block that was set, you could set a pixel in a texture to be the appropriate color. Each frame, you then render a full screen quad with that texture (with GL_NEAREST filtering).
However, if you want to take advantage of your GPU there are some tricks that could massively speed up the simulation by using a fragment shader to generate the texture. In this case you would actually have two textures that you ping-pong between: one containing the current game state, and the other containing the next game state. Each frame you would use your fragment shader (along with a FBO) to generate the next state texture from the current state texture. Afterwards, the two textures are swapped, making the next state become the current state. The current state texture would then be rendered to the screen the same way as above.
I tried to give an overview of how you might be able to offload the computation onto the GPU, but if I was unclear anywhere just ask! For a more detailed explanation feel free to ask another question.

SDL: Combination of Tile sets and layered surfaces does not work

I would like to create a modularly designed game using SDL, but yet I fail to get my sprites displayed. Precisely, I am trying to implement tile sets, which are are bunch of equally sized sprites collected in one single PNG file (in my case).
My data structure should hold an array of sprites available in the tile set which can then be drawn with a method, like draw(Tile *, Position, Layer);.
As indicated, I want to feature multiple layers of surfaces to later on implement multiple independent background layers and a foreground layer. Similarly, I have an array of layers that are blitted onto my screen surface (created with SDL_SetVideoMode) in a pre-defined order.
However, I don't get what's going wrong in my code.
While a tile set is loaded, I can successfully blit the currently loaded tile onto a layer surface, like in this snippet:
this->graphic = SDL_CreateRGBSurface(SDL_HWSURFACE | SDL_SRCALPHA,
tile_widths, tile_heights, bit_depth,
rmask, gmask, bmask, amask);
SDL_BlitSurface(tileset_graphic, &tile_position, this->graphic, nullptr);
SDL_BlitSurface(tileset_graphic, &tile_position,
((VideoController::get_instance())->layers)[0], &tile_position);
In the first line, I try to blit the part of the tileset_graphic, that corresponds to a sprite, to an SDL_Surface * that is held by my Tile structure to be used later on.
However, I cannot use this surface to blit onto a layer.
The second (test) statement just copies the considered region of the tileset_graphic to the most bottom of my layers. Furthermore, I have performed several test commands in my main method.
My findings during testing:
I can blit a tileset_graphic piece to a layer and it is correctly shown (see above)
I can blit a Tile directly onto the screen:
SDL_BlitSurface(
tile->graphic,
nullptr,
(VideoController::the_instance)->screen,
&relative_position);
However, I cannot blit a Tile onto a layer:
SDL_BlitSurface(
tile->graphic,
nullptr,
(VideoController::the_instance)->layers[0],
&relative_position);
To be more precise, when I blit the whole tileset_graphic for testing and then blit a Tile onto a region that is already occupied due to this test, I can partly see my sprite. But then again, I have absolutely no clue why this is the case...
Summary:
I try to blit several SDL_Surfaces onto another, but seem to fail only by trying this (desired) chain of surfaces:
graphic --> layer --> screen
Does anyone have a clue what may go wrong, or is able to tell me which additional information is needed by you guys?
EDIT
I was able to find that blitting on the initialized (SDL_CreateRGBSurface), but still "untouched" layer surfaces seems to fail somehow. When I use SDL_FillRect on my layer surfaces before blitting a tile onto the layer, it is displayed correctly. However, I am losing transparency of layers this way...
I figured out the solution.
I had to explicitly reset the SDL_SRCALPHA flag of my graphic by doing
SDL_SetAlpha(this->graphic, 0, SDL_ALPHA_OPAQUE );

Copying SDL_Surfaces with Alpha Channels

I've run into issues preserving the alpha channels of surfaces being copied/clip blitted (blitting sections of a surface onto a smaller surface, they're spritesheets). I've tried various solutions, but the end result is that any surface that's supposed to have transparency ends up becoming fully opaque (alpha mask becomes white).
So my question is, how does one copy one RGBA SDL_Surface to another new surface (also RGBA), including the alpha channel? And if it's any different, how does one copy a section of an RGBA surface, to a new RGBA surface (the same size of the clipped portion of the source surface), ala tilesheet blitting.
It seems that SDL_BlitSurface blends the alpha channels, so when for example, I want to copy a tile from my tilesheet surface to a new surface (which is of course, blank, I'm assuming SDL fills surfaces with black or white by default), it ends up losing it's alpha mask, so that when that tile is finally blitted to the screen, it doesn't blend with whatever is on the screen.
SDL_DisplayFormatAlpha works great to copy surfaces with an alpha mask, but it doesn't take clip parameters, it's only intended to copy the entire surface, not a portion of it, hence my problem.
If anyone is still wondering after all these years:
Before bliting the surface, you need to make sure that the blending mode of the source (which is an SDL_Surface) is set to SDL_BLENDMODE_NONE as described in the documentation: SDL_SetSurfaceBlendMode(). Is should look something simple like this:
SDL_SetSurfaceBlendMode(source, SDL_BLENDMODE_BLEND);
SDL_BlitSurface(source, sourceRect, destination, destinationRect);
I had this problem before and have not come to an official answer yet.
However, I think the only way to do it will be to write your own copy function.
http://www.libsdl.org/docs/html/sdlpixelformat.html
This page will help you understand how SDL_Surface stores color information. Note that there is a huge difference between colors above and below 8 bits.