C++のカスタムモジュール

モジュール

Godotでは、モジュール方式でエンジンを拡張できます。新しいモジュールを作成してから、有効/無効にすることができます。これにより、コアを変更せずにすべてのレベルで新しいエンジン機能を追加できます。コアは別のモジュールで使用および再利用するために分割できます。

Modules are located in the modules/ subdirectory of the build system. By default, dozens of modules are enabled, such as GDScript (which, yes, is not part of the base engine), the Mono runtime, a regular expressions module, and others. As many new modules as desired can be created and combined. The SCons build system will take care of it transparently.

何のために?

ゲームの大部分はスクリプトで記述することをお勧めしますが(時間を大幅に節約できるため)、代わりに完全にC++を使用することも可能です。 C++モジュールの追加は、次のシナリオで役立ちます:

  • 外部ライブラリをGodot にバインドする(PhysX、FMODなど)。

  • ゲームの重要な部分を最適化します。

  • エンジンまたはエディタに新しい機能を追加します。

  • 既存のゲームを移植します。

  • C++なしでは生きていけないので、C++で新しいゲームを書きます。

新しいモジュールの作成

Before creating a module, make sure to download the source code of Godot and compile it.

新しいモジュールを作成するには、最初のステップは modules/ 内にディレクトリを作成することです。モジュールを個別に保守する場合は、別のVCSをモジュールにチェックアウトして使用できます。

The example module will be called "summator" (godot/modules/summator). Inside we will create a simple summator class:

/* summator.h */

#ifndef SUMMATOR_H
#define SUMMATOR_H

#include "core/reference.h"

class Summator : public Reference {
    GDCLASS(Summator, Reference);

    int count;

protected:
    static void _bind_methods();

public:
    void add(int p_value);
    void reset();
    int get_total() const;

    Summator();
};

#endif // SUMMATOR_H

それからcppファイル。

/* summator.cpp */

#include "summator.h"

void Summator::add(int p_value) {
    count += p_value;
}

void Summator::reset() {
    count = 0;
}

int Summator::get_total() const {
    return count;
}

void Summator::_bind_methods() {
    ClassDB::bind_method(D_METHOD("add", "value"), &Summator::add);
    ClassDB::bind_method(D_METHOD("reset"), &Summator::reset);
    ClassDB::bind_method(D_METHOD("get_total"), &Summator::get_total);
}

Summator::Summator() {
    count = 0;
}

次に、新しいクラスを何らかの方法で登録する必要があるので、さらに2つのファイルを作成する必要があります:

register_types.h
register_types.cpp

重要

These files must be in the top-level folder of your module (next to your SCsub and config.py files) for the module to be registered properly.

These files should contain the following:

/* register_types.h */

void register_summator_types();
void unregister_summator_types();
/* yes, the word in the middle must be the same as the module folder name */
/* register_types.cpp */

#include "register_types.h"

#include "core/class_db.h"
#include "summator.h"

void register_summator_types() {
    ClassDB::register_class<Summator>();
}

void unregister_summator_types() {
   // Nothing to do here in this example.
}

次に、ビルドシステムがこのモジュールをコンパイルできるように SCsub ファイルを作成する必要があります:

# SCsub

Import('env')

env.add_source_files(env.modules_sources, "*.cpp") # Add all cpp files to the build

複数のソースを使用して、各ファイルをPython文字列リストに個別に追加することもできます:

src_list = ["summator.cpp", "other.cpp", "etc.cpp"]
env.add_source_files(env.modules_sources, src_list)

This allows for powerful possibilities using Python to construct the file list using loops and logic statements. Look at some modules that ship with Godot by default for examples.

コンパイラが見るインクルードディレクトリを追加するには、環境のパスに追加します:

env.Append(CPPPATH=["mylib/include"]) # this is a relative path
env.Append(CPPPATH=["#myotherlib/include"]) # this is an 'absolute' path

If you want to add custom compiler flags when building your module, you need to clone env first, so it won't add those flags to whole Godot build (which can cause errors). Example SCsub with custom flags:

# SCsub

Import('env')

module_env = env.Clone()
module_env.add_source_files(env.modules_sources, "*.cpp")
# Append CCFLAGS flags for both C and C++ code.
module_env.Append(CCFLAGS=['-O2'])
# If you need to, you can:
# - Append CFLAGS for C code only.
# - Append CXXFLAGS for C++ code only.

最後に、モジュールの構成ファイルは、 config.py という名前を付けなければならない単純なPythonスクリプトです:

# config.py

def can_build(env, platform):
    return True

def configure(env):
    pass

モジュールは、特定のプラットフォーム用にビルドしてもよいかどうかを尋ねられます(この場合、True はすべてのプラットフォーム用にビルドすることを意味します)。

以上です。あまり複雑でなければいいのですが。モジュールは次のようになります:

godot/modules/summator/config.py
godot/modules/summator/summator.h
godot/modules/summator/summator.cpp
godot/modules/summator/register_types.h
godot/modules/summator/register_types.cpp
godot/modules/summator/SCsub

その後、それを圧縮し、他の人とモジュールを共有することができます。すべてのプラットフォーム (前のセクションの手順)を構築する場合は、モジュールが含まれます。

