-
@friflo edit - renamed title. Was: "MonoGame Render GarbageCollection"; format code as C#; typo Im generation Garbage every frame because of the Delegate Allocation here. Any idea how to do it better? using App2;
using App2.Components;
using Friflo.Engine.ECS;
using Friflo.Engine.ECS.Systems;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
public class RenderSystem : QuerySystem<Position2D, Sprite>
{
private SpriteBatch _spriteBatch;
private TextureManager _textureManager;
public RenderSystem(SpriteBatch spriteBatch, TextureManager textureManager)
{
_spriteBatch = spriteBatch;
_textureManager = textureManager;
}
protected override void OnUpdate()
{
_spriteBatch.Begin();
Query.ForEachEntity((ref Position2D position, ref Sprite sprite, Entity entity) =>
{
var texture = _textureManager.GetTexture(sprite.TextureId);
_spriteBatch.Draw(
texture,
new Vector2(position.Value.X, position.Value.Y),
null,
sprite.Color,
0f,
new Vector2(texture.Width / 2, texture.Height / 2),
sprite.Scale,
SpriteEffects.None,
0f
);
});
_spriteBatch.End();
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
friflo
May 30, 2024
Replies: 1 comment
-
To avoid the allocation caused by the delegate you can use the approach explained in the Wiki - Enumerate Query Chunks This approach replaces foreach (var (positions, sprites, entities) in Query.Chunks)
{
for (int n = 0; n < positions.Length; n++) {
var position = positions[n];
var sprite = sprites[n];
var texture = _textureManager.GetTexture(sprite.TextureId);
_spriteBatch.Draw(...)
}
} If you like you can extract the inner block to a method. foreach (var (positions, sprites, entities) in Query.Chunks)
{
for (int n = 0; n < positions.Length; n++) {
Draw(position[n], sprites[n]);
}
}
void Draw(Position2D position, Sprite sprite) {
...
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
friflo
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To avoid the allocation caused by the delegate you can use the approach explained in the Wiki - Enumerate Query Chunks
This approach replaces
Query.ForEachEntity(...)
by two loops. This approach is allocation free.If you like you can extract the inner block to a method.