custom_drawing_in_2d.rst 18 KB

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