Using graphics programming to create a Sprite2D

Godot Version

Version 4.5.1 stable

Question

Hello,

I’m trying to create Sprite2D images using pure graphics programming. I have been successful drawing on a CanvasItem using those graphics primitives. I don’t understand two things and I am looking for an answer:

  1. When I call a graphics primitive in my code, like calling the draw_ellipse() function, am I creating a raster / RGBA bitmap of some sort, or an object to be run in a render pipeline? I’ve noticed that the more I use the draw function (once, not per rendering moment), the slower the Godot engine runs.
  2. What’s the right way to make use of the graphics primitives to create Sprite2D images? I hope I will not have to rewrite all the graphics primitive functions using Image.fill_rect() ; that’s really annoying.
  3. [Bonus Question] If I put my image creation graphics code into a Shader, is it going to run faster/on the GPU?

Thank you for your time and consideration in responding to or answering these questions.
Sincerely,

-Vexar

  1. The final result is not a bitmap. It’s a series of cached draw calls. Your script function _draw() is typically called only once which will build the cache. This cache is then redrawn each frame. _draw() may be called again in some situations like viewport resize or if you force it using queue_redraw()

  2. A typical approach would be to draw into an offscreen buffer. Put a canvas item into a subviewport, execute your drawing commands on that canvas item and display the viewport texture on the sprite. The viewport can be set to re-draw only once so there won’t be any performance cost on subsequent frames.

  3. Technically it could be done but you’d still need to implement your own drawing functions in the shader. It may run faster but since you need to run it only once anyway it wouldn’t be much more efficient than 2. It’s simply not worth the effort.