custom_drawing_in_2d.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. .. _doc_custom_drawing_in_2d:
  2. Custom drawing in 2D
  3. ====================
  4. Introduction
  5. ------------
  6. Godot has nodes to draw sprites, polygons, particles, and all sorts of
  7. stuff. For most cases, this is enough; but not always. Before crying in fear,
  8. angst, and rage because a node to draw that specific *something* does not exist...
  9. it would be good to know that it is possible to easily make any 2D node (be it
  10. :ref:`Control <class_Control>` or :ref:`Node2D <class_Node2D>`
  11. based) draw custom commands. It is *really* easy to do it, too.
  12. Custom drawing in a 2D node is *really* useful. Here are some use cases:
  13. - Drawing shapes or logic that existing nodes can't do, such as an image
  14. with trails or a special animated polygon.
  15. - Visualizations that are not that compatible with nodes, such as a
  16. tetris board. (The tetris example uses a custom draw function to draw
  17. the blocks.)
  18. - Drawing a large number of simple objects. Custom drawing avoids the
  19. overhead of using a large number of nodes, possibly lowering memory
  20. usage and improving performance.
  21. - Making a custom UI control. There are plenty of controls available,
  22. but when you have unusual needs, you will likely need a custom
  23. control.
  24. Drawing
  25. -------
  26. Add a script to any :ref:`CanvasItem <class_CanvasItem>`
  27. derived node, like :ref:`Control <class_Control>` or
  28. :ref:`Node2D <class_Node2D>`. Then override the ``_draw()`` function.
  29. .. tabs::
  30. .. code-tab:: gdscript GDScript
  31. extends Node2D
  32. func _draw():
  33. # Your draw commands here
  34. pass
  35. .. code-tab:: csharp
  36. public override void _Draw()
  37. {
  38. // Your draw commands here
  39. }
  40. Draw commands are described in the :ref:`CanvasItem <class_CanvasItem>`
  41. class reference. There are plenty of them.
  42. Updating
  43. --------
  44. The ``_draw()`` function is only called once, and then the draw commands
  45. are cached and remembered, so further calls are unnecessary.
  46. If re-drawing is required because a state or something else changed,
  47. call :ref:`CanvasItem.update() <class_CanvasItem_method_update>`
  48. in that same node and a new ``_draw()`` call will happen.
  49. Here is a little more complex example, a texture variable that will be
  50. redrawn if modified:
  51. .. tabs::
  52. .. code-tab:: gdscript GDScript
  53. extends Node2D
  54. export (Texture) var texture setget _set_texture
  55. func _set_texture(value):
  56. # If the texture variable is modified externally,
  57. # this callback is called.
  58. texture = value # Texture was changed.
  59. update() # Update the node's visual representation.
  60. func _draw():
  61. draw_texture(texture, Vector2())
  62. .. code-tab:: csharp
  63. public class CustomNode2D : Node2D
  64. {
  65. private Texture _texture;
  66. public Texture Texture
  67. {
  68. get
  69. {
  70. return _texture;
  71. }
  72. set
  73. {
  74. _texture = value;
  75. Update();
  76. }
  77. }
  78. public override void _Draw()
  79. {
  80. DrawTexture(_texture, new Vector2());
  81. }
  82. }
  83. In some cases, it may be desired to draw every frame. For this, just
  84. call ``update()`` from the ``_process()`` callback, like this:
  85. .. tabs::
  86. .. code-tab:: gdscript GDScript
  87. extends Node2D
  88. func _draw():
  89. # Your draw commands here
  90. pass
  91. func _process(delta):
  92. update()
  93. .. code-tab:: csharp
  94. public class CustomNode2D : Node2D
  95. {
  96. public override void _Draw()
  97. {
  98. // Your draw commands here
  99. }
  100. public override void _Process(float delta)
  101. {
  102. Update();
  103. }
  104. }
  105. An example: drawing circular arcs
  106. ----------------------------------
  107. We will now use the custom drawing functionality of the Godot Engine to draw
  108. something that Godot doesn't provide functions for. As an example, Godot provides
  109. a ``draw_circle()`` function that draws a whole circle. However, what about drawing a
  110. portion of a circle? You will have to code a function to perform this and draw it yourself.
  111. Arc function
  112. ^^^^^^^^^^^^
  113. An arc is defined by its support circle parameters, that is, the center position
  114. and the radius. The arc itself is then defined by the angle it starts from
  115. and the angle at which it stops. These are the 4 arguments that we have to provide to our drawing function.
  116. We'll also provide the color value, so we can draw the arc in different colors if we wish.
  117. Basically, drawing a shape on the screen requires it to be decomposed into a certain number of points
  118. linked from one to the next. As you can imagine, the more points your shape is made of,
  119. the smoother it will appear, but the heavier it will also be in terms of processing cost. In general,
  120. if your shape is huge (or in 3D, close to the camera), it will require more points to be drawn without
  121. it being angular-looking. On the contrary, if your shape is small (or in 3D, far from the camera),
  122. you may decrease its number of points to save processing costs; this is known as *Level of Detail (LOD)*.
  123. In our example, we will simply use a fixed number of points, no matter the radius.
  124. .. tabs::
  125. .. code-tab:: gdscript GDScript
  126. func draw_circle_arc(center, radius, angle_from, angle_to, color):
  127. var nb_points = 32
  128. var points_arc = PoolVector2Array()
  129. for i in range(nb_points + 1):
  130. var angle_point = deg2rad(angle_from + i * (angle_to-angle_from) / nb_points - 90)
  131. points_arc.push_back(center + Vector2(cos(angle_point), sin(angle_point)) * radius)
  132. for index_point in range(nb_points):
  133. draw_line(points_arc[index_point], points_arc[index_point + 1], color)
  134. .. code-tab:: csharp
  135. public void DrawCircleArc(Vector2 center, float radius, float angleFrom, float angleTo, Color color)
  136. {
  137. int nbPoints = 32;
  138. var pointsArc = new Vector2[nbPoints];
  139. for (int i = 0; i < nbPoints; ++i)
  140. {
  141. float anglePoint = Mathf.Deg2Rad(angleFrom + i * (angleTo - angleFrom) / nbPoints - 90f);
  142. pointsArc[i] = center + new Vector2(Mathf.Cos(anglePoint), Mathf.Sin(anglePoint)) * radius;
  143. }
  144. for (int i = 0; i < nbPoints - 1; ++i)
  145. DrawLine(pointsArc[i], pointsArc[i + 1], color);
  146. }
  147. Remember the number of points our shape has to be decomposed into? We fixed this
  148. number in the ``nb_points`` variable to a value of ``32``. Then, we initialize an empty
  149. ``PoolVector2Array``, which is simply an array of ``Vector2``\ s.
  150. The next step consists of computing the actual positions of these 32 points that
  151. compose an arc. This is done in the first for-loop: we iterate over the number of
  152. points for which we want to compute the positions, plus one to include the last point.
  153. We first determine the angle of each point, between the starting and ending angles.
  154. The reason why each angle is decreased by 90° is that we will compute 2D positions
  155. out of each angle using trigonometry (you know, cosine and sine stuff...). However,
  156. to be simple, ``cos()`` and ``sin()`` use radians, not degrees. The angle of 0° (0 radian)
  157. starts at 3 o'clock, although we want to start counting at 12 o'clock. So we decrease
  158. each angle by 90° in order to start counting from 12 o'clock.
  159. The actual position of a point located on a circle at angle ``angle`` (in radians)
  160. is given by ``Vector2(cos(angle), sin(angle))``. Since ``cos()`` and ``sin()`` return values
  161. between -1 and 1, the position is located on a circle of radius 1. To have this
  162. position on our support circle, which has a radius of ``radius``, we simply need to
  163. multiply the position by ``radius``. Finally, we need to position our support circle
  164. at the ``center`` position, which is performed by adding it to our ``Vector2`` value.
  165. Finally, we insert the point in the ``PoolVector2Array`` which was previously defined.
  166. Now, we need to actually draw our points. As you can imagine, we will not simply
  167. draw our 32 points: we need to draw everything that is between each of them.
  168. We could have computed every point ourselves using the previous method, and drew
  169. it one by one. But this is too complicated and inefficient (except if explicitly needed),
  170. so we simply draw lines between each pair of points. Unless the radius of our
  171. support circle is big, the length of each line between a pair of points will
  172. never be long enough to see them. If that were to happen, we would simply need to
  173. increase the number of points.
  174. Draw the arc on the screen
  175. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  176. We now have a function that draws stuff on the screen;
  177. it is time to call it inside the ``_draw()`` function:
  178. .. tabs::
  179. .. code-tab:: gdscript GDScript
  180. func _draw():
  181. var center = Vector2(200, 200)
  182. var radius = 80
  183. var angle_from = 75
  184. var angle_to = 195
  185. var color = Color(1.0, 0.0, 0.0)
  186. draw_circle_arc(center, radius, angle_from, angle_to, color)
  187. .. code-tab:: csharp
  188. public override void _Draw()
  189. {
  190. var center = new Vector2(200, 200);
  191. float radius = 80;
  192. float angleFrom = 75;
  193. float angleTo = 195;
  194. var color = new Color(1, 0, 0);
  195. DrawCircleArc(center, radius, angleFrom, angleTo, color);
  196. }
  197. Result:
  198. .. image:: img/result_drawarc.png
  199. Arc polygon function
  200. ^^^^^^^^^^^^^^^^^^^^
  201. We can take this a step further and not only write a function that draws the plain
  202. portion of the disc defined by the arc, but also its shape. The method is exactly
  203. the same as before, except that we draw a polygon instead of lines:
  204. .. tabs::
  205. .. code-tab:: gdscript GDScript
  206. func draw_circle_arc_poly(center, radius, angle_from, angle_to, color):
  207. var nb_points = 32
  208. var points_arc = PoolVector2Array()
  209. points_arc.push_back(center)
  210. var colors = PoolColorArray([color])
  211. for i in range(nb_points + 1):
  212. var angle_point = deg2rad(angle_from + i * (angle_to - angle_from) / nb_points - 90)
  213. points_arc.push_back(center + Vector2(cos(angle_point), sin(angle_point)) * radius)
  214. draw_polygon(points_arc, colors)
  215. .. code-tab:: csharp
  216. public void DrawCircleArcPoly(Vector2 center, float radius, float angleFrom, float angleTo, Color color)
  217. {
  218. int nbPoints = 32;
  219. var pointsArc = new Vector2[nbPoints + 1];
  220. pointsArc[0] = center;
  221. var colors = new Color[] { color };
  222. for (int i = 0; i < nbPoints; ++i)
  223. {
  224. float anglePoint = Mathf.Deg2Rad(angleFrom + i * (angleTo - angleFrom) / nbPoints - 90);
  225. pointsArc[i + 1] = center + new Vector2(Mathf.Cos(anglePoint), Mathf.Sin(anglePoint)) * radius;
  226. }
  227. DrawPolygon(pointsArc, colors);
  228. }
  229. .. image:: img/result_drawarc_poly.png
  230. Dynamic custom drawing
  231. ^^^^^^^^^^^^^^^^^^^^^^
  232. All right, we are now able to draw custom stuff on the screen. However, it is static;
  233. let's make this shape turn around the center. The solution to do this is simply
  234. to change the angle_from and angle_to values over time. For our example,
  235. we will simply increment them by 50. This increment value has to remain
  236. constant or else the rotation speed will change accordingly.
  237. First, we have to make both angle_from and angle_to variables global at the top
  238. of our script. Also note that you can store them in other nodes and access them
  239. using ``get_node()``.
  240. .. tabs::
  241. .. code-tab:: gdscript GDScript
  242. extends Node2D
  243. var rotation_angle = 50
  244. var angle_from = 75
  245. var angle_to = 195
  246. .. code-tab:: csharp
  247. public class CustomNode2D : Node2D
  248. {
  249. private float _rotationAngle = 50;
  250. private float _angleFrom = 75;
  251. private float _angleTo = 195;
  252. }
  253. We make these values change in the _process(delta) function.
  254. We also increment our angle_from and angle_to values here. However, we must not
  255. forget to ``wrap()`` the resulting values between 0 and 360°! That is, if the angle
  256. is 361°, then it is actually 1°. If you don't wrap these values, the script will
  257. work correctly, but the angle values will grow bigger and bigger over time until
  258. they reach the maximum integer value Godot can manage (``2^31 - 1``).
  259. When this happens, Godot may crash or produce unexpected behavior.
  260. Finally, we must not forget to call the ``update()`` function, which automatically
  261. calls ``_draw()``. This way, you can control when you want to refresh the frame.
  262. .. tabs::
  263. .. code-tab:: gdscript GDScript
  264. func _process(delta):
  265. angle_from += rotation_angle
  266. angle_to += rotation_angle
  267. # We only wrap angles when both of them are bigger than 360.
  268. if angle_from > 360 and angle_to > 360:
  269. angle_from = wrapf(angle_from, 0, 360)
  270. angle_to = wrapf(angle_to, 0, 360)
  271. update()
  272. .. code-tab:: csharp
  273. public override void _Process(float delta)
  274. {
  275. _angleFrom += _rotationAngle;
  276. _angleTo += _rotationAngle;
  277. // We only wrap angles when both of them are bigger than 360.
  278. if (_angleFrom > 360 && _angleTo > 360)
  279. {
  280. _angleFrom = Mathf.Wrap(_angleFrom, 0, 360);
  281. _angleTo = Mathf.Wrap(_angleTo, 0, 360);
  282. }
  283. Update();
  284. }
  285. Also, don't forget to modify the ``_draw()`` function to make use of these variables:
  286. .. tabs::
  287. .. code-tab:: gdscript GDScript
  288. func _draw():
  289. var center = Vector2(200, 200)
  290. var radius = 80
  291. var color = Color(1.0, 0.0, 0.0)
  292. draw_circle_arc( center, radius, angle_from, angle_to, color )
  293. .. code-tab:: csharp
  294. public override void _Draw()
  295. {
  296. var center = new Vector2(200, 200);
  297. float radius = 80;
  298. var color = new Color(1, 0, 0);
  299. DrawCircleArc(center, radius, _angleFrom, _angleTo, color);
  300. }
  301. Let's run!
  302. It works, but the arc is rotating insanely fast! What's wrong?
  303. The reason is that your GPU is actually displaying the frames as fast as it can.
  304. We need to "normalize" the drawing by this speed; to achieve that, we have to make
  305. use of the ``delta`` parameter of the ``_process()`` function. ``delta`` contains the
  306. time elapsed between the two last rendered frames. It is generally small
  307. (about 0.0003 seconds, but this depends on your hardware), so using ``delta`` to
  308. control your drawing ensures that your program runs at the same speed on
  309. everybody's hardware.
  310. In our case, we simply need to multiply our ``rotation_angle`` variable by ``delta``
  311. in the ``_process()`` function. This way, our 2 angles will be increased by a much
  312. smaller value, which directly depends on the rendering speed.
  313. .. tabs::
  314. .. code-tab:: gdscript GDScript
  315. func _process(delta):
  316. angle_from += rotation_angle * delta
  317. angle_to += rotation_angle * delta
  318. # We only wrap angles when both of them are bigger than 360.
  319. if angle_from > 360 and angle_to > 360:
  320. angle_from = wrapf(angle_from, 0, 360)
  321. angle_to = wrapf(angle_to, 0, 360)
  322. update()
  323. .. code-tab:: csharp
  324. public override void _Process(float delta)
  325. {
  326. _angleFrom += _rotationAngle * delta;
  327. _angleTo += _rotationAngle * delta;
  328. // We only wrap angles when both of them are bigger than 360.
  329. if (_angleFrom > 360 && _angleTo > 360)
  330. {
  331. _angleFrom = Wrap(_angleFrom, 0, 360);
  332. _angleTo = Wrap(_angleTo, 0, 360);
  333. }
  334. Update();
  335. }
  336. Let's run again! This time, the rotation displays fine!
  337. Antialiased drawing
  338. ^^^^^^^^^^^^^^^^^^^
  339. Godot offers method parameters in :ref:`draw_line<class_CanvasItem_method_draw_line>`
  340. to enable antialiasing, but it doesn't work reliably in all situations
  341. (for instance, on mobile/web platforms, or when HDR is enabled).
  342. There is also no ``antialiased`` parameter available in
  343. :ref:`draw_polygon<class_CanvasItem_method_draw_polygon>`.
  344. As a workaround, install and use the
  345. `Antialiased Line2D add-on <https://github.com/godot-extended-libraries/godot-antialiased-line2d>`__
  346. (which also supports antialiased Polygon2D drawing). Note that this add-on relies
  347. on high-level nodes, rather than low-level ``_draw()`` functions.
  348. Tools
  349. -----
  350. Drawing your own nodes might also be desired while running them in the
  351. editor. This can be used as a preview or visualization of some feature or
  352. behavior. See :ref:`doc_running_code_in_the_editor` for more information.