Pygame: Blitting a moving background creates too much blur - python

What I am trying to do is create a viewport to view a small portion of a background. (And later put sprites in).
However the problem I have noticed is there seems to be an issue of the background blurring when it starts moving. I was not sure if this is because blitting is slow or because of a problem in the code. I was looking for examples on how others blit or create scrolling backgrounds and found this article: Scrolling Games
I used their simple example and sure enough the background appears blurry as you scroll (aka blit the background with an offset). I also thought it might be the FPS dropping for whatever reason however it doesn't deviate at all. I can't recall an issue like this with other 2D games. I understand there may be some motion blur due to it constantly shifting. Just wondering if I can do anything to alleviate this. Can someone chime in on anything I may be missing? I would appreciate any feedback or help. Thank you

I couldn't know what caused the problem you faced, but I guess it is related to double buffering.
Did you use at least two surfaces?
# preparing two surfaces in __init__()
screen = pygame.display.set_mode((800,600))
background = pygame.Surface(screen.get_size())
background.fill((250, 250, 250))
# called at every step in main loop
# draw images on the background surface
background.blit(image, position)
....
# blit background to screen
screen.blit(background, (0, 0))
pygame.display.flip()
If images are drawn on the screen surface directly, flicking occurs.

By "blurry" do you mean that the background appears "doubled"? Do you get the same effect when moving a normal-sized (e.g., 64x64) sprite?
If you are seeing double, then it's probably a refresh rate problem. Turning on vsync may help.
What frame rate are you getting?
If you slow down the animation to around 10 FPS, do you have the same problem?

Related

Replacing a surface instead of blitting to it

I'm having some performance issues in pygame, so I'm trying to optimize the rendering.
Currently, I'm blitting the background image to the display buffer:
self.display.blit(self.bg, (0, 0))
Instead, I'm looking for a way to replace the buffer with a copy of the background surface, and draw over that. This way, I don't have to blit a large image every frame, saving me some time.
Is there any way to do so?
It doesn't matter that much how often you blit something to the screen surface, since the display does only get updated once you call pygame.display.update or pygame.display.flip.
If you're sure that blitting the whole background image to the screen surface is a bottle neck in your game, you can try the following things:
a) Instead of blitting the whole background every frame, use the clear() function to "erase" your sprites from the screen.
b) Instead of calling pygame.display.flip or pygame.display.update without an argument, call pygame.display.update with the list of the areas on the screen that have been changed, which is returned by the draw() function (maybe in combination with clear()).
c) Create your display surface with the FULLSCREEN, DOUBLEBUF and HWSURFACE flags.
But as I already said: make sure you know where your bottle neck is. Some common performance pitfalls are: loading images multiple times from disk, font rendering, using different pixel formats (e.g. not calling convert/convert_alpha on surfaces created from images) and generally the lack of caching.
(also note that python/pygame is generally not the first choice when creating graphically demanding games)
Without seeing your code it will be hard to really see where the bottleneck is. Sloth is correct on his points as a way to optimize. in my experience all images should be pre-processed outside of the main game loop by drawing them onto their own surfaces. Blitting surfaces to surfaces is much faster than blitting images to surfaces.
img_surface = pygame.Surface((img_rect.width, img_rect.height), pygame.SRCALPHA)
img_surface.fill((0, 0, 0, 0))
img_surface.blit(get_image("my_image.png"), img_rect)
This happens outside the game loop. In the game loop you blit the image surface to your surface. If you really want to evaluate you code, use cProfile. This will help you nail down exactly where the bottleneck is. Do as much pre-processing outside the main game loop as possible.
Python getting meaningful results from cProfile
This link really helped me understand cProfile. Sloth is also correct in that pygame is limited, so you are going to need to optimize everything as much as you can. That is where cProfile comes in.
...Also, make sure you are only drawing things that are visible to the user. That can really help improve performance.

Failing to update pygame surfaces

I'm making a pygame game. I have 3 surfaces: gameDisplay (where the character and background is directly rendered to), guiSurf and invSurf
I have a clock made in core pyhon which displays the game time with the pygame font. I blit the clock to guiSurf and then in my gameloop I blit guiSurf and invSurf to gameDisplay. My problem is that the clock leaves a mark from where it was. IE when it changes from '07:00' to '07:01', the '01' is ontop of the '00' which shouldn't be there. I would post the code but theres like 400 lines. Does anyone have any idea what I may of done wrong. Link to a picture of the clock
Make sure you 'clear' the area of where the time is being printed by blitting another image over the spot where the text is. When you draw your surfaces to the screen it simply becomes one 'surface' that is always drawn until overwritten by something else. You need to clear this surface before you blit something else to it, otherwise you get the effect you see. By simple calling display_name.fill((0,0,0)) at the beginning of every game tick you will 'clear' the screen and then redraw your text onto it without the spillover effect. Of course you will have to reblit everything to the screen every tick, but this should not be a problem unless you need to blit thousands of items. If you do not wish to redraw everything, then blit a small rectangle over the text and then redraw it, and your issues should be solved.
I hope this helps you with your issue and happy coding!
Visibly, the clock is blitted twice on the guiSurf. And I guess it keeps stacking the previous image of time (7:00, then 7:01, then 7.02 and so on). You need to clear the surface holding the clock before drawing time into it : clock_surf.fill(clearcolor, clock_surf.get_rect()).

