Custom resource format loaders

    This guide assumes the reader knows how to create C++ modules and Godot data types. If not, refer to this guide .

    What for?

    • Adding new support for many file formats
    • Audio formats
    • Video formats
    • Machine learning models
    • Raster images

    ImageFormatLoader should be used to load images.

    Creating a ResourceFormatLoader

    ResourceFormatLoaders are usually simple classes which return all the necessary metadata for supporting new extensions in Godot. The class must the return the format name and the extension string.

    In addition, ResourceFormatLoaders must convert file paths into resources with the load function. To load a resource, load must read and handle data serialization.

    1. #include "my_json_loader.h"
    2. #include "my_json.h"
    3. ResourceFormatLoaderMyJson::ResourceFormatLoaderMyJson() {
    4. }
    5. RES ResourceFormatLoaderMyJson::load(const String &p_path, const String &p_original_path, Error *r_error) {
    6. MyJson *my = memnew(MyJson);
    7. *r_error = OK;
    8. Error err = my->set_file(p_path);
    9. return Ref<MyJson>(my);
    10. }
    11. void ResourceFormatLoaderMyJson::get_recognized_extensions(List<String> *p_extensions) const {
    12. p_extensions->push_back("mjson");
    13. }
    14. String ResourceFormatLoaderMyJson::get_resource_type(const String &p_path) const {
    15. if (p_path.get_extension().to_lower() == "mjson")
    16. return "";
    17. }
    18. bool ResourceFormatLoaderMyJson::handles_type(const String &p_type) const {
    19. return (p_type == "MyJson");
    20. }

    Here is an example of how to create a custom datatype

    Some libraries may not define certain common routines such as IO handling. Therefore, Godot call translations are required.

    1. #include <istream>
    2. #include <streambuf>
    3. class GodotFileInStreamBuf : public std::streambuf {
    4. public:
    5. GodotFileInStreamBuf(FileAccess *fa) {
    6. _file = fa;
    7. }
    8. if (_file->eof_reached()) {
    9. return EOF;
    10. } else {
    11. size_t pos = _file->get_position();
    12. uint8_t ret = _file->get_8();
    13. return ret;
    14. }
    15. }
    16. int uflow() {
    17. return _file->eof_reached() ? EOF : _file->get_8();
    18. }
    19. private:
    20. FileAccess *_file;
    21. };

    Registering the new file format

    Godot registers ResourcesFormatLoader with a ResourceLoader handler. The handler selects the proper loader automatically when load is called.

    1. {
    2. "savefilename" : "demo.mjson",
    3. "demo": [
    4. "welcome",
    5. "to",
    6. "godot",
    7. "resource",
    8. "loaders"
    9. }