custom_modules_in_cpp.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. .. _doc_custom_modules_in_cpp:
  2. Custom modules in C++
  3. =====================
  4. Modules
  5. -------
  6. Godot allows extending the engine in a modular way. New modules can be
  7. created and then enabled/disabled. This allows for adding new engine
  8. functionality at every level without modifying the core, which can be
  9. split for use and reuse in different modules.
  10. Modules are located in the ``modules/`` subdirectory of the build system.
  11. By default, dozens of modules are enabled, such as GDScript (which, yes,
  12. is not part of the base engine), GridMap support, a regular expressions
  13. module, and others. As many new modules as desired can be
  14. created and combined. The SCons build system will take care of it
  15. transparently.
  16. What for?
  17. ---------
  18. While it's recommended that most of a game be written in scripting (as
  19. it is an enormous time saver), it's perfectly possible to use C++
  20. instead. Adding C++ modules can be useful in the following scenarios:
  21. - Binding an external library to Godot (like PhysX, FMOD, etc).
  22. - Optimize critical parts of a game.
  23. - Adding new functionality to the engine and/or editor.
  24. - Porting an existing game to Godot.
  25. - Write a whole, new game in C++ because you can't live without C++.
  26. .. note::
  27. While it is possible to use modules for custom game logic,
  28. :ref:`GDExtension <doc_gdextension>` is generally more suited as it doesn't
  29. require recompiling the engine after every code change.
  30. C++ modules are mainly needed when GDExtension doesn't suffice and deeper engine
  31. integration is required.
  32. Creating a new module
  33. ---------------------
  34. Before creating a module, make sure to :ref:`download the source code of Godot
  35. and compile it <toc-devel-compiling>`.
  36. To create a new module, the first step is creating a directory inside
  37. ``modules/``. If you want to maintain the module separately, you can checkout
  38. a different VCS into modules and use it.
  39. The example module will be called "summator" (``godot/modules/summator``).
  40. Inside we will create a summator class:
  41. .. code-block:: cpp
  42. :caption: godot/modules/summator/summator.h
  43. #pragma once
  44. #include "core/object/ref_counted.h"
  45. class Summator : public RefCounted {
  46. GDCLASS(Summator, RefCounted);
  47. int count;
  48. protected:
  49. static void _bind_methods();
  50. public:
  51. void add(int p_value);
  52. void reset();
  53. int get_total() const;
  54. Summator();
  55. };
  56. And then the cpp file.
  57. .. code-block:: cpp
  58. :caption: godot/modules/summator/summator.cpp
  59. #include "summator.h"
  60. void Summator::add(int p_value) {
  61. count += p_value;
  62. }
  63. void Summator::reset() {
  64. count = 0;
  65. }
  66. int Summator::get_total() const {
  67. return count;
  68. }
  69. void Summator::_bind_methods() {
  70. ClassDB::bind_method(D_METHOD("add", "value"), &Summator::add);
  71. ClassDB::bind_method(D_METHOD("reset"), &Summator::reset);
  72. ClassDB::bind_method(D_METHOD("get_total"), &Summator::get_total);
  73. }
  74. Summator::Summator() {
  75. count = 0;
  76. }
  77. Then, the new class needs to be registered somehow, so two more files
  78. need to be created:
  79. .. code-block:: none
  80. register_types.h
  81. register_types.cpp
  82. .. important::
  83. These files must be in the top-level folder of your module (next to your
  84. ``SCsub`` and ``config.py`` files) for the module to be registered properly.
  85. These files should contain the following:
  86. .. code-block:: cpp
  87. :caption: godot/modules/summator/register_types.h
  88. #include "modules/register_module_types.h"
  89. void initialize_summator_module(ModuleInitializationLevel p_level);
  90. void uninitialize_summator_module(ModuleInitializationLevel p_level);
  91. /* yes, the word in the middle must be the same as the module folder name */
  92. .. code-block:: cpp
  93. :caption: godot/modules/summator/register_types.cpp
  94. #include "register_types.h"
  95. #include "core/object/class_db.h"
  96. #include "summator.h"
  97. void initialize_summator_module(ModuleInitializationLevel p_level) {
  98. if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
  99. return;
  100. }
  101. ClassDB::register_class<Summator>();
  102. }
  103. void uninitialize_summator_module(ModuleInitializationLevel p_level) {
  104. if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
  105. return;
  106. }
  107. // Nothing to do here in this example.
  108. }
  109. Next, we need to create an ``SCsub`` file so the build system compiles
  110. this module:
  111. .. code-block:: python
  112. :caption: godot/modules/summator/SCsub
  113. # SCsub
  114. Import('env')
  115. env.add_source_files(env.modules_sources, "*.cpp") # Add all cpp files to the build
  116. With multiple sources, you can also add each file individually to a Python
  117. string list:
  118. .. code-block:: python
  119. src_list = ["summator.cpp", "other.cpp", "etc.cpp"]
  120. env.add_source_files(env.modules_sources, src_list)
  121. This allows for powerful possibilities using Python to construct the file list
  122. using loops and logic statements. Look at some modules that ship with Godot by
  123. default for examples.
  124. To add include directories for the compiler to look at you can append it to the
  125. environment's paths:
  126. .. code-block:: python
  127. env.Append(CPPPATH=["mylib/include"]) # this is a relative path
  128. env.Append(CPPPATH=["#myotherlib/include"]) # this is an 'absolute' path
  129. If you want to add custom compiler flags when building your module, you need to clone
  130. ``env`` first, so it won't add those flags to whole Godot build (which can cause errors).
  131. Example ``SCsub`` with custom flags:
  132. .. code-block:: python
  133. :caption: godot/modules/summator/SCsub
  134. Import('env')
  135. module_env = env.Clone()
  136. module_env.add_source_files(env.modules_sources, "*.cpp")
  137. # Append CCFLAGS flags for both C and C++ code.
  138. module_env.Append(CCFLAGS=['-O2'])
  139. # If you need to, you can:
  140. # - Append CFLAGS for C code only.
  141. # - Append CXXFLAGS for C++ code only.
  142. And finally, the configuration file for the module, this is a
  143. Python script that must be named ``config.py``:
  144. .. code-block:: python
  145. :caption: godot/modules/summator/config.py
  146. # config.py
  147. def can_build(env, platform):
  148. return True
  149. def configure(env):
  150. pass
  151. The module is asked if it's OK to build for the specific platform (in
  152. this case, ``True`` means it will build for every platform).
  153. And that's it. Hope it was not too complex! Your module should look like
  154. this:
  155. .. code-block:: none
  156. godot/modules/summator/config.py
  157. godot/modules/summator/summator.h
  158. godot/modules/summator/summator.cpp
  159. godot/modules/summator/register_types.h
  160. godot/modules/summator/register_types.cpp
  161. godot/modules/summator/SCsub
  162. You can then zip it and share the module with everyone else. When
  163. building for every platform (instructions in the previous sections),
  164. your module will be included.
  165. Using the module
  166. ----------------
  167. You can now use your newly created module from any script:
  168. .. tabs::
  169. .. code-tab:: gdscript GDScript
  170. var s = Summator.new()
  171. s.add(10)
  172. s.add(20)
  173. s.add(30)
  174. print(s.get_total())
  175. s.reset()
  176. The output will be ``60``.
  177. .. seealso:: The previous Summator example is great for small, custom modules,
  178. but what if you want to use a larger, external library? Refer to
  179. :ref:`doc_binding_to_external_libraries` for details about binding to
  180. external libraries.
  181. .. warning:: If your module is meant to be accessed from the running project
  182. (not just from the editor), you must also recompile every export
  183. template you plan to use, then specify the path to the custom
  184. template in each export preset. Otherwise, you'll get errors when
  185. running the project as the module isn't compiled in the export
  186. template. See the :ref:`Compiling <toc-devel-compiling>` pages
  187. for more information.
  188. Compiling a module externally
  189. -----------------------------
  190. Compiling a module involves moving the module's sources directly under the
  191. engine's ``modules/`` directory. While this is the most straightforward way to
  192. compile a module, there are a couple of reasons as to why this might not be a
  193. practical thing to do:
  194. 1. Having to manually copy modules sources every time you want to compile the
  195. engine with or without the module, or taking additional steps needed to
  196. manually disable a module during compilation with a build option similar to
  197. ``module_summator_enabled=no``. Creating symbolic links may also be a solution,
  198. but you may additionally need to overcome OS restrictions like needing the
  199. symbolic link privilege if doing this via script.
  200. 2. Depending on whether you have to work with the engine's source code, the
  201. module files added directly to ``modules/`` changes the working tree to the
  202. point where using a VCS (like ``git``) proves to be cumbersome as you need to
  203. make sure that only the engine-related code is committed by filtering
  204. changes.
  205. So if you feel like the independent structure of custom modules is needed, lets
  206. take our "summator" module and move it to the engine's parent directory:
  207. .. code-block:: shell
  208. mkdir ../modules
  209. mv modules/summator ../modules
  210. Compile the engine with our module by providing ``custom_modules`` build option
  211. which accepts a comma-separated list of directory paths containing custom C++
  212. modules, similar to the following:
  213. .. code-block:: shell
  214. scons custom_modules=../modules
  215. The build system shall detect all modules under the ``../modules`` directory
  216. and compile them accordingly, including our "summator" module.
  217. .. warning::
  218. Any path passed to ``custom_modules`` will be converted to an absolute path
  219. internally as a way to distinguish between custom and built-in modules. It
  220. means that things like generating module documentation may rely on a
  221. specific path structure on your machine.
  222. .. seealso::
  223. :ref:`Introduction to the buildsystem - Custom modules build option <doc_buildsystem_custom_modules>`.
  224. Customizing module types initialization
  225. ---------------------------------------
  226. Modules can interact with other built-in engine classes during runtime and even
  227. affect the way core types are initialized. So far, we've been using
  228. ``register_summator_types`` as a way to bring in module classes to be available
  229. within the engine.
  230. A crude order of the engine setup can be summarized as a list of the following
  231. type registration methods:
  232. .. code-block:: cpp
  233. preregister_module_types();
  234. preregister_server_types();
  235. register_core_singletons();
  236. register_server_types();
  237. register_scene_types();
  238. EditorNode::register_editor_types();
  239. register_platform_apis();
  240. register_module_types();
  241. initialize_physics();
  242. initialize_navigation_server();
  243. register_server_singletons();
  244. register_driver_types();
  245. ScriptServer::init_languages();
  246. Our ``Summator`` class is initialized during the ``register_module_types()``
  247. call. Imagine that we need to satisfy some common module runtime dependency
  248. (like singletons), or allow us to override existing engine method callbacks
  249. before they can be assigned by the engine itself. In that case, we want to
  250. ensure that our module classes are registered *before* any other built-in type.
  251. This is where we can define an optional ``preregister_summator_types()``
  252. method which will be called before anything else during the
  253. ``preregister_module_types()`` engine setup stage.
  254. We now need to add this method to ``register_types`` header and source files:
  255. .. code-block:: cpp
  256. :caption: godot/modules/summator/register_types.h
  257. #define MODULE_SUMMATOR_HAS_PREREGISTER
  258. void preregister_summator_types();
  259. void register_summator_types();
  260. void unregister_summator_types();
  261. .. note:: Unlike other register methods, we have to explicitly define
  262. ``MODULE_SUMMATOR_HAS_PREREGISTER`` to let the build system know what
  263. relevant method calls to include at compile time. The module's name
  264. has to be converted to uppercase as well.
  265. .. code-block:: cpp
  266. :caption: godot/modules/summator/register_types.cpp
  267. #include "register_types.h"
  268. #include "core/object/class_db.h"
  269. #include "summator.h"
  270. void preregister_summator_types() {
  271. // Called before any other core types are registered.
  272. // Nothing to do here in this example.
  273. }
  274. void register_summator_types() {
  275. ClassDB::register_class<Summator>();
  276. }
  277. void unregister_summator_types() {
  278. // Nothing to do here in this example.
  279. }
  280. Writing custom documentation
  281. ----------------------------
  282. Writing documentation may seem like a boring task, but it is highly recommended
  283. to document your newly created module to make it easier for users to benefit
  284. from it. Not to mention that the code you've written one year ago may become
  285. indistinguishable from the code that was written by someone else, so be kind to
  286. your future self!
  287. There are several steps in order to setup custom docs for the module:
  288. 1. Make a new directory in the root of the module. The directory name can be
  289. anything, but we'll be using the ``doc_classes`` name throughout this section.
  290. 2. Now, we need to edit ``config.py``, add the following snippet:
  291. .. code-block:: python
  292. def get_doc_path():
  293. return "doc_classes"
  294. def get_doc_classes():
  295. return [
  296. "Summator",
  297. ]
  298. The ``get_doc_path()`` function is used by the build system to determine
  299. the location of the docs. In this case, they will be located in the
  300. ``modules/summator/doc_classes`` directory. If you don't define this,
  301. the doc path for your module will fall back to the main ``doc/classes``
  302. directory.
  303. The ``get_doc_classes()`` method is necessary for the build system to
  304. know which registered classes belong to the module. You need to list all of your
  305. classes here. The classes that you don't list will end up in the
  306. main ``doc/classes`` directory.
  307. .. tip::
  308. You can use Git to check if you have missed some of your classes by checking the
  309. untracked files with ``git status``. For example:
  310. ::
  311. git status
  312. Example output:
  313. ::
  314. Untracked files:
  315. (use "git add <file>..." to include in what will be committed)
  316. doc/classes/MyClass2D.xml
  317. doc/classes/MyClass4D.xml
  318. doc/classes/MyClass5D.xml
  319. doc/classes/MyClass6D.xml
  320. ...
  321. 3. Now we can generate the documentation:
  322. We can do this via running Godot's doctool i.e. ``godot --doctool <path>``,
  323. which will dump the engine API reference to the given ``<path>`` in XML format.
  324. In our case we'll point it to the root of the cloned repository. You can point it
  325. to an another folder, and just copy over the files that you need.
  326. Run command:
  327. ::
  328. bin/<godot_binary> --doctool .
  329. Now if you go to the ``godot/modules/summator/doc_classes`` folder, you will see
  330. that it contains a ``Summator.xml`` file, or any other classes, that you referenced
  331. in your ``get_doc_classes`` function.
  332. Edit the file(s) following the `class reference primer <https://contributing.godotengine.org/en/latest/documentation/class_reference/class_reference_primer.html>`__ and recompile the engine.
  333. Once the compilation process is finished, the docs will become accessible within
  334. the engine's built-in documentation system.
  335. In order to keep documentation up-to-date, all you'll have to do is simply modify
  336. one of the XML files and recompile the engine from now on.
  337. If you change your module's API, you can also re-extract the docs, they will contain
  338. the things that you previously added. Of course if you point it to your godot
  339. folder, make sure you don't lose work by extracting older docs from an older engine build
  340. on top of the newer ones.
  341. Note that if you don't have write access rights to your supplied ``<path>``,
  342. you might encounter an error similar to the following:
  343. .. code-block:: console
  344. ERROR: Can't write doc file: docs/doc/classes/@GDScript.xml
  345. At: editor/doc/doc_data.cpp:956
  346. .. _doc_custom_module_unit_tests:
  347. Writing custom unit tests
  348. -------------------------
  349. It's possible to write self-contained unit tests as part of a C++ module. If you
  350. are not familiar with the unit testing process in Godot yet, please refer to
  351. :ref:`doc_unit_testing`.
  352. The procedure is the following:
  353. 1. Create a new directory named ``tests/`` under your module's root:
  354. .. code-block:: console
  355. cd modules/summator
  356. mkdir tests
  357. cd tests
  358. 2. Create a new test suite: ``test_summator.h``. The header must be prefixed
  359. with ``test_`` so that the build system can collect it and include it as part
  360. of the ``tests/test_main.cpp`` where the tests are run.
  361. 3. Write some test cases. Here's an example:
  362. .. code-block:: cpp
  363. :caption: godot/modules/summator/tests/test_summator.h
  364. #pragma once
  365. #include "tests/test_macros.h"
  366. #include "modules/summator/summator.h"
  367. namespace TestSummator {
  368. TEST_CASE("[Modules][Summator] Adding numbers") {
  369. Ref<Summator> s = memnew(Summator);
  370. CHECK(s->get_total() == 0);
  371. s->add(10);
  372. CHECK(s->get_total() == 10);
  373. s->add(20);
  374. CHECK(s->get_total() == 30);
  375. s->add(30);
  376. CHECK(s->get_total() == 60);
  377. s->reset();
  378. CHECK(s->get_total() == 0);
  379. }
  380. } // namespace TestSummator
  381. 4. Compile the engine with ``scons tests=yes``, and run the tests with the
  382. following command:
  383. .. code-block:: console
  384. ./bin/<godot_binary> --test --source-file="*test_summator*" --success
  385. You should see the passing assertions now.
  386. .. _doc_custom_module_icons:
  387. Adding custom editor icons
  388. --------------------------
  389. Similarly to how you can write self-contained documentation within a module,
  390. you can also create your own custom icons for classes to appear in the editor.
  391. For the actual process of creating editor icons to be integrated within the engine,
  392. please refer to :ref:`doc_editor_icons` first.
  393. Once you've created your icon(s), proceed with the following steps:
  394. 1. Make a new directory in the root of the module named ``icons``. This is the
  395. default path for the engine to look for module's editor icons.
  396. 2. Move your newly created ``svg`` icons (optimized or not) into that folder.
  397. 3. Recompile the engine and run the editor. Now the icon(s) will appear in
  398. editor's interface where appropriate.
  399. If you'd like to store your icons somewhere else within your module,
  400. add the following code snippet to ``config.py`` to override the default path:
  401. .. code-block:: python
  402. def get_icons_path():
  403. return "path/to/icons"
  404. Summing up
  405. ----------
  406. Remember to:
  407. - Use ``GDCLASS`` macro for inheritance, so Godot can wrap it.
  408. - Use ``_bind_methods`` to bind your functions to scripting, and to
  409. allow them to work as callbacks for signals.
  410. - **Avoid multiple inheritance for classes exposed to Godot**, as ``GDCLASS``
  411. doesn't support this. You can still use multiple inheritance in your own
  412. classes as long as they're not exposed to Godot's scripting API.
  413. But this is not all, depending what you do, you will be greeted with
  414. some (hopefully positive) surprises.
  415. - If you inherit from :ref:`class_Node` (or any derived node type, such as
  416. Sprite2D), your new class will appear in the editor, in the inheritance
  417. tree in the "Add Node" dialog.
  418. - If you inherit from :ref:`class_Resource`, it will appear in the resource
  419. list, and all the exposed properties can be serialized when
  420. saved/loaded.
  421. - By this same logic, you can extend the Editor and almost any area of
  422. the engine.