common_engine_methods_and_macros.rst 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. .. _doc_common_engine_methods_and_macros:
  2. Common engine methods and macros
  3. ================================
  4. Godot's C++ codebase makes use of dozens of custom methods and macros which are
  5. used in almost every file. This page is geared towards beginner contributors,
  6. but it can also be useful for those writing custom C++ modules.
  7. Print text
  8. ----------
  9. .. code-block:: cpp
  10. // Prints a message to standard output.
  11. print_line("Message");
  12. // Non-String arguments are automatically converted to String for printing.
  13. // If passing several arguments, they will be concatenated together with a
  14. // space between each argument.
  15. print_line("There are", 123, "nodes");
  16. // Prints a message to standard output, but only when the engine
  17. // is started with the `--verbose` command line argument.
  18. print_verbose("Message");
  19. // Prints a rich-formatted message using BBCode to standard output.
  20. // This supports a subset of BBCode tags supported by RichTextLabel
  21. // and will also appear formatted in the editor Output panel.
  22. // On Windows, this requires Windows 10 or later to work in the terminal.
  23. print_line_rich("[b]Bold[/b], [color=red]Red text[/color]")
  24. // Prints a formatted error or warning message with a trace.
  25. ERR_PRINT("Message");
  26. WARN_PRINT("Message");
  27. // Prints an error or warning message only once per session.
  28. // This can be used to avoid spamming the console output.
  29. ERR_PRINT_ONCE("Message");
  30. WARN_PRINT_ONCE("Message");
  31. If you need to add placeholders in your messages, use format strings as
  32. described below.
  33. Format a string
  34. ---------------
  35. The ``vformat()`` function returns a formatted :ref:`class_String`. It behaves
  36. in a way similar to C's ``sprintf()``:
  37. .. code-block:: cpp
  38. vformat("My name is %s.", "Godette");
  39. vformat("%d bugs on the wall!", 1234);
  40. vformat("Pi is approximately %f.", 3.1416);
  41. // Converts the resulting String into a `const char *`.
  42. // You may need to do this if passing the result as an argument
  43. // to a method that expects a `const char *` instead of a String.
  44. vformat("My name is %s.", "Godette").c_str();
  45. In most cases, try to use ``vformat()`` instead of string concatenation as it
  46. makes for more readable code.
  47. Convert an integer or float to a string
  48. ---------------------------------------
  49. This is not needed when printing numbers using ``print_line()``, but you may
  50. still need to perform manual conversion for some other use cases.
  51. .. code-block:: cpp
  52. // Stores the string "42" using integer-to-string conversion.
  53. String int_to_string = itos(42);
  54. // Stores the string "123.45" using real-to-string conversion.
  55. String real_to_string = rtos(123.45);
  56. Internationalize a string
  57. -------------------------
  58. There are two types of internationalization in Godot's codebase:
  59. - ``TTR()``: **Editor ("tools") translations** will only be processed in the
  60. editor. If a user uses the same text in one of their projects, it won't be
  61. translated if they provide a translation for it. When contributing to the
  62. engine, this is generally the macro you should use for localizable strings.
  63. - ``RTR()``: **Run-time translations** will be automatically localized in
  64. projects if they provide a translation for the given string. This kind of
  65. translation shouldn't be used in editor-only code.
  66. .. code-block:: cpp
  67. // Returns the translated string that matches the user's locale settings.
  68. // Translations are located in `editor/translations`.
  69. // The localization template is generated automatically; don't modify it.
  70. TTR("Exit the editor?");
  71. To insert placeholders in localizable strings, wrap the localization macro in a
  72. ``vformat()`` call as follows:
  73. .. code-block:: cpp
  74. String file_path = "example.txt";
  75. vformat(TTR("Couldn't open \"%s\" for reading."), file_path);
  76. .. note::
  77. When using ``vformat()`` and a translation macro together, always wrap the
  78. translation macro in ``vformat()``, not the other way around. Otherwise, the
  79. string will never match the translation as it will have the placeholder
  80. already replaced when it's passed to TranslationServer.
  81. Clamp a value
  82. -------------
  83. Godot provides macros for clamping a value with a lower bound (``MAX``), an
  84. upper bound (``MIN``) or both (``CLAMP``):
  85. .. code-block:: cpp
  86. int a = 3;
  87. int b = 5;
  88. MAX(b, 6); // 6
  89. MIN(2, a); // 2
  90. CLAMP(a, 10, 30); // 10
  91. This works with any type that can be compared to other values (like ``int`` and
  92. ``float``).
  93. Microbenchmarking
  94. -----------------
  95. If you want to benchmark a piece of code but don't know how to use a profiler,
  96. use this snippet:
  97. .. code-block:: cpp
  98. uint64_t begin = OS::get_singleton()->get_ticks_usec();
  99. // Your code here...
  100. uint64_t end = OS::get_singleton()->get_ticks_usec();
  101. print_line(vformat("Snippet took %d microseconds", end - begin));
  102. This will print the time spent between the ``begin`` declaration and the ``end``
  103. declaration.
  104. .. note::
  105. You may have to ``#include "core/os/os.h"`` if it's not present already.
  106. When opening a pull request, make sure to remove this snippet as well as the
  107. include if it wasn't there previously.
  108. Get project/editor settings
  109. ---------------------------
  110. There are four macros available for this:
  111. .. code-block:: cpp
  112. // Returns the specified project setting's value,
  113. // defaulting to `false` if it doesn't exist.
  114. GLOBAL_DEF("section/subsection/value", false);
  115. // Returns the specified editor setting's value,
  116. // defaulting to "Untitled" if it doesn't exist.
  117. EDITOR_DEF("section/subsection/value", "Untitled");
  118. If a default value has been specified elsewhere, don't specify it again to avoid
  119. repetition:
  120. .. code-block:: cpp
  121. // Returns the value of the project setting.
  122. GLOBAL_GET("section/subsection/value");
  123. // Returns the value of the editor setting.
  124. EDITOR_GET("section/subsection/value");
  125. It's recommended to use ``GLOBAL_DEF``/``EDITOR_DEF`` only once per setting and
  126. use ``GLOBAL_GET``/``EDITOR_GET`` in all other places where it's referenced.
  127. Error macros
  128. ------------
  129. Godot features many error macros to make error reporting more convenient.
  130. .. warning::
  131. Conditions in error macros work in the **opposite** way of GDScript's
  132. built-in ``assert()`` function. An error is reached if the condition inside
  133. evaluates to ``true``, not ``false``.
  134. .. note::
  135. Only variants with custom messages are documented here, as these should
  136. always be used in new contributions. Make sure the custom message provided
  137. includes enough information for people to diagnose the issue, even if they
  138. don't know C++. In case a method was passed invalid arguments, you can print
  139. the invalid value in question to ease debugging.
  140. For internal error checking where displaying a human-readable message isn't
  141. necessary, remove ``_MSG`` at the end of the macro name and don't supply a
  142. message argument.
  143. Also, always try to return processable data so the engine can keep running
  144. well.
  145. .. code-block:: cpp
  146. // Conditionally prints an error message and returns from the function.
  147. // Use this in methods which don't return a value.
  148. ERR_FAIL_COND_MSG(!mesh.is_valid(), vformat("Couldn't load mesh at: %s", path));
  149. // Conditionally prints an error message and returns `0` from the function.
  150. // Use this in methods which must return a value.
  151. ERR_FAIL_COND_V_MSG(rect.x < 0 || rect.y < 0, 0,
  152. "Couldn't calculate the rectangle's area.");
  153. // Prints an error message if `index` is < 0 or >= `SomeEnum::QUALITY_MAX`,
  154. // then returns from the function.
  155. ERR_FAIL_INDEX_MSG(index, SomeEnum::QUALITY_MAX,
  156. vformat("Invalid quality: %d. See SomeEnum for allowed values.", index));
  157. // Prints an error message if `index` is < 0 >= `some_array.size()`,
  158. // then returns `-1` from the function.
  159. ERR_FAIL_INDEX_V_MSG(index, some_array.size(), -1,
  160. vformat("Item %d is out of bounds.", index));
  161. // Unconditionally prints an error message and returns from the function.
  162. // Only use this if you need to perform complex error checking.
  163. if (!complex_error_checking_routine()) {
  164. ERR_FAIL_MSG("Couldn't reload the filesystem cache.");
  165. }
  166. // Unconditionally prints an error message and returns `false` from the function.
  167. // Only use this if you need to perform complex error checking.
  168. if (!complex_error_checking_routine()) {
  169. ERR_FAIL_V_MSG(false, "Couldn't parse the input arguments.");
  170. }
  171. // Crashes the engine. This should generally never be used
  172. // except for testing crash handling code. Godot's philosophy
  173. // is to never crash, both in the editor and in exported projects.
  174. CRASH_NOW_MSG("Can't predict the future! Aborting.");
  175. .. seealso::
  176. See `core/error/error_macros.h <https://github.com/godotengine/godot/blob/master/core/error/error_macros.h>`__
  177. in Godot's codebase for more information about each error macro.
  178. Some functions return an error code (materialized by a return type of
  179. ``Error``). This value can be returned directly from an error macro.
  180. See the list of available error codes in
  181. `core/error/error_list.h <https://github.com/godotengine/godot/blob/master/core/error/error_list.h>`__.