hashlink icon indicating copy to clipboard operation
hashlink copied to clipboard

With SDL backend on Windows, adding an element to a SpriteBatch can cause a large lag spike

Open csclyde opened this issue 1 year ago • 1 comments

I've been profiling my game recently, and found that when adding elements to a SpriteBatch (for a custom particle engine), it frequently creates a lag spike. I can confirm that it happens on the frame in which a particle is added, but I can't tell why certain adds trigger this behavior, and some do not. You can see a profile here, where frames are regularly dropped, corresponding to when a particle (BatchElement) is added to the SpriteBatch:

image

Zooming into the offending frame, you can see that the SpriteBatch flush is creating a massive delay:

image

Once it gets into allocBuffer, I have no clue what's happening. But I don't feel that I'm using the SpriteBatch improperly. I'm just creating a pool of BatchElement subclasses. Then periodically adding them to the SpriteBatch. Then, after a time, removing them from the sprite batch and returning them to the pool.

csclyde avatar Apr 01 '24 00:04 csclyde

You can try to setup a GPU buffer cache with hxd.impl.Allocator.set(new hxd.impl.CacheAllocator()) This will permit the reuse of GPU buffers for dynamic draws.

ncannasse avatar Apr 06 '24 09:04 ncannasse

After looking at the code some more, I realized that the SpriteBatch flush() was basically rebuilding the entire buffer every time an element got added, until the maximum amount of elements that were ever going to be in the batch were there. I solved it by simply instantiating the buffer to a reasonable size within my SpriteBatch subclass constructor

image

csclyde avatar Aug 13 '24 18:08 csclyde