gdnative_cpp_example.rst 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. .. _doc_gdnative_cpp_example:
  2. GDNative C++ example
  3. ====================
  4. Introduction
  5. ------------
  6. This tutorial builds on top of the information given in the
  7. :ref:`GDNative C example <doc_gdnative_c_example>`, so we highly recommend you
  8. read that first.
  9. The C++ bindings for GDNative are built on top of the NativeScript GDNative API
  10. and provide a nicer way to "extend" nodes in Godot using C++. This is equivalent
  11. to writing scripts in GDScript, but in C++ instead.
  12. You can download the full example we'll be creating in this tutorial `on
  13. GitHub <https://github.com/BastiaanOlij/gdnative_cpp_example>`__.
  14. Setting up the project
  15. ----------------------
  16. There are a few prerequisites you'll need:
  17. - a Godot 3.x executable,
  18. - a C++ compiler,
  19. - SCons as a build tool,
  20. - a copy of the `godot-cpp
  21. repository <https://github.com/godotengine/godot-cpp>`__.
  22. See also :ref:`Compiling <toc-devel-compiling>` as the build tools are identical
  23. to the ones you need to compile Godot from source.
  24. You can download these repositories from GitHub or let Git do the work for you.
  25. Note that these repositories now have different branches for different versions
  26. of Godot. GDNative modules written for an earlier version of Godot will work in
  27. newer versions (with the exception of one breaking change in ARVR interfaces
  28. between 3.0 and 3.1) but not vice versa so make sure you download the correct
  29. branch. Also note that the version of Godot you use to generate the ``api.json``
  30. with becomes your minimum version.
  31. .. note::
  32. `GDExtension <https://godotengine.org/article/introducing-gd-extensions>`__
  33. has been merged in the ``master`` branch of godot-cpp,
  34. but it is only compatible with the upcoming Godot 4.0.
  35. Therefore, you need to use the ``3.x`` branch of godot-cpp to use GDNative
  36. and follow this example.
  37. This tutorial covers only GDNative in Godot 3.x, *not* GDExtension in Godot 4.0.
  38. If you are versioning your project using Git, it is a good idea to add them as
  39. Git submodules:
  40. .. code-block:: none
  41. mkdir gdnative_cpp_example
  42. cd gdnative_cpp_example
  43. git init
  44. git submodule add -b 3.x https://github.com/godotengine/godot-cpp
  45. cd godot-cpp
  46. git submodule update --init
  47. If you decide to just download the repositories or clone them into your project
  48. folder, make sure to keep the folder layout identical to the one described here,
  49. as much of the code we'll be showcasing here assumes the project follows this
  50. layout.
  51. Do make sure you clone recursive to pull in both repositories:
  52. .. code-block:: none
  53. mkdir gdnative_cpp_example
  54. cd gdnative_cpp_example
  55. git clone --recursive -b 3.x https://github.com/godotengine/godot-cpp
  56. .. note::
  57. ``godot-cpp`` now includes ``godot-headers`` as a nested submodule, if you've
  58. manually downloaded them please make sure to place ``godot-headers`` inside
  59. of the ``godot-cpp`` folder.
  60. You don't have to do it this way, but we've found it easiest to manage. If you
  61. decide to download the repositories or clone them into your folder,
  62. make sure to keep the folder layout the same as we've setup here. Much of
  63. the code we'll be showcasing here assumes the project has this layout.
  64. If you cloned the example from the link specified in the introduction, the
  65. submodules are not automatically initialized. You will need to execute the
  66. following commands:
  67. .. code-block:: none
  68. cd gdnative_cpp_example
  69. git submodule update --init --recursive
  70. This will clone these two repositories into your project folder.
  71. Building the C++ bindings
  72. -------------------------
  73. Now that we've downloaded our prerequisites, it is time to build the C++
  74. bindings.
  75. The repository contains a copy of the metadata for the current Godot release,
  76. but if you need to build these bindings for a newer version of Godot, simply
  77. call the Godot executable:
  78. .. code-block:: none
  79. godot --gdnative-generate-json-api api.json
  80. Place the resulting ``api.json`` file in the project folder and add
  81. ``use_custom_api_file=yes custom_api_file=../api.json`` to the scons command
  82. below.
  83. To generate and compile the bindings, use this command (replacing ``<platform>``
  84. with ``windows``, ``linux`` or ``osx`` depending on your OS):
  85. To speed up compilation, add `-jN` at the end of the SCons command line where `N`
  86. is the number of CPU threads you have on your system. The example below uses 4 threads.
  87. .. code-block:: none
  88. cd godot-cpp
  89. scons platform=<platform> generate_bindings=yes -j4
  90. cd ..
  91. This step will take a while. When it is completed, you should have static
  92. libraries that can be compiled into your project stored in ``godot-cpp/bin/``.
  93. .. note::
  94. You may need to add ``bits=64`` to the command on Windows or Linux.
  95. Creating a simple plugin
  96. ------------------------
  97. Now it's time to build an actual plugin. We'll start by creating an empty Godot
  98. project in which we'll place a few files.
  99. Open Godot and create a new project. For this example, we will place it in a
  100. folder called ``demo`` inside our GDNative module's folder structure.
  101. In our demo project, we'll create a scene containing a Node called "Main" and
  102. we'll save it as ``main.tscn``. We'll come back to that later.
  103. Back in the top-level GDNative module folder, we're also going to create a
  104. subfolder called ``src`` in which we'll place our source files.
  105. You should now have ``demo``, ``godot-cpp``, ``godot-headers``, and ``src``
  106. directories in your GDNative module.
  107. In the ``src`` folder, we'll start with creating our header file for the
  108. GDNative node we'll be creating. We will name it ``gdexample.h``:
  109. .. code-block:: C++
  110. #ifndef GDEXAMPLE_H
  111. #define GDEXAMPLE_H
  112. #include <Godot.hpp>
  113. #include <Sprite.hpp>
  114. namespace godot {
  115. class GDExample : public Sprite {
  116. GODOT_CLASS(GDExample, Sprite)
  117. private:
  118. float time_passed;
  119. public:
  120. static void _register_methods();
  121. GDExample();
  122. ~GDExample();
  123. void _init(); // our initializer called by Godot
  124. void _process(float delta);
  125. };
  126. }
  127. #endif
  128. There are a few things of note to the above. We're including ``Godot.hpp`` which
  129. contains all our basic definitions. After that, we include ``Sprite.hpp`` which
  130. contains bindings to the Sprite class. We'll be extending this class in our
  131. module.
  132. We're using the namespace ``godot``, since everything in GDNative is defined
  133. within this namespace.
  134. Then we have our class definition, which inherits from our Sprite through a
  135. container class. We'll see a few side effects of this later on. The
  136. ``GODOT_CLASS`` macro sets up a few internal things for us.
  137. After that, we declare a single member variable called ``time_passed``.
  138. In the next block we're defining our methods, we obviously have our constructor
  139. and destructor defined, but there are two other functions that will likely look
  140. familiar to some, and one new method.
  141. The first is ``_register_methods``, which is a static function that Godot will
  142. call to find out which methods can be called on our NativeScript and which
  143. properties it exposes. The second is our ``_process`` function, which will work
  144. exactly the same as the ``_process`` function you're used to in GDScript. The
  145. third is our ``_init`` function which is called after Godot has properly set up
  146. our object. It has to exist even if you don't place any code in it.
  147. Let's implement our functions by creating our ``gdexample.cpp`` file:
  148. .. code-block:: C++
  149. #include "gdexample.h"
  150. using namespace godot;
  151. void GDExample::_register_methods() {
  152. register_method("_process", &GDExample::_process);
  153. }
  154. GDExample::GDExample() {
  155. }
  156. GDExample::~GDExample() {
  157. // add your cleanup here
  158. }
  159. void GDExample::_init() {
  160. // initialize any variables here
  161. time_passed = 0.0;
  162. }
  163. void GDExample::_process(float delta) {
  164. time_passed += delta;
  165. Vector2 new_position = Vector2(10.0 + (10.0 * sin(time_passed * 2.0)), 10.0 + (10.0 * cos(time_passed * 1.5)));
  166. set_position(new_position);
  167. }
  168. This one should be straightforward. We're implementing each method of our class
  169. that we defined in our header file. Note that the ``register_method`` call
  170. **must** expose the ``_process`` method, otherwise Godot will not be able to use
  171. it. However, we do not have to tell Godot about our constructor, destructor and
  172. ``_init`` functions.
  173. The other method of note is our ``_process`` function, which simply keeps track
  174. of how much time has passed and calculates a new position for our sprite using a
  175. sine and cosine function. What stands out is calling
  176. ``owner->set_position`` to call one of the built-in methods of our Sprite. This
  177. is because our class is a container class; ``owner`` points to the actual Sprite
  178. node our script relates to.
  179. There is one more C++ file we need; we'll name it ``gdlibrary.cpp``. Our
  180. GDNative plugin can contain multiple NativeScripts, each with their own header
  181. and source file like we've implemented ``GDExample`` up above. What we need now
  182. is a small bit of code that tells Godot about all the NativeScripts in our
  183. GDNative plugin.
  184. .. code-block:: C++
  185. #include "gdexample.h"
  186. extern "C" void GDN_EXPORT godot_gdnative_init(godot_gdnative_init_options *o) {
  187. godot::Godot::gdnative_init(o);
  188. }
  189. extern "C" void GDN_EXPORT godot_gdnative_terminate(godot_gdnative_terminate_options *o) {
  190. godot::Godot::gdnative_terminate(o);
  191. }
  192. extern "C" void GDN_EXPORT godot_nativescript_init(void *handle) {
  193. godot::Godot::nativescript_init(handle);
  194. godot::register_class<godot::GDExample>();
  195. }
  196. Note that we are not using the ``godot`` namespace here, since the three
  197. functions implemented here need to be defined without a namespace.
  198. The ``godot_gdnative_init`` and ``godot_gdnative_terminate`` functions get
  199. called respectively when Godot loads our plugin and when it unloads it. All
  200. we're doing here is parse through the functions in our bindings module to
  201. initialize them, but you might have to set up more things depending on your
  202. needs.
  203. The important function is the third function called ``godot_nativescript_init``.
  204. We first call a function in our bindings library that does its usual stuff.
  205. After that, we call the function ``register_class`` for each of our classes in
  206. our library.
  207. Compiling the plugin
  208. --------------------
  209. We cannot easily write by hand a ``SConstruct`` file that SCons would use for
  210. building. For the purpose of this example, just use
  211. :download:`this hardcoded SConstruct file <files/cpp_example/SConstruct>` we've
  212. prepared. We'll cover a more customizable, detailed example on how to use these
  213. build files in a subsequent tutorial.
  214. .. note::
  215. This ``SConstruct`` file was written to be used with the latest ``godot-cpp``
  216. master, you may need to make small changes using it with older versions or
  217. refer to the ``SConstruct`` file in the Godot 3.0 documentation.
  218. Once you've downloaded the ``SConstruct`` file, place it in your GDNative module
  219. folder besides ``godot-cpp``, ``godot-headers`` and ``demo``, then run:
  220. .. code-block:: none
  221. scons platform=<platform>
  222. You should now be able to find the module in ``demo/bin/<platform>``.
  223. .. note::
  224. Here, we've compiled both godot-cpp and our gdexample library as debug
  225. builds. For optimized builds, you should compile them using the
  226. ``target=release`` switch.
  227. Using the GDNative module
  228. -------------------------
  229. Before we jump back into Godot, we need to create two more files in
  230. ``demo/bin/``. Both can be created using the Godot editor, but it may be faster
  231. to create them directly.
  232. The first one is a file that lets Godot know what dynamic libraries should be
  233. loaded for each platform and is called ``gdexample.gdnlib``.
  234. .. code-block:: none
  235. [general]
  236. singleton=false
  237. load_once=true
  238. symbol_prefix="godot_"
  239. reloadable=false
  240. [entry]
  241. X11.64="res://bin/x11/libgdexample.so"
  242. Windows.64="res://bin/win64/libgdexample.dll"
  243. OSX.64="res://bin/osx/libgdexample.dylib"
  244. [dependencies]
  245. X11.64=[]
  246. Windows.64=[]
  247. OSX.64=[]
  248. This file contains a ``general`` section that controls how the module is loaded.
  249. It also contains a prefix section which should be left on ``godot_`` for now. If
  250. you change this, you'll need to rename various functions that are used as entry
  251. points. This was added for the iPhone platform because it doesn't allow dynamic
  252. libraries to be deployed, yet GDNative modules are linked statically.
  253. The ``entry`` section is the important bit: it tells Godot the location of the
  254. dynamic library in the project's filesystem for each supported platform. It will
  255. also result in *just* that file being exported when you export the project,
  256. which means the data pack won't contain libraries that are incompatible with the
  257. target platform.
  258. Finally, the ``dependencies`` section allows you to name additional dynamic
  259. libraries that should be included as well. This is important when your GDNative
  260. plugin implements someone else's library and requires you to supply a
  261. third-party dynamic library with your project.
  262. If you double click on the ``gdexample.gdnlib`` file within Godot, you'll see
  263. there are far more options to set:
  264. .. image:: img/gdnative_library.png
  265. The second file we need to create is a file used by each NativeScript we've
  266. added to our plugin. We'll name it ``gdexample.gdns`` for our gdexample
  267. NativeScript.
  268. .. code-block:: none
  269. [gd_resource type="NativeScript" load_steps=2 format=2]
  270. [ext_resource path="res://bin/gdexample.gdnlib" type="GDNativeLibrary" id=1]
  271. [resource]
  272. resource_name = "gdexample"
  273. class_name = "GDExample"
  274. library = ExtResource( 1 )
  275. This is a standard Godot resource; you could just create it directly in your
  276. scene, but saving it to a file makes it much easier to reuse it in other places.
  277. This resource points to our gdnlib file, so that Godot can know which dynamic
  278. library contains our NativeScript. It also defines the ``class_name`` which
  279. identifies the NativeScript in our plugin we want to use.
  280. Time to jump back into Godot. We load up the main scene we created way back in
  281. the beginning and now add a Sprite to our scene:
  282. .. image:: img/gdnative_cpp_nodes.png
  283. We're going to assign the Godot logo to this sprite as our texture, disable the
  284. ``centered`` property and drag our ``gdexample.gdns`` file onto the ``script``
  285. property of the sprite:
  286. .. image:: img/gdnative_cpp_sprite.png
  287. We're finally ready to run the project:
  288. .. image:: img/gdnative_cpp_animated.gif
  289. Adding properties
  290. -----------------
  291. GDScript allows you to add properties to your script using the ``export``
  292. keyword. In GDNative you have to register the properties and there are two ways
  293. of doing this. You can either bind directly to a member or use a setter and
  294. getter function.
  295. .. note::
  296. There is a third option, just like in GDScript you can directly implement the
  297. ``_get_property_list``, ``_get`` and ``_set`` methods of an object but that
  298. goes far beyond the scope of this tutorial.
  299. We'll examine both starting with the direct bind. Lets add a property that
  300. allows us to control the amplitude of our wave.
  301. In our ``gdexample.h`` file we simply need to add a member variable like so:
  302. .. code-block:: C++
  303. ...
  304. private:
  305. float time_passed;
  306. float amplitude;
  307. ...
  308. In our ``gdexample.cpp`` file we need to make a number of changes, we will only
  309. show the methods we end up changing, don't remove the lines we're omitting:
  310. .. code-block:: C++
  311. void GDExample::_register_methods() {
  312. register_method("_process", &GDExample::_process);
  313. register_property<GDExample, float>("amplitude", &GDExample::amplitude, 10.0);
  314. }
  315. void GDExample::_init() {
  316. // initialize any variables here
  317. time_passed = 0.0;
  318. amplitude = 10.0;
  319. }
  320. void GDExample::_process(float delta) {
  321. time_passed += delta;
  322. Vector2 new_position = Vector2(
  323. amplitude + (amplitude * sin(time_passed * 2.0)),
  324. amplitude + (amplitude * cos(time_passed * 1.5))
  325. );
  326. set_position(new_position);
  327. }
  328. Once you compile the module with these changes in place, you will see that a
  329. property has been added to our interface. You can now change this property and
  330. when you run your project, you will see that our Godot icon travels along a
  331. larger figure.
  332. .. note::
  333. The ``reloadable`` property in the ``gdexample.gdnlib`` file must be set to
  334. ``true`` for the Godot editor to automatically pick up the newly added
  335. property.
  336. However, this setting should be used with care, especially when tool classes
  337. are used, as the editor might hold objects then that have script instances
  338. attached to them that are managed by a GDNative library.
  339. Let's do the same but for the speed of our animation and use a setter and getter
  340. function. Our ``gdexample.h`` header file again only needs a few more lines of
  341. code:
  342. .. code-block:: C++
  343. ...
  344. float amplitude;
  345. float speed;
  346. ...
  347. void _process(float delta);
  348. void set_speed(float p_speed);
  349. float get_speed();
  350. ...
  351. This requires a few more changes to our ``gdexample.cpp`` file, again we're only
  352. showing the methods that have changed so don't remove anything we're omitting:
  353. .. code-block:: C++
  354. void GDExample::_register_methods() {
  355. register_method("_process", &GDExample::_process);
  356. register_property<GDExample, float>("amplitude", &GDExample::amplitude, 10.0);
  357. register_property<GDExample, float>("speed", &GDExample::set_speed, &GDExample::get_speed, 1.0);
  358. }
  359. void GDExample::_init() {
  360. // initialize any variables here
  361. time_passed = 0.0;
  362. amplitude = 10.0;
  363. speed = 1.0;
  364. }
  365. void GDExample::_process(float delta) {
  366. time_passed += speed * delta;
  367. Vector2 new_position = Vector2(
  368. amplitude + (amplitude * sin(time_passed * 2.0)),
  369. amplitude + (amplitude * cos(time_passed * 1.5))
  370. );
  371. set_position(new_position);
  372. }
  373. void GDExample::set_speed(float p_speed) {
  374. speed = p_speed;
  375. }
  376. float GDExample::get_speed() {
  377. return speed;
  378. }
  379. Now when the project is compiled, we'll see another property called speed.
  380. Changing its value will make the animation go faster or slower.
  381. For this example, there is no obvious advantage of using a setter and getter.
  382. A good reason for a setter would be if you wanted to react on the variable being changed.
  383. If you don't need to do something like that, binding the variable is enough.
  384. Getters and setters become far more useful in more complex scenarios where you
  385. need to make additional choices based on the state of your object.
  386. .. note::
  387. For simplicity, we've left out the optional parameters in the
  388. register_property<class, type> method call. These parameters are
  389. ``rpc_mode``, ``usage``, ``hint`` and ``hint_string``. These can be used to
  390. further configure how properties are displayed and set on the Godot side.
  391. Modern C++ compilers are able to infer the class and variable type and allow
  392. you to omit the ``<GDExample, float>`` part of our ``register_property``
  393. method. We've had mixed experiences with this however.
  394. Signals
  395. -------
  396. Last but not least, signals fully work in GDNative as well. Having your module
  397. react to a signal given out by another object requires you to call ``connect``
  398. on that object. We can't think of a good example for our wobbling Godot icon, we
  399. would need to showcase a far more complete example.
  400. This is the required syntax:
  401. .. code-block:: C++
  402. some_other_node->connect("the_signal", this, "my_method");
  403. Note that you can only call ``my_method`` if you've previously registered it in
  404. your ``_register_methods`` method.
  405. Having your object sending out signals is more common. For our wobbling
  406. Godot icon, we'll do something silly just to show how it works. We're going to
  407. emit a signal every time a second has passed and pass the new location along.
  408. In our ``gdexample.h`` header file, we need to define a new member ``time_emit``:
  409. .. code-block:: C++
  410. ...
  411. float time_passed;
  412. float time_emit;
  413. float amplitude;
  414. ...
  415. This time, the changes in ``gdexample.cpp`` are more elaborate. First,
  416. you'll need to set ``time_emit = 0.0;`` in either our ``_init`` method or in our
  417. constructor. We'll look at the other 2 needed changes one by one.
  418. In our ``_register_methods`` method, we need to declare our signal. This is done
  419. as follows:
  420. .. code-block:: C++
  421. void GDExample::_register_methods() {
  422. register_method("_process", &GDExample::_process);
  423. register_property<GDExample, float>("amplitude", &GDExample::amplitude, 10.0);
  424. register_property<GDExample, float>("speed", &GDExample::set_speed, &GDExample::get_speed, 1.0);
  425. register_signal<GDExample>((char *)"position_changed", "node", GODOT_VARIANT_TYPE_OBJECT, "new_pos", GODOT_VARIANT_TYPE_VECTOR2);
  426. }
  427. Here, our ``register_signal`` method can be a single call first taking the
  428. signals name, then having pairs of values specifying the parameter name and
  429. type of each parameter we'll send along with this signal.
  430. Next, we'll need to change our ``_process`` method:
  431. .. code-block:: C++
  432. void GDExample::_process(float delta) {
  433. time_passed += speed * delta;
  434. Vector2 new_position = Vector2(
  435. amplitude + (amplitude * sin(time_passed * 2.0)),
  436. amplitude + (amplitude * cos(time_passed * 1.5))
  437. );
  438. set_position(new_position);
  439. time_emit += delta;
  440. if (time_emit > 1.0) {
  441. emit_signal("position_changed", this, new_position);
  442. time_emit = 0.0;
  443. }
  444. }
  445. After a second has passed, we emit our signal and reset our counter. We can add
  446. our parameter values directly to ``emit_signal``.
  447. Once the GDNative library is compiled, we can go into Godot and select our sprite
  448. node. In the **Node** dock, we can find our new signal and link it up by pressing
  449. the **Connect** button or double-clicking the signal. We've added a script on
  450. our main node and implemented our signal like this:
  451. .. code-block:: GDScript
  452. extends Node
  453. func _on_Sprite_position_changed(node, new_pos):
  454. print("The position of " + node.name + " is now " + str(new_pos))
  455. Every second, we output our position to the console.
  456. Next steps
  457. ----------
  458. The above is only a simple example, but we hope it shows you the basics. You can
  459. build upon this example to create full-fledged scripts to control nodes in Godot
  460. using C++.
  461. To edit and recompile the plugin while the Godot editor
  462. remains open, re-run the project after the library has finished building.