I’m having some performance issues with large numbers of entities in a scene.
At the moment I am just creating large numbers of entities of 16x16 pixel sprites and adding them to the scene. The picture below shows the result of this.
I’m using this code to add the entities:
private void DrawCell(int startX, int startY, int length, Dictionary<string, SpriteComponent> spriteComponents)
{
var random = new Random(1);
for (int x = -length/2; x < length/2; x++)
{
for (int y = -length/2; y < length/2; y++)
{
var entity = new Entity();
switch (random.Next(2))
{
case 0:
entity.Add(spriteComponents["grass_sq_0"]);
break;
case 1:
entity.Add(spriteComponents["stone_sq_0"]);
break;
}
entity.Transform.Position = new Vector3(x + startX, y + startY, 0);
entity.Transform.Rotation = Player.Entity.Transform.Rotation;
SceneSystem.SceneInstance.Scene.AddChild(entity);
}
}
}
This works OK for small numbers of sprites, but the frame rate drops quite considerably as more of the map is drawn (which is to be expected).
In order to optimise this I’m looking to combine the sprites into a larger image, say 100x100 sprites which is 1600x1600 pixels. The map isn’t going to change an awful lot, and pushing one entity with one texture to the GPU should hopefully alleviate all performance issues.
What would be the best way to manage this? Here are the two options I’ve considered:
- Create the images in memory, never write them to file, and assign this texture to an entity on the fly. This should be OK, but you’ll have the drawback of possibly running out of RAM if the map is huge and out of view cells are not disposed of properly. This method means that you will potentially be creating the same chunks over and over again, as you move around the map, which seems like a waste of CPU. The disadvantage of this is I’ve no idea how to get the actual png file that contains the terrain sprites, and how to assign that to an entity in game.
- Create the images in memory, write them to file and then load them in via the already existing Game.Asset.Load() methods and assign them to an entity on the fly. Basically switch the advantages/disadvantages of #1 around. I think I will try this option and see how things go!
I’ve written quite a lot here without any real questions I guess. I’d just like confirmation that pushing lots of entities to the GPU every frame is the issue here, and that there’s not an already existing solution to my problem .