custom_modules_in_cpp.rst 20 KB

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