Technology
Godot has actually turned into one of the most popular video game engines of the last couple of years. It is complimentary, open source under the MIT license, and little sufficient to download and begin utilizing in minutes. Many Godot video games are composed in GDScript, the engine’s own scripting language.
Eventually, however, lots of tasks require something that currently exists as a C or C++ library: a simulation library, a database, a networking procedure, a maker finding out runtime. GDScript can not call native code, however Godot can fill it through GDExtensionand godot-cppthe main C++ bindings, lets you expose that code as routine engine classes. Composing the C++ code is the simple part. The difficult part is the develop: godot-cpp needs to match your Godot variation, and every library you include needs to be put together for each platform you deliver to.
In this post we provide a brief trip of Godot, discuss how C++ extensions work, and demonstrate how to bring C++ libraries into a Godot video game with Conan and godot-cpp 10, now offered in ConanCenter. As an example we will utilize flecsan Entity Component System library, to mimic 100,000 particles inside a Godot scene.
100,000 particles simulated with flecs inside a Godot scene, getting away from the mouse cursor
A Quick Introduction to Godot
Godot is a basic function engine for 2D and 3D video games. Whatever in a Godot job is constructed from 2 principles:
- Nodes are the fundamental foundation. Each node has a type(
Sprite2D
Camera3DAudioStreamPlayerTimer… ), a set of homes you can modify in the Inspector, and callbacks such as_ready()or_process()that the engine calls throughout the video game loop. - Scenes are trees of nodes conserved to disk as
.tscnfiles. A scene can be a character, a menu or an entire level, and scenes can be instanced inside other scenes.
Habits is generally included by connecting a script to a node. GDScript is a Python-like language created for the engine, and it is excellent for gameplay reasoning due to the fact that modifications appear right away without an assemble action.
What makes Godot fascinating for C++ designers is that the engine itself is composed in C++, and it can pack extensions composed in C++ without being recompiled. A class that originates from among these extensions ends up being a routine engine class: it appears in the editor beside the integrated nodes, with its homes in the Inspector, and GDScript can utilize it like any other node. The next area discusses how these extensions work.
Extending Godot with C++
There are 2 methods to include C++ code to Godot:
- Engine modules
are put together into the engine itself. They have complete access to the internals, however you require to develop and deliver your own copy of Godot, consisting of the editor and export design templates for each platform.
- GDExtension
loads a shared library (
.dll.so.dylibor.wasmon the internet) into an authorities, unmodified Godot develop at runtime. The engine speak with the library through a steady C user interface.
GDExtension is the suggested method for the majority of tasks, and it is the number of popular plugins are dispersed today. Since the C user interface is verbose to utilize straight, the Godot group keeps godot-cppa C++ library that covers it with an API extremely near the one utilized inside the engine. It offers a C++ class for each engine class, such as Node2D Sprite2D or Input
Your own classes are routine C++ code that originates from those classes. A node composed with godot-cpp appears like this:
#include
namespace godot {
class MyNode : public Node2D {
GDCLASS(MyNode, Node2D)
protected:
static void _bind_methods() {}
public:
void _process(double p_delta) override {
// runs every frame
}
};
} // namespace godot
Because variation 10.0, a single godot-cpp release deals with any Godot variation from 4.3 onwards. You choose one with the api_version develop choice, and godot-cpp creates its C++ classes from the API of that variation. An extension constructed for Godot 4.3 likewise operates in more recent variations, however not in older ones, so you normally choose the earliest Godot variation you wish to support.
Construct targets and function tags
There is another principle you require to understand before constructing anything. godot-cpp is put together for among 3 targetscalled after the Godot constructs that load the library:
template_debug: the default. Makes it possible for debug checks through the
DEBUG_ENABLEDmeaning. This library is packed by the editor and by debug exports.template_release: for release exports, with the debug checks eliminated.editor: for libraries that are just filled by the editor.
Which library Godot loads is chosen at runtime by a little .gdextension
file. It maps function tags to library courses. The debug tag matches the editor and debug exports, and the release tag matches release exports:
[configuration]
entry_symbol = "gdexample_library_init"
compatibility_minimum = "4.7"
[libraries]
macos.debug = "res://bin/libgdexample.template_debug.dylib"
macos.release = "res://bin/libgdexample.template_release.dylib"
linux.debug = "res://bin/libgdexample.template_debug.so"
linux.release = "res://bin/libgdexample.template_release.so"
windows.debug = "res://bin/libgdexample.template_debug.dll"
windows.release = "res://bin/libgdexample.template_release.dll"
The normal workflow
The Godot paperwork
advises including godot-cpp to your repository as a git submodule and structure it together with your library utilizing SCons. That works well for a very first extension, however every job winds up assembling its own godot-cpp for each target, platform and architecture, and any 3rd party library you cover, such as a physics engine or a device finding out runtime, needs to be vendored and constructed with matching flags for each platform Godot exports to.
Both are precisely the sort of issue Conan was developed to fix.
Handling the Dependencies with Conan
With the godot-cpp dish in ConanCenter, godot-cpp ends up being a routine bundle. The 2 specifications talked about above are Conan choices:
api_version: the Godot API variation the bindings target, from4.3to
4.7(the default).target:template_debug(the default),template_releaseoreditor
Each mix is constructed when and after that recycled by every job that requires it, rather of being assembled inside each extension.
Your GDExtension ends up being simply another C++ task with dependences. Any of the more than 1,900 libraries in ConanCenteror one you package yourself with a Conan dishcan be included beside godot-cpp, and Conan constructs all of them regularly for each platform you target.
A Practical Example: A Swarm of 100,000 Particles
To demonstrate how this operates in practice, we will compose a GDExtension that signs up a brand-new Swarm node. It replicates 100,000 particles that leave from the mouse cursor and bounce off the window edges, and draws all of them in a Godot scene.
The simulation works on flecsan
Entity Component System (ECS) library for C and C++. In an ECS, entities appear ids, elements appear information structs connected to them, and systems are functions that run over every entity that has actually a provided set of parts. Parts of the very same type are saved together in memory, that makes repeating over great deals of entities really quickly. That is why ECS is a popular option for simulations, crowds or bullet hell video games. It is likewise the type of work where native code settles, considering that upgrading this numerous entities every frame is much quicker in C++ than in GDScript.
You can discover the total example in the Conan examples2 repository:
$ git clone https://github.com/conan-io/examples2.git
$ cd examples2/examples/libraries/godot-cpp/gdextension
The src folder includes the extension code, and demo is a routine Godot job that loads it.
Stating the reliances
The conanfile.py needs godot-cpp and flecs from ConanCenter:
from conan import ConanFile
from conan.tools.cmake import CMake CMakeToolchain cmake_layout
class GDExtensionExample(ConanFile:
package_type = "shared-library"
settings = "os" "compiler" "build_type" "arch"
generators = "CMakeDeps"
def requirements(self:
selfneeds("godot-cpp/10.0.0"
selfneeds("flecs/4.1.6"
def design(self:
cmake_layout(self
def create(self:
tc = CMakeToolchain(self
# Godot chooses the library to load by its construct "target"so we call
# the output after the target godot-cpp was developed with
tccache_variables["GODOTCPP_TARGET"] = str(selfdependences["godot-cpp"]choicestarget
tccreate()
def develop(self:
cmake = CMake(self
cmakeset up()
cmakedevelop()
The only Godot particular information remains in generate()We checked out the target
alternative of the godot-cpp dependence and pass it to CMake, so the name of the library constantly matches the godot-cpp binary it was connected versus.
The CMakeLists.txt
cmake_minimum_required(VARIATION 3.15
job(gdexample LANGUAGES CXX
find_package(godot-cpp REQUIRED CONFIG
find_package(flecs REQUIRED CONFIG
add_library(gdexample SHARED src/register _ types.cpp src/swarm. cpp
target_link_libraries(gdexample PRIVATE godot-cpp flecs:: flecs_static
# Output as demo/bin/libgdexample.<.<, the course the
# demo/bin/gdexample. gdextension file points Godot to. The generator
# expression avoids multi-config generators from including a Release/ subfolder
set_target_properties(gdexample PROPERTIES OUTPUT_NAME "gdexample.${GODOTCPP_TARGET}"
PREFIX "lib"
LIBRARY_OUTPUT_DIRECTORY "$<1:${CMAKE_SOURCE_DIR}/demo/bin>"
RUNTIME_OUTPUT_DIRECTORY "$<1:${CMAKE_SOURCE_DIR}/demo/bin>"
This is a totally basic CMake job. The extension is a shared library that connects godot-cpp and flecs statically, so there is a single library file to ship. We compose it directly into demo/bin Godot discovers it without an additional copy action.
Composing the node
The Swarm class originates from Node2D and owns the flecs world. The parts of each particle appear structs. The GDCLASS macro includes the boilerplate that Godot’s class system requires, and _bind_methods() states what Godot can see, in this case the count and flee_radius residential or commercial properties. When the class is signed up, they appear in the Inspector and can be utilized from GDScript. This is a streamlined view of the class:
struct Position ;
struct Speed ;
class Swarm : public Node2D ;
The remainder of the node links both worlds. _ready() produces one flecs entity per particle and a flecs system that updates them. It likewise establishes a MultiMeshwhich draws numerous circumstances of the very same mesh in a single draw call, since one Godot node per particle would be far too heavy for 100,000 of them.
Every frame, _process() hands the mouse position to flecs, runs the systems with world.progress()and copies the resulting positions back into the MultiMesh. Once again, this is a streamlined view, and the complete code remains in the repository:
void Swarm::_ prepared() One entity per particle, with a Position and a Velocity part
for (int i = 0; i set_buffer(buffer;
Signing up the extension
register_types.cpp signs up the class when Godot loads the library:
void initialize_gdexample_module(ModuleInitializationLevel p_level) {
if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) {
return;
}
GDREGISTER_RUNTIME_CLASS(Swarm);
}
We sign up Swarm with GDREGISTER_RUNTIME_CLASSBy default, the code of a GDExtension class likewise runs inside the editor, so _ready() and
_process() would begin the simulation while you are modifying the scene. A
runtime class is just a placeholder in the editor: you can include it to a scene and set its residential or commercial properties, however its code just runs when the video game is running.
The exact same file specifies gdexample_library_init()the entry point called in the .gdextension file. It is a couple of lines of boilerplate that look the exact same in every extension.
Structure and running
With whatever in location, developing the extension is a single command:
$ conan build . --build=missing
...
[100%] Linking CXX shared library .../demo/bin/libgdexample.template_debug.dylib
[100%] Built target gdexample
Conan fixes godot-cpp and flecs, downloads precompiled binaries from ConanCenter when they exist for your setup, constructs the rest from source, produces the CMake combination and lastly constructs the extension.
Keep in mind: godot-cpp needs C++ 17. If your default profile utilizes an older requirement, which holds true for MSVC, include
-s compiler.cppstd=17to the command.
Now begin Godot 4.7, click “Import” in the Project Manager, and choose
demo/project.godotWhen the job opens, Godot checks out
bin/gdexample.gdextensionloads the library, and Swarm appears like any integrated node. You can discover it in the “Create New Node” dialog, under Node2D:
The primary scene of the demonstration currently includes a Swarm node. Choosing it reveals count and flee_radius in the Inspector, the 2 homes we bound in _bind_methods():
Press Play to run the scene, and move the mouse over the window to press the particles around. Stop it, alter count or flee_radius in the Inspector, and play it once again to see how the swarm acts with more particles or a larger get away radius.
Conclusion
GDExtension and godot-cpp let you compose engine classes in C++, and Conan looks after structure godot-cpp and any other C++ library your extension requires. This is likewise a huge benefit when you disperse the extension: constructing it for each platform you deliver to just takes altering the settings of the develop.
Keep in mind for Linux: By default, the extension links
libstdc++dynamically, so the target system should offer a variation a minimum of as brand-new as the one utilized to construct it. For broad compatibility, develop the extension and its reliances versus a toolchain and system libraries suitable with the earliest circulation you mean to support. Linklibstdc++
statically and conceal its signs with a linker variation script.
Attempt the total example
and examine the godot-cpp paperwork
for more information about composing extensions. If you have any feedback or face any problems, please let us understand in the Conan GitHub repository
Pleased video game advancement!
This post was composed with AI support and examined by human beings.
Discover more from PMN S.P.O.R.T.S - A PRIME MEDIA NETWORK BRAND
Subscribe to get the latest posts sent to your email.