注釈

サブクラスなどのC++モジュールには、パラメーター数が5までの制限があります。これは、ヘッダーファイル core/method_bind_ext.gen.inc を含めることで13に上げることができます。

モジュールの使用

これで、任意のスクリプトから新しく作成したモジュールを使用できます:

var s = Summator.new()
s.add(10)
s.add(20)
s.add(30)
print(s.get_total())
s.reset()

出力は 60 になります。

参考

前のSummatorの例は、小さなカスタムモジュールに最適ですが、より大きな外部ライブラリを使用する場合はどうでしょうか。外部ライブラリへのバインドの詳細については、外部ライブラリへのバインド を参照してください。

警告

モジュールが(エディタからだけでなく)実行中のプロジェクトからアクセスされる場合、使用する予定のすべてのエクスポートテンプレートを再コンパイルし、各エクスポートプリセットでカスタムテンプレートへのパスを指定する必要があります。そうしないと、モジュールがエクスポートテンプレートでコンパイルされないため、プロジェクトの実行時にエラーが発生します。詳細については、Compiling ページを参照してください。

Compiling a module externally

Compiling a module involves moving the module's sources directly under the engine's modules/ directory. While this is the most straightforward way to compile a module, there are a couple of reasons as to why this might not be a practical thing to do:

  1. Having to manually copy modules sources every time you want to compile the engine with or without the module, or taking additional steps needed to manually disable a module during compilation with a build option similar to module_summator_enabled=no. Creating symbolic links may also be a solution, but you may additionally need to overcome OS restrictions like needing the symbolic link privilege if doing this via script.

  2. Depending on whether you have to work with the engine's source code, the module files added directly to modules/ changes the working tree to the point where using a VCS (like git) proves to be cumbersome as you need to make sure that only the engine-related code is committed by filtering changes.

So if you feel like the independent structure of custom modules is needed, lets take our "summator" module and move it to the engine's parent directory:

mkdir ../modules
mv modules/summator ../modules

Compile the engine with our module by providing custom_modules build option which accepts a comma-separated list of directory paths containing custom C++ modules, similar to the following:

scons custom_modules=../modules

The build system shall detect all modules under the ../modules directory and compile them accordingly, including our "summator" module.

警告

Any path passed to custom_modules will be converted to an absolute path internally as a way to distinguish between custom and built-in modules. It means that things like generating module documentation may rely on a specific path structure on your machine.

開発のためのビルドシステムの改善

警告

This shared library support is not designed to support distributing a module to other users without recompiling the engine. For that purpose, use GDNative instead.

So far, we defined a clean SCsub that allows us to add the sources of our new module as part of the Godot binary.

This static approach is fine when we want to build a release version of our game, given we want all the modules in a single binary.

However, the trade-off is that every single change requires a full recompilation of the game. Even though SCons is able to detect and recompile only the file that was changed, finding such files and eventually linking the final binary takes a long time.

このようなコストを回避するソリューションは、ゲームのバイナリを起動するときに動的に読み込まれる共有ライブラリとして独自のモジュールを構築することです。

# SCsub

Import('env')

sources = [
    "register_types.cpp",
    "summator.cpp"
]

# First, create a custom env for the shared library.
module_env = env.Clone()

# Position-independent code is required for a shared library.
module_env.Append(CCFLAGS=['-fPIC'])

# Don't inject Godot's dependencies into our shared library.
module_env['LIBS'] = []

# Define the shared library. By default, it would be built in the module's
# folder, however it's better to output it into `bin` next to the
# Godot binary.
shared_lib = module_env.SharedLibrary(target='#bin/summator', source=sources)

# Finally, notify the main build environment it now has our shared library
# as a new dependency.

# LIBPATH and LIBS need to be set on the real "env" (not the clone)
# to link the specified libraries to the Godot executable.

env.Append(LIBPATH=['#bin'])

# SCons wants the name of the library with it custom suffixes
# (e.g. ".x11.tools.64") but without the final ".so".
shared_lib_shim = shared_lib[0].name.rsplit('.', 1)[0]
env.Append(LIBS=[shared_lib_shim])

Once compiled, we should end up with a bin directory containing both the godot* binary and our libsummator*.so. However given the .so is not in a standard directory (like /usr/lib), we have to help our binary find it during runtime with the LD_LIBRARY_PATH environment variable:

export LD_LIBRARY_PATH="$PWD/bin/"
./bin/godot*

注釈

You have to export the environment variable. Otherwise, you won't be able to run your project from the editor.

On top of that, it would be nice to be able to select whether to compile our module as shared library (for development) or as a part of the Godot binary (for release). To do that we can define a custom flag to be passed to SCons using the ARGUMENT command:

# SCsub

Import('env')

sources = [
    "register_types.cpp",
    "summator.cpp"
]

module_env = env.Clone()
module_env.Append(CCFLAGS=['-O2'])

