So, I’m making this little game where you have a flashlight. The flashlight is quite high resolution, so I need to precache 360 copies of it for every angle to avoid rotating it in realtime, which would take a lot of computing power. The image is 1002×246 and .png, but quite simple, so it only takes up 3.95KB on the hard drive. But when I make 360 copies of it in the game and add them to a list, they take around 800MB of RAM. That’s quite a lot. Why? How can I reduce it?
The code:
def flashlightinit():
init.flashlights = []
fl = files.flashlight
for i in range(360):
init.flashlights.append(pygame.transform.rotate(fl, -i))
The flashlight image is convert()ed and doesn’t have a colorkey or alpha-channel.
Displaying the flashlight:
def flashlightupdate(angle):
screen.blit(init.flashlights[angle], (340 - init.flashlights[angle].get_width()/2, 360 - init.flashlights[angle].get_height()/2))
Angle is degrees and is calculated from mouse’s position and from the player’s position.
Thanks.
I’m going to publish this as an answer, since grouping together some of the comments you are probably going to solve both memory and performance issues.
The high RAM usage is due to the number of images (360), which, even on disk, would occupy at least 266MB, as Dikei pointed out, and you have to consider that images are represented as pygame objects, thus using more memory than a raw bitmap.
To avoid using 800MB of RAM you, obviously, have to avoid creating all those images.
To maintain good performances you could cache only some images for the degrees 0-90°,
and then use flip operations, which are quite faster than rotations, to build the images for the other rotation angles(as pointed out by halex).
In this way you can surely consume about 1/4 of current RAM and still have comparable rendering speed.