Is there a way to stretch the whole display image to fit a given resolution?

I've been using pygame to make a game recently, and have ran into a little problem...
Basically, I would like to be able to stretch the whole image that is on the screen (all the things that I have blitted to it) into the resolution which the user has resized the window to. I've searched a lot on the documentation for pygame and on stack overflow and I can't seem to find an answer... Is it even possible? The source code for my game is pretty big atm, if anyone needs it I'll be willing to post it. Sorry if I made my question a little unclear :)
Blit everything to a separate surface (not directly to the screen), let's call it main_surface. Then blit the main_surface to the screen.
Call pygame.transform.scale(main_surface, (width, height) with the new width and height that you get from the VIDEORESIZE event to scale the main_surface and everything in it to the new window dimensions.

Pygame (Python) Scale Transform Slow

I'm writing a simple program in python which takes in data over the serial port and updates the screen.
Because I want this program to look the same on whatever computer it runs on, and it needs to be fullscreen, I had the idea that I wanted to draw everything in a small 640, 480 window, and then scale it to a fullscreen window every time I update the frame.
This allows me to keep all the offsets the same for text, etc. It also turns out this is really slow.
Here's about what the important part of the code looks like:
window = pygame.display.set_mode((1920, 1080),pygame.FULLSCREEN)
screenPrescaled=pygame.Surface((640,480))
clock=pygame.time.Clock()
while iterations<400:
#Blit all the stuff to the prescaled surface here
screenPostscaled=pygame.transform.scale(screenPrescaled,(1920, 1080))
window.blit(screenPostscaled,(0,0))
pygame.display.flip()
iterations+=1
clock.tick(40)
This runs a WHOLE lot slower than 40fps.
Everything on the screen is either text or lines, there are no images loaded.
I suspect I'm doing something stupid.
I know I can update "dirty rectangles" only, but I wonder if I'm missing something more fundamental.
Thanks in advance!
You can save one blit by using window as destination surface:
pygame.transform.scale(screenPrescaled, (1920, 1080), window)
If it continues being too slow, you should use update rectangles, you can scale them using the same factor as you scale the image 1920/640 and 1080/480.
The simplest thing is instead of using
pygame.display.flip()
is to use
pygame.display.update()
It's not that big of a difference but it worked pretty well for me on my game, especially when it uses a lot of pictures.
You are updating a huge screen by display.flip(). In SDL (and that's behind pygame) that is not a good idea (try removing everything put the flip, and see how fast that runs, it shouldn't by to much faster).
I have no way to measure, but I would guess the reason your code takes a long time is a problem with the .flip().
Since you are only working with data in 640x480, why are you scaling it up to such a huge dimension? Try setting your screen to 640x480, and take a look at how fast it will be then. It should run four or five times faster, I would think.

How do I clear a pygame alpha layer efficiently?

I'm trying to write a 2D game using python / pygame that blits several layers on top of one another every screen refresh. My basic setup is (from bottom to top):
Background: surface (non-transparent), scrolls at a different rate than rest
Midground: SRCALPHA transparent surface (static)
Player / Sprites / Enemies: sprite group
Forground: SRCALPHA transparent surface (static)
Right now, I'm blitting these four layers one on top of another every screen. The background scrolls at a different rate than the other three layers, which is why I have it separate from midground. As I have the game structured now, it runs on my fairly modest laptop at 60fps.
-BUT- I'm having trouble with the sprite group, which I'm blitting directly to the screen. Having to adjust the rect for every sprite according to my current viewport seems like an ugly way to program things, and I'd like a more elegant solution.
I'd love to blit the sprites to another transparent surface which I could manage, but therin lies my problem: I can't find a way of clearing a transparent layer that doesn't half my performance. Some of the setups I've tried:
I've tried filling the layer with a white surface with blend mode rgba_sub (surf.fill((255,255,255,255), area, BLEND_RGBA_SUB)) -- this is super, super slow
I've tried surface.copy() of a blank surface - this is faster, but still halves my fps
I've tried combining the sprites with the midground layer and using pygame.sprite.LayeredUpdates to update the sprites. This has no effect on performance, but does not work where the midground is transparent. I get trails of sprites over the background layer.
The best solution I've found so far is my current setup of drawing sprites directly to the screen. It looks great, runs fast, but is a pain to manage, as I have to make sure each sprites' rect is adjusted according to the viewport every frame. Its also making collision detection difficult.
Is there another quick way to clear a pygame transparent surface? Quick as in, can be done 60+ times a second? Alternately, is there a setup for my layers that would still accomplish the same effect?
I figured out a fast way of clearing a sprites only transparent layer by applying Peter's solution selectively to the layer:
for s in self.level.sprites:
spritelayer.fill((0), s.rect)
This seems to be working fine (erasing everything each frame) and still runs at 60fps.
The Surface.fill() will clear all R, G, B, and A values.
>>> img = pygame.image.load("hasalpha.png")
>>> print img.get_at((300, 300))
(238, 240, 239, 255)
>>> surface.fill(0)
>>> print img.get_at((300, 300))
(0, 0, 0, 0)
It sounds like this will do what you are describing. If you are trying to do something more specific with the alpha values the pygame.surfarray.pixel functions can give you directly editable values. That will be quick, but requires numpy as a dependency.

Categories