if ARGUMENTS.get('summator_shared', 'no') == 'yes':
    # Shared lib compilation
    module_env.Append(CCFLAGS=['-fPIC'])
    module_env['LIBS'] = []
    shared_lib = module_env.SharedLibrary(target='#bin/summator', source=sources)
    shared_lib_shim = shared_lib[0].name.rsplit('.', 1)[0]
    env.Append(LIBS=[shared_lib_shim])
    env.Append(LIBPATH=['#bin'])
else:
    # Static compilation
    module_env.add_source_files(env.modules_sources, sources)

現在、デフォルトで scons コマンドは、モジュールをGodotのバイナリの一部として、そして summator_shared = yes を渡すときに共有ライブラリとしてビルドします。

Finally, you can even speed up the build further by explicitly specifying your shared module as target in the SCons command:

scons summator_shared=yes platform=x11 bin/libsummator.x11.tools.64.so

カスタムドキュメントの作成

ドキュメントを書くのは退屈な作業のように思えるかもしれませんが、ユーザーが役立てやすくするために、新しく作成したモジュールを文書化することを強くお勧めします。1年前に書いたコードは、他の人が書いたコードと区別がつかないかもしれないので、将来の自分に親切にしてください!

モジュールのカスタムドキュメントをセットアップするには、いくつかの手順があります:

  1. モジュールのルートに新しいディレクトリを作成します。ディレクトリ名は何でもかまいませんが、このセクションでは doc_classes という名前を使用します。

  2. Now, we need to edit config.py, add the following snippet:

    def get_doc_path():
        return "doc_classes"
    
    def get_doc_classes():
        return [
            "Summator",
        ]
    

The get_doc_path() function is used by the build system to determine the location of the docs. In this case, they will be located in the modules/summator/doc_classes directory. If you don't define this, the doc path for your module will fall back to the main doc/classes directory.

The get_doc_classes() method is necessary for the build system to know which registered classes belong to the module. You need to list all of your classes here. The classes that you don't list will end up in the main doc/classes directory.

ちなみに

You can use Git to check if you have missed some of your classes by checking the untracked files with git status. For example:

user@host:~/godot$ git status

Example output:

Untracked files:
    (use "git add <file>..." to include in what will be committed)

    doc/classes/MyClass2D.xml
    doc/classes/MyClass4D.xml
    doc/classes/MyClass5D.xml
    doc/classes/MyClass6D.xml
    ...
  1. これで、ドキュメントを生成できます:

We can do this via running Godot's doctool i.e. godot --doctool <path>, which will dump the engine API reference to the given <path> in XML format.

In our case we'll point it to the root of the cloned repository. You can point it to an another folder, and just copy over the files that you need.

コマンドの実行:

user@host:~/godot/bin$ ./bin/<godot_binary> --doctool .

Now if you go to the godot/modules/summator/doc_classes folder, you will see that it contains a Summator.xml file, or any other classes, that you referenced in your get_doc_classes function.

Edit the file(s) following Contributing to the class reference and recompile the engine.

Once the compilation process is finished, the docs will become accessible within the engine's built-in documentation system.

In order to keep documentation up-to-date, all you'll have to do is simply modify one of the XML files and recompile the engine from now on.

If you change your module's API, you can also re-extract the docs, they will contain the things that you previously added. Of course if you point it to your godot folder, make sure you don't lose work by extracting older docs from an older engine build on top of the newer ones.

Note that if you don't have write access rights to your supplied <path>, you might encounter an error similar to the following:

ERROR: Can't write doc file: docs/doc/classes/@GDScript.xml
   At: editor/doc/doc_data.cpp:956

カスタムエディタアイコンの追加

モジュール内で自己完結型のドキュメントを作成する方法と同様に、エディタに表示されるクラスの独自のカスタムアイコンを作成することもできます。

エンジン内に統合されるエディタアイコンを作成する実際のプロセスについては、最初に エディタアイコン を参照してください。

アイコンを作成したら、次の手順に進みます:

  1. icons という名前のモジュールのルートに新しいディレクトリを作成します。これは、モジュールのエディタアイコンを検索するエンジンのデフォルトパスです。

  2. 新しく作成した svg アイコン(最適化されているかどうかに関係なく)をそのフォルダに移動します。

  3. エンジンを再コンパイルし、エディタを実行します。必要に応じて、エディタのインターフェースにアイコンが表示されます。

モジュール内の別の場所にアイコンを保存したい場合は、次のコードスニペットを config.py に追加してデフォルトパスをオーバーライドします:

def get_icons_path():
    return "path/to/icons"

まとめ

覚えておいてください:

  • 継承に GDCLASS マクロを使用するので、Godotはそれをラップできます

  • 関数をスクリプトにバインドし、シグナルのコールバックとして機能できるようにするには、 _bind_methods を使用します。

しかし、これはすべてではありません、あなたが何をするかに応じて、いくつかの(うまくいけば肯定的な)驚きで迎えられます。

  • Node (またはSpriteなどの派生ノードタイプ) から継承すると、新しいクラスがエディタに表示され、「ノードの追加」ダイアログボックスの継承ツリーに表示されます。

  • Resourceから継承すると、リソース リストに表示され、公開されているすべてのプロパティは、保存/読み込み時にシリアル化できます。

  • この同じロジックによって、エディタとエンジンのほぼすべての領域を拡張できます。