summaryrefslogtreecommitdiff
path: root/modules
diff options
context:
space:
mode:
Diffstat (limited to 'modules')
-rw-r--r--modules/SCsub2
-rw-r--r--modules/arkit/SCsub10
-rw-r--r--modules/arkit/arkit_interface.h125
-rw-r--r--modules/arkit/arkit_interface.mm738
-rw-r--r--modules/arkit/arkit_session_delegate.h50
-rw-r--r--modules/arkit/arkit_session_delegate.mm56
-rw-r--r--modules/arkit/config.py5
-rw-r--r--modules/arkit/register_types.cpp (renamed from modules/mono/editor/monodevelop_instance.h)35
-rw-r--r--modules/arkit/register_types.h (renamed from modules/mono/editor/mono_build_info.cpp)36
-rw-r--r--modules/assimp/SCsub118
-rw-r--r--modules/assimp/editor_scene_importer_assimp.cpp34
-rw-r--r--modules/bmp/image_loader_bmp.cpp30
-rw-r--r--modules/bmp/image_loader_bmp.h8
-rw-r--r--modules/bullet/SCsub8
-rw-r--r--modules/bullet/bullet_physics_server.cpp2
-rw-r--r--modules/bullet/bullet_physics_server.h2
-rw-r--r--modules/bullet/collision_object_bullet.cpp2
-rw-r--r--modules/bullet/cone_twist_joint_bullet.cpp2
-rw-r--r--modules/bullet/generic_6dof_joint_bullet.cpp4
-rw-r--r--modules/bullet/hinge_joint_bullet.cpp2
-rw-r--r--modules/bullet/pin_joint_bullet.cpp2
-rw-r--r--modules/bullet/rigid_body_bullet.cpp8
-rw-r--r--modules/bullet/rigid_body_bullet.h2
-rw-r--r--modules/bullet/space_bullet.h3
-rw-r--r--modules/csg/csg.cpp10
-rw-r--r--modules/csg/csg_gizmos.cpp66
-rw-r--r--modules/csg/csg_gizmos.h3
-rw-r--r--modules/csg/csg_shape.cpp17
-rw-r--r--modules/csg/csg_shape.h21
-rw-r--r--modules/csg/doc_classes/CSGBox.xml6
-rw-r--r--modules/csg/doc_classes/CSGCylinder.xml10
-rw-r--r--modules/csg/doc_classes/CSGPolygon.xml8
-rw-r--r--modules/csg/doc_classes/CSGPrimitive.xml2
-rw-r--r--modules/csg/doc_classes/CSGShape.xml14
-rw-r--r--modules/csg/doc_classes/CSGSphere.xml8
-rw-r--r--modules/csg/doc_classes/CSGTorus.xml10
-rw-r--r--modules/csg/icons/icon_c_s_g_box.svg6
-rw-r--r--modules/csg/icons/icon_c_s_g_capsule.svg6
-rw-r--r--modules/csg/icons/icon_c_s_g_combiner.svg8
-rw-r--r--modules/csg/icons/icon_c_s_g_cylinder.svg6
-rw-r--r--modules/csg/icons/icon_c_s_g_mesh.svg6
-rw-r--r--modules/csg/icons/icon_c_s_g_polygon.svg6
-rw-r--r--modules/csg/icons/icon_c_s_g_sphere.svg6
-rw-r--r--modules/csg/icons/icon_c_s_g_torus.svg6
-rw-r--r--modules/cvtt/image_compress_cvtt.cpp10
-rw-r--r--modules/dds/texture_loader_dds.cpp30
-rw-r--r--modules/dds/texture_loader_dds.h1
-rw-r--r--modules/enet/SCsub2
-rw-r--r--modules/enet/doc_classes/NetworkedMultiplayerENet.xml34
-rw-r--r--modules/enet/networked_multiplayer_enet.cpp9
-rw-r--r--modules/enet/networked_multiplayer_enet.h3
-rw-r--r--modules/etc/texture_loader_pkm.cpp2
-rw-r--r--modules/etc/texture_loader_pkm.h1
-rw-r--r--modules/freetype/SCsub8
-rw-r--r--modules/gdnative/android/android_gdn.cpp29
-rw-r--r--modules/gdnative/arvr/arvr_interface_gdnative.cpp37
-rw-r--r--modules/gdnative/arvr/arvr_interface_gdnative.h5
-rw-r--r--modules/gdnative/config.py2
-rw-r--r--modules/gdnative/doc_classes/@NativeScript.xml (renamed from modules/stb_vorbis/doc_classes/ResourceImporterOGGVorbis.xml)2
-rw-r--r--modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml4
-rw-r--r--modules/gdnative/doc_classes/GDNativeLibrary.xml8
-rw-r--r--modules/gdnative/doc_classes/NativeScript.xml6
-rw-r--r--modules/gdnative/gdnative.cpp18
-rw-r--r--modules/gdnative/gdnative.h8
-rw-r--r--modules/gdnative/gdnative/array.cpp4
-rw-r--r--modules/gdnative/gdnative/vector2.cpp8
-rw-r--r--modules/gdnative/gdnative/vector3.cpp8
-rw-r--r--modules/gdnative/gdnative_api.json32
-rw-r--r--modules/gdnative/icons/icon_g_d_native_library.svg5
-rw-r--r--modules/gdnative/icons/icon_native_script.svg5
-rw-r--r--modules/gdnative/include/android/godot_android.h2
-rw-r--r--modules/gdnative/include/arvr/godot_arvr.h1
-rw-r--r--modules/gdnative/include/gdnative/gdnative.h6
-rw-r--r--modules/gdnative/include/gdnative/vector2.h2
-rw-r--r--modules/gdnative/include/gdnative/vector3.h2
-rw-r--r--modules/gdnative/include/pluginscript/godot_pluginscript.h2
-rw-r--r--modules/gdnative/nativescript/SCsub1
-rw-r--r--modules/gdnative/nativescript/nativescript.h6
-rw-r--r--modules/gdnative/net/multiplayer_peer_gdnative.cpp2
-rw-r--r--modules/gdnative/net/multiplayer_peer_gdnative.h2
-rw-r--r--modules/gdnative/net/packet_peer_gdnative.h2
-rw-r--r--modules/gdnative/pluginscript/pluginscript_language.cpp9
-rw-r--r--modules/gdnative/pluginscript/pluginscript_language.h2
-rw-r--r--modules/gdnative/pluginscript/pluginscript_loader.h4
-rw-r--r--modules/gdnative/pluginscript/pluginscript_script.cpp30
-rw-r--r--modules/gdnative/register_types.cpp9
-rw-r--r--modules/gdnative/videodecoder/video_stream_gdnative.h1
-rw-r--r--modules/gdscript/config.py1
-rw-r--r--modules/gdscript/doc_classes/@GDScript.xml1347
-rw-r--r--modules/gdscript/editor/gdscript_highlighter.cpp23
-rw-r--r--modules/gdscript/gdscript.cpp4
-rw-r--r--modules/gdscript/gdscript.h6
-rw-r--r--modules/gdscript/gdscript_compiler.cpp12
-rw-r--r--modules/gdscript/gdscript_editor.cpp249
-rw-r--r--modules/gdscript/gdscript_function.cpp141
-rw-r--r--modules/gdscript/gdscript_functions.cpp35
-rw-r--r--modules/gdscript/gdscript_functions.h2
-rw-r--r--modules/gdscript/gdscript_parser.cpp174
-rw-r--r--modules/gdscript/gdscript_parser.h6
-rw-r--r--modules/gdscript/gdscript_tokenizer.cpp31
-rw-r--r--modules/gdscript/icons/icon_g_d_script.svg5
-rw-r--r--modules/gridmap/doc_classes/GridMap.xml20
-rw-r--r--modules/gridmap/grid_map.cpp5
-rw-r--r--modules/gridmap/grid_map_editor_plugin.cpp23
-rw-r--r--modules/gridmap/grid_map_editor_plugin.h3
-rw-r--r--modules/gridmap/icons/icon_grid_map.svg5
-rw-r--r--modules/jpg/image_loader_jpegd.cpp4
-rwxr-xr-xmodules/mbedtls/stream_peer_mbed_tls.cpp4
-rwxr-xr-xmodules/mbedtls/stream_peer_mbed_tls.h1
-rw-r--r--modules/mobile_vr/doc_classes/MobileVRInterface.xml20
-rw-r--r--modules/mono/SCsub33
-rw-r--r--modules/mono/__init__.py0
-rw-r--r--modules/mono/build_scripts/api_solution_build.py66
-rw-r--r--modules/mono/build_scripts/godot_tools_build.py112
-rw-r--r--modules/mono/build_scripts/make_android_mono_config.py69
-rw-r--r--modules/mono/build_scripts/make_cs_compressed_header.py21
-rw-r--r--modules/mono/build_scripts/mono_configure.py195
-rw-r--r--modules/mono/build_scripts/mono_reg_utils.py2
-rw-r--r--modules/mono/build_scripts/patches/fix-mono-android-tkill.diff70
-rw-r--r--modules/mono/build_scripts/solution_builder.py (renamed from modules/mono/build_scripts/godotsharptools_build.py)155
-rw-r--r--modules/mono/class_db_api_json.cpp242
-rw-r--r--modules/mono/class_db_api_json.h39
-rw-r--r--modules/mono/config.py10
-rw-r--r--modules/mono/csharp_script.cpp546
-rw-r--r--modules/mono/csharp_script.h32
-rw-r--r--modules/mono/editor/GodotSharpTools/.gitignore2
-rw-r--r--modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs425
-rw-r--r--modules/mono/editor/GodotSharpTools/Editor/GodotSharpExport.cs74
-rw-r--r--modules/mono/editor/GodotSharpTools/GodotSharpTools.sln17
-rw-r--r--modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs71
-rw-r--r--modules/mono/editor/GodotSharpTools/Utils/OS.cs62
-rw-r--r--modules/mono/editor/GodotTools/.gitignore356
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs186
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj59
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs35
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj38
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Core/ProcessExtensions.cs38
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs26
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs (renamed from modules/mono/editor/GodotSharpTools/StringExtensions.cs)33
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiAssembliesInfo.cs15
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiSolutionGenerator.cs52
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs122
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj (renamed from modules/mono/editor/GodotSharpTools/GodotSharpTools.csproj)41
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/IdentifierUtils.cs (renamed from modules/mono/editor/GodotSharpTools/Project/IdentifierUtils.cs)14
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs (renamed from modules/mono/editor/GodotSharpTools/Project/ProjectExtensions.cs)3
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs (renamed from modules/mono/editor/GodotSharpTools/Project/ProjectGenerator.cs)40
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs175
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/Properties/AssemblyInfo.cs (renamed from modules/mono/editor/GodotSharpTools/Properties/AssemblyInfo.cs)4
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.ProjectEditor/packages.config (renamed from modules/mono/editor/GodotSharpTools/packages.config)2
-rw-r--r--modules/mono/editor/GodotTools/GodotTools.sln35
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs172
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs210
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/CSharpProject.cs127
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotSharpBuilds.cs277
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs491
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotSharpExport.cs197
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj82
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs48
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/BindingsGenerator.cs87
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs50
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs33
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs91
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs99
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs52
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/MonoBottomPanel.cs343
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/MonoBuildInfo.cs47
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/MonoBuildTab.cs260
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/MonoDevelopInstance.cs (renamed from modules/mono/editor/GodotSharpTools/Editor/MonoDevelopInstance.cs)55
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs26
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Utils/CollectionExtensions.cs20
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Utils/Directory.cs40
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Utils/File.cs43
-rw-r--r--modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs127
-rw-r--r--modules/mono/editor/bindings_generator.cpp200
-rw-r--r--modules/mono/editor/bindings_generator.h8
-rw-r--r--modules/mono/editor/csharp_project.cpp206
-rw-r--r--modules/mono/editor/csharp_project.h7
-rw-r--r--modules/mono/editor/dotnet_solution.cpp140
-rw-r--r--modules/mono/editor/editor_internal_calls.cpp427
-rw-r--r--modules/mono/editor/editor_internal_calls.h (renamed from modules/mono/editor/dotnet_solution.h)37
-rw-r--r--modules/mono/editor/godotsharp_builds.cpp624
-rw-r--r--modules/mono/editor/godotsharp_editor.cpp581
-rw-r--r--modules/mono/editor/godotsharp_editor.h134
-rw-r--r--modules/mono/editor/godotsharp_export.cpp199
-rw-r--r--modules/mono/editor/godotsharp_export.h28
-rw-r--r--modules/mono/editor/mono_bottom_panel.cpp528
-rw-r--r--modules/mono/editor/mono_bottom_panel.h150
-rw-r--r--modules/mono/glue/Managed/.gitignore2
-rw-r--r--modules/mono/glue/Managed/Files/Attributes/RPCAttributes.cs16
-rw-r--r--modules/mono/glue/Managed/Files/Interfaces/ISerializationListener.cs8
-rw-r--r--modules/mono/glue/Managed/Files/Mathf.cs5
-rw-r--r--modules/mono/glue/Managed/Files/StringExtensions.cs9
-rw-r--r--modules/mono/glue/Managed/Files/Vector2.cs8
-rw-r--r--modules/mono/glue/Managed/Files/Vector3.cs8
-rw-r--r--modules/mono/glue/base_object_glue.cpp15
-rw-r--r--modules/mono/glue/collections_glue.cpp8
-rw-r--r--modules/mono/glue/string_glue.cpp12
-rw-r--r--modules/mono/godotsharp_defs.h3
-rw-r--r--modules/mono/godotsharp_dirs.cpp52
-rw-r--r--modules/mono/godotsharp_dirs.h1
-rw-r--r--modules/mono/mono_gc_handle.h2
-rw-r--r--modules/mono/mono_gd/gd_mono.cpp613
-rw-r--r--modules/mono/mono_gd/gd_mono.h42
-rw-r--r--modules/mono/mono_gd/gd_mono_assembly.cpp40
-rw-r--r--modules/mono/mono_gd/gd_mono_assembly.h2
-rw-r--r--modules/mono/mono_gd/gd_mono_class.cpp17
-rw-r--r--modules/mono/mono_gd/gd_mono_class.h1
-rw-r--r--modules/mono/mono_gd/gd_mono_field.cpp28
-rw-r--r--modules/mono/mono_gd/gd_mono_internals.cpp9
-rw-r--r--modules/mono/mono_gd/gd_mono_marshal.cpp38
-rw-r--r--modules/mono/mono_gd/gd_mono_method.cpp2
-rw-r--r--modules/mono/mono_gd/gd_mono_property.cpp2
-rw-r--r--modules/mono/mono_gd/gd_mono_utils.cpp140
-rw-r--r--modules/mono/mono_gd/gd_mono_utils.h42
-rw-r--r--modules/mono/signal_awaiter_utils.cpp4
-rw-r--r--modules/mono/signal_awaiter_utils.h2
-rw-r--r--modules/mono/utils/android_utils.cpp (renamed from modules/mono/editor/monodevelop_instance.cpp)71
-rw-r--r--modules/mono/utils/android_utils.h (renamed from modules/mono/editor/mono_build_info.h)31
-rw-r--r--modules/mono/utils/path_utils.cpp127
-rw-r--r--modules/mono/utils/path_utils.h32
-rw-r--r--modules/mono/utils/string_utils.cpp2
-rw-r--r--modules/mono/utils/thread_local.h2
-rw-r--r--modules/opensimplex/doc_classes/NoiseTexture.xml10
-rw-r--r--modules/opensimplex/doc_classes/OpenSimplexNoise.xml14
-rw-r--r--modules/opensimplex/icons/icon_noise_texture.svg3
-rw-r--r--modules/opensimplex/noise_texture.h6
-rw-r--r--modules/opensimplex/open_simplex_noise.h2
-rw-r--r--modules/opus/SCsub14
-rw-r--r--modules/opus/audio_stream_opus.cpp4
-rw-r--r--modules/opus/audio_stream_opus.h5
-rw-r--r--modules/pvr/texture_loader_pvr.cpp6
-rw-r--r--modules/pvr/texture_loader_pvr.h1
-rw-r--r--modules/recast/navigation_mesh_editor_plugin.cpp4
-rw-r--r--modules/recast/navigation_mesh_generator.cpp18
-rw-r--r--modules/recast/register_types.cpp7
-rw-r--r--modules/regex/SCsub11
-rw-r--r--modules/regex/doc_classes/RegEx.xml16
-rw-r--r--modules/regex/doc_classes/RegExMatch.xml10
-rw-r--r--modules/squish/image_compress_squish.cpp4
-rw-r--r--modules/stb_vorbis/audio_stream_ogg_vorbis.cpp3
-rw-r--r--modules/stb_vorbis/audio_stream_ogg_vorbis.h4
-rw-r--r--modules/stb_vorbis/config.py1
-rw-r--r--modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml6
-rw-r--r--modules/stb_vorbis/register_types.cpp13
-rw-r--r--modules/stb_vorbis/resource_importer_ogg_vorbis.cpp5
-rw-r--r--modules/stb_vorbis/resource_importer_ogg_vorbis.h3
-rw-r--r--modules/svg/SCsub2
-rw-r--r--modules/svg/image_loader_svg.cpp2
-rw-r--r--modules/tga/image_loader_tga.cpp2
-rw-r--r--modules/theora/SCsub2
-rw-r--r--modules/theora/config.py1
-rw-r--r--modules/theora/video_stream_theora.h1
-rw-r--r--modules/tinyexr/image_loader_tinyexr.cpp6
-rw-r--r--modules/upnp/SCsub5
-rw-r--r--modules/upnp/doc_classes/UPNP.xml19
-rw-r--r--modules/upnp/doc_classes/UPNPDevice.xml12
-rw-r--r--modules/vhacd/SCsub21
-rw-r--r--modules/visual_script/config.py1
-rw-r--r--modules/visual_script/doc_classes/@VisualScript.xml (renamed from modules/gdnative/doc_classes/ResourceFormatLoaderVideoStreamGDNative.xml)4
-rw-r--r--modules/visual_script/doc_classes/VisualScript.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml94
-rw-r--r--modules/visual_script/doc_classes/VisualScriptClassConstant.xml6
-rw-r--r--modules/visual_script/doc_classes/VisualScriptComment.xml6
-rw-r--r--modules/visual_script/doc_classes/VisualScriptConstant.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptCustomNode.xml8
-rw-r--r--modules/visual_script/doc_classes/VisualScriptDeconstruct.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptEmitSignal.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptFunctionCall.xml10
-rw-r--r--modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptInputAction.xml4
-rw-r--r--modules/visual_script/doc_classes/VisualScriptLocalVar.xml4
-rw-r--r--modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml4
-rw-r--r--modules/visual_script/doc_classes/VisualScriptMathConstant.xml3
-rw-r--r--modules/visual_script/doc_classes/VisualScriptOperator.xml4
-rw-r--r--modules/visual_script/doc_classes/VisualScriptPropertyGet.xml6
-rw-r--r--modules/visual_script/doc_classes/VisualScriptPropertySet.xml8
-rw-r--r--modules/visual_script/doc_classes/VisualScriptResourcePath.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptReturn.xml4
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSceneNode.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSelect.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSequence.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptSwitch.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptTypeCast.xml4
-rw-r--r--modules/visual_script/doc_classes/VisualScriptVariableGet.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptVariableSet.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptYield.xml2
-rw-r--r--modules/visual_script/doc_classes/VisualScriptYieldSignal.xml6
-rw-r--r--modules/visual_script/icons/icon_visual_script.svg6
-rw-r--r--modules/visual_script/visual_script.cpp21
-rw-r--r--modules/visual_script/visual_script.h5
-rw-r--r--modules/visual_script/visual_script_builtin_funcs.cpp151
-rw-r--r--modules/visual_script/visual_script_builtin_funcs.h5
-rw-r--r--modules/visual_script/visual_script_editor.cpp165
-rw-r--r--modules/visual_script/visual_script_editor.h4
-rw-r--r--modules/visual_script/visual_script_expression.cpp2
-rw-r--r--modules/visual_script/visual_script_expression.h2
-rw-r--r--modules/visual_script/visual_script_flow_control.h14
-rw-r--r--modules/visual_script/visual_script_func_nodes.cpp46
-rw-r--r--modules/visual_script/visual_script_func_nodes.h11
-rw-r--r--modules/visual_script/visual_script_nodes.h54
-rw-r--r--modules/visual_script/visual_script_property_selector.cpp3
-rw-r--r--modules/visual_script/visual_script_property_selector.h2
-rw-r--r--modules/visual_script/visual_script_yield_nodes.cpp1
-rw-r--r--modules/visual_script/visual_script_yield_nodes.h6
-rw-r--r--modules/vorbis/audio_stream_ogg_vorbis.cpp5
-rw-r--r--modules/vorbis/audio_stream_ogg_vorbis.h1
-rw-r--r--modules/webm/config.py1
-rw-r--r--modules/webm/libvpx/SCsub6
-rw-r--r--modules/webm/video_stream_webm.cpp7
-rw-r--r--modules/webm/video_stream_webm.h3
-rw-r--r--modules/webp/image_loader_webp.cpp8
-rw-r--r--modules/webrtc/config.py3
-rw-r--r--modules/webrtc/doc_classes/WebRTCDataChannel.xml23
-rw-r--r--modules/webrtc/doc_classes/WebRTCMultiplayer.xml85
-rw-r--r--modules/webrtc/doc_classes/WebRTCPeerConnection.xml61
-rw-r--r--modules/webrtc/register_types.cpp2
-rw-r--r--modules/webrtc/webrtc_data_channel_gdnative.cpp1
-rw-r--r--modules/webrtc/webrtc_data_channel_js.cpp35
-rw-r--r--modules/webrtc/webrtc_multiplayer.cpp384
-rw-r--r--modules/webrtc/webrtc_multiplayer.h (renamed from modules/mono/editor/godotsharp_builds.h)113
-rw-r--r--modules/websocket/SCsub105
-rw-r--r--modules/websocket/doc_classes/WebSocketClient.xml18
-rw-r--r--modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml21
-rw-r--r--modules/websocket/doc_classes/WebSocketPeer.xml18
-rw-r--r--modules/websocket/doc_classes/WebSocketServer.xml21
-rw-r--r--modules/websocket/emws_client.cpp6
-rw-r--r--modules/websocket/emws_client.h1
-rw-r--r--modules/websocket/emws_server.cpp4
-rw-r--r--modules/websocket/emws_server.h1
-rw-r--r--modules/websocket/lws_client.cpp237
-rw-r--r--modules/websocket/lws_helper.cpp157
-rw-r--r--modules/websocket/lws_helper.h111
-rw-r--r--modules/websocket/lws_peer.cpp270
-rw-r--r--modules/websocket/lws_server.cpp214
-rw-r--r--modules/websocket/register_types.cpp11
-rw-r--r--modules/websocket/websocket_client.h2
-rw-r--r--modules/websocket/websocket_multiplayer_peer.cpp3
-rw-r--r--modules/websocket/websocket_multiplayer_peer.h5
-rw-r--r--modules/websocket/websocket_server.h2
-rw-r--r--modules/websocket/wsl_client.cpp363
-rw-r--r--modules/websocket/wsl_client.h (renamed from modules/websocket/lws_client.h)45
-rw-r--r--modules/websocket/wsl_peer.cpp339
-rw-r--r--modules/websocket/wsl_peer.h (renamed from modules/websocket/lws_peer.h)72
-rw-r--r--modules/websocket/wsl_server.cpp302
-rw-r--r--modules/websocket/wsl_server.h (renamed from modules/websocket/lws_server.h)55
-rw-r--r--modules/xatlas_unwrap/register_types.cpp96
348 files changed, 12563 insertions, 6754 deletions
diff --git a/modules/SCsub b/modules/SCsub
index 67f5893db4..36c2472c42 100644
--- a/modules/SCsub
+++ b/modules/SCsub
@@ -13,7 +13,7 @@ env.modules_sources = [
for x in env.module_list:
if (x in env.disabled_modules):
continue
- env_modules.Append(CPPFLAGS=["-DMODULE_" + x.upper() + "_ENABLED"])
+ env_modules.Append(CPPDEFINES=["MODULE_" + x.upper() + "_ENABLED"])
SConscript(x + "/SCsub")
if env.split_modules:
diff --git a/modules/arkit/SCsub b/modules/arkit/SCsub
new file mode 100644
index 0000000000..b43d936768
--- /dev/null
+++ b/modules/arkit/SCsub
@@ -0,0 +1,10 @@
+#!/usr/bin/env python
+
+Import('env')
+Import('env_modules')
+
+env_arkit = env_modules.Clone()
+
+# Add source files
+env_arkit.add_source_files(env.modules_sources, "*.cpp")
+env_arkit.add_source_files(env.modules_sources, "*.mm")
diff --git a/modules/arkit/arkit_interface.h b/modules/arkit/arkit_interface.h
new file mode 100644
index 0000000000..8129611287
--- /dev/null
+++ b/modules/arkit/arkit_interface.h
@@ -0,0 +1,125 @@
+/*************************************************************************/
+/* arkit_interface.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef ARKIT_INTERFACE_H
+#define ARKIT_INTERFACE_H
+
+#include "servers/arvr/arvr_interface.h"
+#include "servers/arvr/arvr_positional_tracker.h"
+#include "servers/camera/camera_feed.h"
+
+/**
+ @author Bastiaan Olij <mux213@gmail.com>
+
+ ARKit interface between iPhone and Godot
+*/
+
+// forward declaration for some needed objects
+class ARKitShader;
+
+class ARKitInterface : public ARVRInterface {
+ GDCLASS(ARKitInterface, ARVRInterface);
+
+private:
+ bool initialized;
+ bool session_was_started;
+ bool plane_detection_is_enabled;
+ bool light_estimation_is_enabled;
+ real_t ambient_intensity;
+ real_t ambient_color_temperature;
+
+ Transform transform;
+ CameraMatrix projection;
+ float eye_height, z_near, z_far;
+
+ Ref<CameraFeed> feed;
+ int image_width[2];
+ int image_height[2];
+ PoolVector<uint8_t> img_data[2];
+
+ struct anchor_map {
+ ARVRPositionalTracker *tracker;
+ unsigned char uuid[16];
+ };
+
+ ///@TODO should use memory map object from Godot?
+ unsigned int num_anchors;
+ unsigned int max_anchors;
+ anchor_map *anchors;
+ ARVRPositionalTracker *get_anchor_for_uuid(const unsigned char *p_uuid);
+ void remove_anchor_for_uuid(const unsigned char *p_uuid);
+ void remove_all_anchors();
+
+protected:
+ static void _bind_methods();
+
+public:
+ void start_session();
+ void stop_session();
+
+ bool get_anchor_detection_is_enabled() const;
+ void set_anchor_detection_is_enabled(bool p_enable);
+ virtual int get_camera_feed_id();
+
+ bool get_light_estimation_is_enabled() const;
+ void set_light_estimation_is_enabled(bool p_enable);
+
+ real_t get_ambient_intensity() const;
+ real_t get_ambient_color_temperature() const;
+
+ /* while Godot has its own raycast logic this takes ARKits camera into account and hits on any ARAnchor */
+ Array raycast(Vector2 p_screen_coord);
+
+ void notification(int p_what);
+
+ virtual StringName get_name() const;
+ virtual int get_capabilities() const;
+
+ virtual bool is_initialized() const;
+ virtual bool initialize();
+ virtual void uninitialize();
+
+ virtual Size2 get_render_targetsize();
+ virtual bool is_stereo();
+ virtual Transform get_transform_for_eye(ARVRInterface::Eyes p_eye, const Transform &p_cam_transform);
+ virtual CameraMatrix get_projection_for_eye(ARVRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far);
+ virtual void commit_for_eye(ARVRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect);
+
+ virtual void process();
+
+ // called by delegate (void * because C++ and Obj-C don't always mix, should really change all platform/iphone/*.cpp files to .mm)
+ void _add_or_update_anchor(void *p_anchor);
+ void _remove_anchor(void *p_anchor);
+
+ ARKitInterface();
+ ~ARKitInterface();
+};
+
+#endif /* !ARKIT_INTERFACE_H */
diff --git a/modules/arkit/arkit_interface.mm b/modules/arkit/arkit_interface.mm
new file mode 100644
index 0000000000..de58f93276
--- /dev/null
+++ b/modules/arkit/arkit_interface.mm
@@ -0,0 +1,738 @@
+/*************************************************************************/
+/* arkit_interface.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "camera_ios.h"
+#include "core/os/input.h"
+#include "core/os/os.h"
+#include "scene/resources/surface_tool.h"
+#include "servers/visual/visual_server_globals.h"
+
+#import <ARKit/ARKit.h>
+#import <UIKit/UIKit.h>
+
+#include "arkit_interface.h"
+#include "arkit_session_delegate.h"
+
+// just a dirty workaround for now, declare these as globals. I'll probably encapsulate ARSession and associated logic into an mm object and change ARKitInterface to a normal cpp object that consumes it.
+ARSession *ar_session;
+ARKitSessionDelegate *ar_delegate;
+NSTimeInterval last_timestamp;
+
+/* this is called when we initialize or when we come back from having our app pushed to the background, just (re)start our session */
+void ARKitInterface::start_session() {
+ // We're active...
+ session_was_started = true;
+
+ // Ignore this if we're not initialized...
+ if (initialized) {
+ print_line("Starting ARKit session");
+ ARWorldTrackingConfiguration *configuration = [ARWorldTrackingConfiguration new];
+ configuration.lightEstimationEnabled = light_estimation_is_enabled;
+ if (plane_detection_is_enabled) {
+ configuration.planeDetection = ARPlaneDetectionVertical | ARPlaneDetectionHorizontal;
+ } else {
+ configuration.planeDetection = 0;
+ }
+
+ // make sure our camera is on
+ if (feed.is_valid()) {
+ feed->set_active(true);
+ }
+
+ [ar_session runWithConfiguration:configuration];
+ }
+}
+
+void ARKitInterface::stop_session() {
+ session_was_started = false;
+
+ // Ignore this if we're not initialized...
+ if (initialized) {
+ // make sure our camera is off
+ if (feed.is_valid()) {
+ feed->set_active(false);
+ }
+
+ [ar_session pause];
+ }
+}
+
+void ARKitInterface::notification(int p_what) {
+ // TODO, this is not being called, need to find out why, possibly because this is not a node.
+ // in that case we need to find a way to get these notifications!
+ switch (p_what) {
+ case MainLoop::NOTIFICATION_WM_FOCUS_IN: {
+ print_line("Focus in");
+
+ start_session();
+ }; break;
+ case MainLoop::NOTIFICATION_WM_FOCUS_OUT: {
+ print_line("Focus out");
+
+ stop_session();
+ }; break;
+ default:
+ break;
+ }
+}
+
+bool ARKitInterface::get_anchor_detection_is_enabled() const {
+ return plane_detection_is_enabled;
+}
+
+void ARKitInterface::set_anchor_detection_is_enabled(bool p_enable) {
+ if (plane_detection_is_enabled != p_enable) {
+ plane_detection_is_enabled = p_enable;
+
+ // Restart our session (this will be ignore if we're not initialised)
+ if (session_was_started) {
+ start_session();
+ }
+ }
+}
+
+int ARKitInterface::get_camera_feed_id() {
+ if (feed.is_null()) {
+ return 0;
+ } else {
+ return feed->get_id();
+ }
+}
+
+bool ARKitInterface::get_light_estimation_is_enabled() const {
+ return light_estimation_is_enabled;
+}
+
+void ARKitInterface::set_light_estimation_is_enabled(bool p_enable) {
+ if (light_estimation_is_enabled != p_enable) {
+ light_estimation_is_enabled = p_enable;
+
+ // Restart our session (this will be ignore if we're not initialised)
+ if (session_was_started) {
+ start_session();
+ }
+ }
+}
+
+real_t ARKitInterface::get_ambient_intensity() const {
+ return ambient_intensity;
+}
+
+real_t ARKitInterface::get_ambient_color_temperature() const {
+ return ambient_color_temperature;
+}
+
+StringName ARKitInterface::get_name() const {
+ return "ARKit";
+}
+
+int ARKitInterface::get_capabilities() const {
+ return ARKitInterface::ARVR_MONO + ARKitInterface::ARVR_AR;
+}
+
+Array ARKitInterface::raycast(Vector2 p_screen_coord) {
+ Array arr;
+ Size2 screen_size = OS::get_singleton()->get_window_size();
+ CGPoint point;
+ point.x = p_screen_coord.x / screen_size.x;
+ point.y = p_screen_coord.y / screen_size.y;
+
+ ///@TODO maybe give more options here, for now we're taking just ARAchors into account that were found during plane detection keeping their size into account
+ NSArray<ARHitTestResult *> *results = [ar_session.currentFrame hittest:point types:ARHitTestResultTypeExistingPlaneUsingExtent];
+
+ for (ARHitTestResult *result in results) {
+ Transform transform;
+
+ matrix_float4x4 m44 = result.worldTransform;
+ transform.basis.elements[0].x = m44.columns[0][0];
+ transform.basis.elements[1].x = m44.columns[0][1];
+ transform.basis.elements[2].x = m44.columns[0][2];
+ transform.basis.elements[0].y = m44.columns[1][0];
+ transform.basis.elements[1].y = m44.columns[1][1];
+ transform.basis.elements[2].y = m44.columns[1][2];
+ transform.basis.elements[0].z = m44.columns[2][0];
+ transform.basis.elements[1].z = m44.columns[2][1];
+ transform.basis.elements[2].z = m44.columns[2][2];
+ transform.origin.x = m44.columns[3][0];
+ transform.origin.y = m44.columns[3][1];
+ transform.origin.z = m44.columns[3][2];
+
+ /* important, NOT scaled to world_scale !! */
+ arr.push_back(transform);
+ }
+
+ return arr;
+}
+
+void ARKitInterface::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("_notification", "what"), &ARKitInterface::_notification);
+
+ ClassDB::bind_method(D_METHOD("set_light_estimation_is_enabled", "enable"), &ARKitInterface::set_light_estimation_is_enabled);
+ ClassDB::bind_method(D_METHOD("get_light_estimation_is_enabled"), &ARKitInterface::get_light_estimation_is_enabled);
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "light_estimation"), "set_light_estimation_is_enabled", "get_light_estimation_is_enabled");
+
+ ClassDB::bind_method(D_METHOD("get_ambient_intensity"), &ARKitInterface::get_ambient_intensity);
+ ClassDB::bind_method(D_METHOD("get_ambient_color_temperature"), &ARKitInterface::get_ambient_color_temperature);
+
+ ClassDB::bind_method(D_METHOD("raycast", "screen_coord"), &ARKitInterface::raycast);
+}
+
+bool ARKitInterface::is_stereo() {
+ // this is a mono device...
+ return false;
+}
+
+bool ARKitInterface::is_initialized() const {
+ return initialized;
+}
+
+bool ARKitInterface::initialize() {
+ ARVRServer *arvr_server = ARVRServer::get_singleton();
+ ERR_FAIL_NULL_V(arvr_server, false);
+
+ if (!initialized) {
+ print_line("initializing ARKit");
+
+ // create our ar session and delegate
+ ar_session = [ARSession new];
+ ar_delegate = [ARKitSessionDelegate new];
+ ar_delegate.arkit_interface = this;
+ ar_session.delegate = ar_delegate;
+
+ // reset our transform
+ transform = Transform();
+
+ // make this our primary interface
+ arvr_server->set_primary_interface(this);
+
+ // make sure we have our feed setup
+ if (feed.is_null()) {
+ feed.instance();
+ feed->set_name("ARKit");
+
+ CameraServer *cs = CameraServer::get_singleton();
+ if (cs != NULL) {
+ cs->add_feed(feed);
+ }
+ }
+ feed->set_active(true);
+
+ // yeah!
+ initialized = true;
+
+ // Start our session...
+ start_session();
+ }
+
+ return true;
+}
+
+void ARKitInterface::uninitialize() {
+ if (initialized) {
+ ARVRServer *arvr_server = ARVRServer::get_singleton();
+ if (arvr_server != NULL) {
+ // no longer our primary interface
+ arvr_server->clear_primary_interface_if(this);
+ }
+
+ if (feed.is_valid()) {
+ CameraServer *cs = CameraServer::get_singleton();
+ if ((cs != NULL)) {
+ cs->remove_feed(feed);
+ }
+ feed.unref();
+ }
+
+ remove_all_anchors();
+
+ [ar_session release];
+ [ar_delegate release];
+ ar_session = NULL;
+ ar_delegate = NULL;
+ initialized = false;
+ session_was_started = false;
+ }
+}
+
+Size2 ARKitInterface::get_render_targetsize() {
+ _THREAD_SAFE_METHOD_
+
+ Size2 target_size = OS::get_singleton()->get_window_size();
+
+ return target_size;
+}
+
+Transform ARKitInterface::get_transform_for_eye(ARVRInterface::Eyes p_eye, const Transform &p_cam_transform) {
+ _THREAD_SAFE_METHOD_
+
+ Transform transform_for_eye;
+
+ ARVRServer *arvr_server = ARVRServer::get_singleton();
+ ERR_FAIL_NULL_V(arvr_server, transform_for_eye);
+
+ if (initialized) {
+ float world_scale = arvr_server->get_world_scale();
+
+ // just scale our origin point of our transform, note that we really shouldn't be using world_scale in ARKit but....
+ transform_for_eye = transform;
+ transform_for_eye.origin *= world_scale;
+
+ transform_for_eye = p_cam_transform * arvr_server->get_reference_frame() * transform_for_eye;
+ } else {
+ // huh? well just return what we got....
+ transform_for_eye = p_cam_transform;
+ }
+
+ return transform_for_eye;
+}
+
+CameraMatrix ARKitInterface::get_projection_for_eye(ARVRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) {
+ // Remember our near and far, it will be used in process when we obtain our projection from our ARKit session.
+ z_near = p_z_near;
+ z_far = p_z_far;
+
+ return projection;
+}
+
+void ARKitInterface::commit_for_eye(ARVRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) {
+ _THREAD_SAFE_METHOD_
+
+ // We must have a valid render target
+ ERR_FAIL_COND(!p_render_target.is_valid());
+
+ // Because we are rendering to our device we must use our main viewport!
+ ERR_FAIL_COND(p_screen_rect == Rect2());
+
+ // get the size of our screen
+ Rect2 screen_rect = p_screen_rect;
+
+ // screen_rect.position.x += screen_rect.size.x;
+ // screen_rect.size.x = -screen_rect.size.x;
+ // screen_rect.position.y += screen_rect.size.y;
+ // screen_rect.size.y = -screen_rect.size.y;
+
+ VSG::rasterizer->set_current_render_target(RID());
+ VSG::rasterizer->blit_render_target_to_screen(p_render_target, screen_rect, 0);
+}
+
+ARVRPositionalTracker *ARKitInterface::get_anchor_for_uuid(const unsigned char *p_uuid) {
+ if (anchors == NULL) {
+ num_anchors = 0;
+ max_anchors = 10;
+ anchors = (anchor_map *)malloc(sizeof(anchor_map) * max_anchors);
+ }
+
+ ERR_FAIL_NULL_V(anchors, NULL);
+
+ for (unsigned int i = 0; i < num_anchors; i++) {
+ if (memcmp(anchors[i].uuid, p_uuid, 16) == 0) {
+ return anchors[i].tracker;
+ }
+ }
+
+ if (num_anchors + 1 == max_anchors) {
+ max_anchors += 10;
+ anchors = (anchor_map *)realloc(anchors, sizeof(anchor_map) * max_anchors);
+ ERR_FAIL_NULL_V(anchors, NULL);
+ }
+
+ ARVRPositionalTracker *new_tracker = memnew(ARVRPositionalTracker);
+ new_tracker->set_type(ARVRServer::TRACKER_ANCHOR);
+
+ char tracker_name[256];
+ sprintf(tracker_name, "Anchor %02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", p_uuid[0], p_uuid[1], p_uuid[2], p_uuid[3], p_uuid[4], p_uuid[5], p_uuid[6], p_uuid[7], p_uuid[8], p_uuid[9], p_uuid[10], p_uuid[11], p_uuid[12], p_uuid[13], p_uuid[14], p_uuid[15]);
+
+ String name = tracker_name;
+ print_line("Adding tracker " + name);
+ new_tracker->set_name(name);
+
+ // add our tracker
+ ARVRServer::get_singleton()->add_tracker(new_tracker);
+ anchors[num_anchors].tracker = new_tracker;
+ memcpy(anchors[num_anchors].uuid, p_uuid, 16);
+ num_anchors++;
+
+ return new_tracker;
+}
+
+void ARKitInterface::remove_anchor_for_uuid(const unsigned char *p_uuid) {
+ if (anchors != NULL) {
+ for (unsigned int i = 0; i < num_anchors; i++) {
+ if (memcmp(anchors[i].uuid, p_uuid, 16) == 0) {
+ // remove our tracker
+ ARVRServer::get_singleton()->remove_tracker(anchors[i].tracker);
+ memdelete(anchors[i].tracker);
+
+ // bring remaining forward
+ for (unsigned int j = i + 1; j < num_anchors; j++) {
+ anchors[j - 1] = anchors[j];
+ };
+
+ // decrease count
+ num_anchors--;
+ return;
+ }
+ }
+ }
+}
+
+void ARKitInterface::remove_all_anchors() {
+ if (anchors != NULL) {
+ for (unsigned int i = 0; i < num_anchors; i++) {
+ // remove our tracker
+ ARVRServer::get_singleton()->remove_tracker(anchors[i].tracker);
+ memdelete(anchors[i].tracker);
+ };
+
+ free(anchors);
+ anchors = NULL;
+ num_anchors = 0;
+ }
+}
+
+void ARKitInterface::process() {
+ _THREAD_SAFE_METHOD_
+
+ if (@available(iOS 11.0, *)) {
+ if (initialized) {
+ // get our next ARFrame
+ ARFrame *current_frame = ar_session.currentFrame;
+ if (last_timestamp != current_frame.timestamp) {
+ // only process if we have a new frame
+ last_timestamp = current_frame.timestamp;
+
+ // get some info about our screen and orientation
+ Size2 screen_size = OS::get_singleton()->get_window_size();
+ UIDeviceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
+
+ // Grab our camera image for our backbuffer
+ CVPixelBufferRef pixelBuffer = current_frame.capturedImage;
+ if ((CVPixelBufferGetPlaneCount(pixelBuffer) == 2) && (feed != NULL)) {
+ // Plane 0 is our Y and Plane 1 is our CbCr buffer
+
+ // ignored, we check each plane separately
+ // image_width = CVPixelBufferGetWidth(pixelBuffer);
+ // image_height = CVPixelBufferGetHeight(pixelBuffer);
+
+ // printf("Pixel buffer %i - %i\n", image_width, image_height);
+
+ CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
+
+ // get our buffers
+ unsigned char *dataY = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0);
+ unsigned char *dataCbCr = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1);
+
+ if (dataY == NULL) {
+ print_line("Couldn't access Y pixel buffer data");
+ } else if (dataCbCr == NULL) {
+ print_line("Couldn't access CbCr pixel buffer data");
+ } else {
+ Ref<Image> img[2];
+ size_t extraLeft, extraRight, extraTop, extraBottom;
+
+ CVPixelBufferGetExtendedPixels(pixelBuffer, &extraLeft, &extraRight, &extraTop, &extraBottom);
+
+ {
+ // do Y
+ int new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0);
+ int new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0);
+ int bytes_per_row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0);
+
+ if ((image_width[0] != new_width) || (image_height[0] != new_height)) {
+ printf("- Camera padding l:%lu r:%lu t:%lu b:%lu\n", extraLeft, extraRight, extraTop, extraBottom);
+ printf("- Camera Y plane size: %i, %i - %i\n", new_width, new_height, bytes_per_row);
+
+ image_width[0] = new_width;
+ image_height[0] = new_height;
+ img_data[0].resize(new_width * new_height);
+ }
+
+ PoolVector<uint8_t>::Write w = img_data[0].write();
+ if (new_width == bytes_per_row) {
+ memcpy(w.ptr(), dataY, new_width * new_height);
+ } else {
+ int offset_a = 0;
+ int offset_b = extraLeft + (extraTop * bytes_per_row);
+ for (int r = 0; r < new_height; r++) {
+ memcpy(w.ptr() + offset_a, dataY + offset_b, new_width);
+ offset_a += new_width;
+ offset_b += bytes_per_row;
+ }
+ }
+
+ img[0].instance();
+ img[0]->create(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]);
+ }
+
+ {
+ // do CbCr
+ int new_width = CVPixelBufferGetWidthOfPlane(pixelBuffer, 1);
+ int new_height = CVPixelBufferGetHeightOfPlane(pixelBuffer, 1);
+ int bytes_per_row = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0);
+
+ if ((image_width[1] != new_width) || (image_height[1] != new_height)) {
+ printf("- Camera CbCr plane size: %i, %i - %i\n", new_width, new_height, bytes_per_row);
+
+ image_width[1] = new_width;
+ image_height[1] = new_height;
+ img_data[1].resize(2 * new_width * new_height);
+ }
+
+ PoolVector<uint8_t>::Write w = img_data[1].write();
+ if ((2 * new_width) == bytes_per_row) {
+ memcpy(w.ptr(), dataCbCr, 2 * new_width * new_height);
+ } else {
+ int offset_a = 0;
+ int offset_b = extraLeft + (extraTop * bytes_per_row);
+ for (int r = 0; r < new_height; r++) {
+ memcpy(w.ptr() + offset_a, dataCbCr + offset_b, 2 * new_width);
+ offset_a += 2 * new_width;
+ offset_b += bytes_per_row;
+ }
+ }
+
+ img[1].instance();
+ img[1]->create(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]);
+ }
+
+ // set our texture...
+ feed->set_YCbCr_imgs(img[0], img[1]);
+
+ // now build our transform to display this as a background image that matches our camera
+ CGAffineTransform affine_transform = [current_frame displayTransformForOrientation:orientation viewportSize:CGSizeMake(screen_size.width, screen_size.height)];
+
+ // we need to invert this, probably row v.s. column notation
+ affine_transform = CGAffineTransformInvert(affine_transform);
+
+ if (orientation != UIDeviceOrientationPortrait) {
+ affine_transform.b = -affine_transform.b;
+ affine_transform.d = -affine_transform.d;
+ affine_transform.ty = 1.0 - affine_transform.ty;
+ } else {
+ affine_transform.c = -affine_transform.c;
+ affine_transform.a = -affine_transform.a;
+ affine_transform.tx = 1.0 - affine_transform.tx;
+ }
+
+ Transform2D display_transform = Transform2D(
+ affine_transform.a, affine_transform.b,
+ affine_transform.c, affine_transform.d,
+ affine_transform.tx, affine_transform.ty);
+
+ feed->set_transform(display_transform);
+ }
+
+ // and unlock
+ CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
+ }
+
+ // Record light estimation to apply to our scene
+ if (light_estimation_is_enabled) {
+ ambient_intensity = current_frame.lightEstimate.ambientIntensity;
+
+ ///@TODO it's there, but not there.. what to do with this...
+ // https://developer.apple.com/documentation/arkit/arlightestimate?language=objc
+ // ambient_color_temperature = current_frame.lightEstimate.ambientColorTemperature;
+ }
+
+ // Process our camera
+ ARCamera *camera = current_frame.camera;
+
+ // strangely enough we have to states, rolling them up into one
+ if (camera.trackingState == ARTrackingStateNotAvailable) {
+ // no tracking, would be good if we black out the screen or something...
+ tracking_state = ARVRInterface::ARVR_NOT_TRACKING;
+ } else {
+ if (camera.trackingState == ARTrackingStateNormal) {
+ tracking_state = ARVRInterface::ARVR_NORMAL_TRACKING;
+ } else if (camera.trackingStateReason == ARTrackingStateReasonExcessiveMotion) {
+ tracking_state = ARVRInterface::ARVR_EXCESSIVE_MOTION;
+ } else if (camera.trackingStateReason == ARTrackingStateReasonInsufficientFeatures) {
+ tracking_state = ARVRInterface::ARVR_INSUFFICIENT_FEATURES;
+ } else {
+ tracking_state = ARVRInterface::ARVR_UNKNOWN_TRACKING;
+ }
+
+ // copy our current frame transform
+ matrix_float4x4 m44 = camera.transform;
+ if (orientation == UIDeviceOrientationLandscapeLeft) {
+ transform.basis.elements[0].x = m44.columns[0][0];
+ transform.basis.elements[1].x = m44.columns[0][1];
+ transform.basis.elements[2].x = m44.columns[0][2];
+ transform.basis.elements[0].y = m44.columns[1][0];
+ transform.basis.elements[1].y = m44.columns[1][1];
+ transform.basis.elements[2].y = m44.columns[1][2];
+ } else if (orientation == UIDeviceOrientationPortrait) {
+ transform.basis.elements[0].x = m44.columns[1][0];
+ transform.basis.elements[1].x = m44.columns[1][1];
+ transform.basis.elements[2].x = m44.columns[1][2];
+ transform.basis.elements[0].y = -m44.columns[0][0];
+ transform.basis.elements[1].y = -m44.columns[0][1];
+ transform.basis.elements[2].y = -m44.columns[0][2];
+ } else if (orientation == UIDeviceOrientationLandscapeRight) {
+ transform.basis.elements[0].x = -m44.columns[0][0];
+ transform.basis.elements[1].x = -m44.columns[0][1];
+ transform.basis.elements[2].x = -m44.columns[0][2];
+ transform.basis.elements[0].y = -m44.columns[1][0];
+ transform.basis.elements[1].y = -m44.columns[1][1];
+ transform.basis.elements[2].y = -m44.columns[1][2];
+ } else if (orientation == UIDeviceOrientationPortraitUpsideDown) {
+ // this may not be correct
+ transform.basis.elements[0].x = m44.columns[1][0];
+ transform.basis.elements[1].x = m44.columns[1][1];
+ transform.basis.elements[2].x = m44.columns[1][2];
+ transform.basis.elements[0].y = m44.columns[0][0];
+ transform.basis.elements[1].y = m44.columns[0][1];
+ transform.basis.elements[2].y = m44.columns[0][2];
+ }
+ transform.basis.elements[0].z = m44.columns[2][0];
+ transform.basis.elements[1].z = m44.columns[2][1];
+ transform.basis.elements[2].z = m44.columns[2][2];
+ transform.origin.x = m44.columns[3][0];
+ transform.origin.y = m44.columns[3][1];
+ transform.origin.z = m44.columns[3][2];
+
+ // copy our current frame projection, investigate using projectionMatrixWithViewportSize:orientation:zNear:zFar: so we can set our own near and far
+ m44 = [camera projectionMatrixForOrientation:orientation viewportSize:CGSizeMake(screen_size.width, screen_size.height) zNear:z_near zFar:z_far];
+ projection.matrix[0][0] = m44.columns[0][0];
+ projection.matrix[1][0] = m44.columns[1][0];
+ projection.matrix[2][0] = m44.columns[2][0];
+ projection.matrix[3][0] = m44.columns[3][0];
+ projection.matrix[0][1] = m44.columns[0][1];
+ projection.matrix[1][1] = m44.columns[1][1];
+ projection.matrix[2][1] = m44.columns[2][1];
+ projection.matrix[3][1] = m44.columns[3][1];
+ projection.matrix[0][2] = m44.columns[0][2];
+ projection.matrix[1][2] = m44.columns[1][2];
+ projection.matrix[2][2] = m44.columns[2][2];
+ projection.matrix[3][2] = m44.columns[3][2];
+ projection.matrix[0][3] = m44.columns[0][3];
+ projection.matrix[1][3] = m44.columns[1][3];
+ projection.matrix[2][3] = m44.columns[2][3];
+ projection.matrix[3][3] = m44.columns[3][3];
+ }
+ }
+ }
+ }
+}
+
+void ARKitInterface::_add_or_update_anchor(void *p_anchor) {
+ _THREAD_SAFE_METHOD_
+
+ ARAnchor *anchor = (ARAnchor *)p_anchor;
+
+ unsigned char uuid[16];
+ [anchor.identifier getUUIDBytes:uuid];
+
+ ARVRPositionalTracker *tracker = get_anchor_for_uuid(uuid);
+ if (tracker != NULL) {
+ // lets update our mesh! (using Arjens code as is for now)
+ // we should also probably limit how often we do this...
+
+ // can we safely cast this?
+ ARPlaneAnchor *planeAnchor = (ARPlaneAnchor *)anchor;
+
+ if (planeAnchor.geometry.triangleCount > 0) {
+ Ref<SurfaceTool> surftool;
+ surftool.instance();
+ surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
+
+ for (int j = planeAnchor.geometry.triangleCount * 3 - 1; j >= 0; j--) {
+ int16_t index = planeAnchor.geometry.triangleIndices[j];
+ simd_float3 vrtx = planeAnchor.geometry.vertices[index];
+ simd_float2 textcoord = planeAnchor.geometry.textureCoordinates[index];
+ surftool->add_uv(Vector2(textcoord[0], textcoord[1]));
+ surftool->add_color(Color(0.8, 0.8, 0.8));
+ surftool->add_vertex(Vector3(vrtx[0], vrtx[1], vrtx[2]));
+ }
+
+ surftool->generate_normals();
+ tracker->set_mesh(surftool->commit());
+ } else {
+ Ref<Mesh> nomesh;
+ tracker->set_mesh(nomesh);
+ }
+
+ // Note, this also contains a scale factor which gives us an idea of the size of the anchor
+ // We may extract that in our ARVRAnchor class
+ Basis b;
+ matrix_float4x4 m44 = anchor.transform;
+ b.elements[0].x = m44.columns[0][0];
+ b.elements[1].x = m44.columns[0][1];
+ b.elements[2].x = m44.columns[0][2];
+ b.elements[0].y = m44.columns[1][0];
+ b.elements[1].y = m44.columns[1][1];
+ b.elements[2].y = m44.columns[1][2];
+ b.elements[0].z = m44.columns[2][0];
+ b.elements[1].z = m44.columns[2][1];
+ b.elements[2].z = m44.columns[2][2];
+ tracker->set_orientation(b);
+ tracker->set_rw_position(Vector3(m44.columns[3][0], m44.columns[3][1], m44.columns[3][2]));
+ }
+}
+
+void ARKitInterface::_remove_anchor(void *p_anchor) {
+ _THREAD_SAFE_METHOD_
+
+ ARAnchor *anchor = (ARAnchor *)p_anchor;
+
+ unsigned char uuid[16];
+ [anchor.identifier getUUIDBytes:uuid];
+
+ remove_anchor_for_uuid(uuid);
+}
+
+ARKitInterface::ARKitInterface() {
+ initialized = false;
+ session_was_started = false;
+ plane_detection_is_enabled = false;
+ light_estimation_is_enabled = false;
+ ar_session = NULL;
+ z_near = 0.01;
+ z_far = 1000.0;
+ projection.set_perspective(60.0, 1.0, z_near, z_far, false);
+ anchors = NULL;
+ num_anchors = 0;
+ ambient_intensity = 1.0;
+ ambient_color_temperature = 1.0;
+ image_width[0] = 0;
+ image_width[1] = 0;
+ image_height[0] = 0;
+ image_height[1] = 0;
+}
+
+ARKitInterface::~ARKitInterface() {
+ remove_all_anchors();
+
+ // and make sure we cleanup if we haven't already
+ if (is_initialized()) {
+ uninitialize();
+ }
+}
diff --git a/modules/arkit/arkit_session_delegate.h b/modules/arkit/arkit_session_delegate.h
new file mode 100644
index 0000000000..afe093656b
--- /dev/null
+++ b/modules/arkit/arkit_session_delegate.h
@@ -0,0 +1,50 @@
+/*************************************************************************/
+/* arkit_session_delegate.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef ARKIT_SESSION_DELEGATE_H
+#define ARKIT_SESSION_DELEGATE_H
+
+#import <ARKit/ARKit.h>
+#import <UIKit/UIKit.h>
+
+class ARKitInterface;
+
+@interface ARKitSessionDelegate : NSObject <ARSessionDelegate> {
+ ARKitInterface *arkit_interface;
+}
+
+@property(nonatomic) ARKitInterface *arkit_interface;
+
+- (void)session:(ARSession *)session didAddAnchors:(NSArray<ARAnchor *> *)anchors;
+- (void)session:(ARSession *)session didRemoveAnchors:(NSArray<ARAnchor *> *)anchors;
+- (void)session:(ARSession *)session didUpdateAnchors:(NSArray<ARAnchor *> *)anchors;
+@end
+
+#endif /* !ARKIT_SESSION_DELEGATE_H */
diff --git a/modules/arkit/arkit_session_delegate.mm b/modules/arkit/arkit_session_delegate.mm
new file mode 100644
index 0000000000..56485c987c
--- /dev/null
+++ b/modules/arkit/arkit_session_delegate.mm
@@ -0,0 +1,56 @@
+/*************************************************************************/
+/* arkit_session_delegate.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "arkit_session_delegate.h"
+#include "arkit_interface.h"
+
+@implementation ARKitSessionDelegate
+
+@synthesize arkit_interface;
+
+- (void)session:(ARSession *)session didAddAnchors:(NSArray<ARAnchor *> *)anchors {
+ for (ARAnchor *anchor in anchors) {
+ arkit_interface->_add_or_update_anchor(anchor);
+ }
+}
+
+- (void)session:(ARSession *)session didRemoveAnchors:(NSArray<ARAnchor *> *)anchors {
+ for (ARAnchor *anchor in anchors) {
+ arkit_interface->_remove_anchor(anchor);
+ }
+}
+
+- (void)session:(ARSession *)session didUpdateAnchors:(NSArray<ARAnchor *> *)anchors {
+ for (ARAnchor *anchor in anchors) {
+ arkit_interface->_add_or_update_anchor(anchor);
+ }
+}
+
+@end \ No newline at end of file
diff --git a/modules/arkit/config.py b/modules/arkit/config.py
new file mode 100644
index 0000000000..96e41826c5
--- /dev/null
+++ b/modules/arkit/config.py
@@ -0,0 +1,5 @@
+def can_build(env, platform):
+ return platform == 'iphone'
+
+def configure(env):
+ pass
diff --git a/modules/mono/editor/monodevelop_instance.h b/modules/arkit/register_types.cpp
index 3b3af9607b..af35828004 100644
--- a/modules/mono/editor/monodevelop_instance.h
+++ b/modules/arkit/register_types.cpp
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* monodevelop_instance.h */
+/* register_types.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,29 +28,18 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef MONODEVELOP_INSTANCE_H
-#define MONODEVELOP_INSTANCE_H
+#include "register_types.h"
-#include "core/reference.h"
+#include "arkit_interface.h"
-#include "../mono_gc_handle.h"
-#include "../mono_gd/gd_mono_method.h"
+void register_arkit_types() {
+ // does it make sense to register the class?
-class MonoDevelopInstance {
+ Ref<ARKitInterface> arkit_interface;
+ arkit_interface.instance();
+ ARVRServer::get_singleton()->add_interface(arkit_interface);
+}
- Ref<MonoGCHandle> gc_handle;
- GDMonoMethod *execute_method;
-
-public:
- enum EditorId {
- MONODEVELOP = 0,
- VISUALSTUDIO_FOR_MAC = 1
- };
-
- void execute(const Vector<String> &p_files);
- void execute(const String &p_file);
-
- MonoDevelopInstance(const String &p_solution, EditorId p_editor_id);
-};
-
-#endif // MONODEVELOP_INSTANCE_H
+void unregister_arkit_types() {
+ // should clean itself up nicely :)
+}
diff --git a/modules/mono/editor/mono_build_info.cpp b/modules/arkit/register_types.h
index b386c06435..6ed2065de2 100644
--- a/modules/mono/editor/mono_build_info.cpp
+++ b/modules/arkit/register_types.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* mono_build_info.cpp */
+/* register_types.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,35 +28,5 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "mono_build_info.h"
-
-#include "../godotsharp_dirs.h"
-#include "../mono_gd/gd_mono_utils.h"
-
-uint32_t MonoBuildInfo::Hasher::hash(const MonoBuildInfo &p_key) {
-
- uint32_t hash = 0;
-
- GDMonoUtils::hash_combine(hash, p_key.solution.hash());
- GDMonoUtils::hash_combine(hash, p_key.configuration.hash());
-
- return hash;
-}
-
-bool MonoBuildInfo::operator==(const MonoBuildInfo &p_b) const {
-
- return p_b.solution == solution && p_b.configuration == configuration;
-}
-
-String MonoBuildInfo::get_log_dirpath() {
-
- return GodotSharpDirs::get_build_logs_dir().plus_file(solution.md5_text() + "_" + configuration);
-}
-
-MonoBuildInfo::MonoBuildInfo() {}
-
-MonoBuildInfo::MonoBuildInfo(const String &p_solution, const String &p_config) {
-
- solution = p_solution;
- configuration = p_config;
-}
+void register_arkit_types();
+void unregister_arkit_types();
diff --git a/modules/assimp/SCsub b/modules/assimp/SCsub
index 0da7e432e2..8a77e4f803 100644
--- a/modules/assimp/SCsub
+++ b/modules/assimp/SCsub
@@ -17,60 +17,60 @@ env_assimp.Prepend(CPPPATH=['#thirdparty/zlib/'])
env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/contrib/openddlparser/include'])
env_assimp.Prepend(CPPPATH=['#thirdparty/assimp/contrib/rapidjson/include'])
env_assimp.Prepend(CPPPATH=['.'])
-#env_assimp.Append(CPPFLAGS=['-DASSIMP_DOUBLE_PRECISION']) # TODO default to what godot is compiled with for future double support
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_BOOST_WORKAROUND'])
-env_assimp.Append(CPPFLAGS=['-DOPENDDLPARSER_BUILD'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_OWN_ZLIB'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_EXPORT'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_X_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_AMF_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_3DS_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MD3_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MD5_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MDL_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MD2_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_PLY_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_ASE_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_OBJ_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_HMP_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_SMD_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MDC_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MD5_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_STL_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_LWO_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_DXF_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_NFF_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_RAW_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_SIB_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_OFF_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_AC_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_BVH_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_IRRMESH_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_IRR_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_Q3D_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_B3D_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_COLLADA_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_TERRAGEN_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_CSM_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_3D_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_LWS_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_OGRE_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_OPENGEX_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_MS3D_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_COB_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_BLEND_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_Q3BSP_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_NDO_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_STEP_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_IFC_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_XGL_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_ASSBIN_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_GLTF_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_C4D_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_3MF_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_NO_X3D_IMPORTER'])
+#env_assimp.Append(CPPDEFINES=['ASSIMP_DOUBLE_PRECISION']) # TODO default to what godot is compiled with for future double support
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_BOOST_WORKAROUND'])
+env_assimp.Append(CPPDEFINES=['OPENDDLPARSER_BUILD'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_OWN_ZLIB'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_EXPORT'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_X_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_AMF_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_3DS_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MD3_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MD5_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MDL_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MD2_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_PLY_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_ASE_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_OBJ_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_HMP_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_SMD_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MDC_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MD5_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_STL_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_LWO_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_DXF_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_NFF_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_RAW_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_SIB_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_OFF_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_AC_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_BVH_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_IRRMESH_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_IRR_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_Q3D_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_B3D_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_COLLADA_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_TERRAGEN_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_CSM_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_3D_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_LWS_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_OGRE_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_OPENGEX_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_MS3D_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_COB_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_BLEND_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_Q3BSP_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_NDO_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_STEP_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_IFC_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_XGL_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_ASSBIN_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_GLTF_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_C4D_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_3MF_IMPORTER'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_NO_X3D_IMPORTER'])
-env_assimp.Append(CPPFLAGS=['-DASSIMP_BUILD_SINGLETHREADED'])
+env_assimp.Append(CPPDEFINES=['ASSIMP_BUILD_SINGLETHREADED'])
if (not env.msvc):
env_assimp.Append(CXXFLAGS=['-std=c++11'])
@@ -78,14 +78,14 @@ elif (env.msvc == False and env['platform'] == 'windows'):
env_assimp.Append(LDFLAGS=['-pthread'])
if(env['platform'] == 'windows'):
- env_assimp.Append(CPPFLAGS=['-DPLATFORM_WINDOWS'])
- env_assimp.Append(CPPFLAGS=['-DPLATFORM=WINDOWS'])
+ env_assimp.Append(CPPDEFINES=['PLATFORM_WINDOWS'])
+ env_assimp.Append(CPPDEFINES=[('PLATFORM', 'WINDOWS')])
elif(env['platform'] == 'x11'):
- env_assimp.Append(CPPFLAGS=['-DPLATFORM_LINUX'])
- env_assimp.Append(CPPFLAGS=['-DPLATFORM=LINUX'])
+ env_assimp.Append(CPPDEFINES=['PLATFORM_LINUX'])
+ env_assimp.Append(CPPDEFINES=[('PLATFORM', 'LINUX')])
elif(env['platform'] == 'osx'):
- env_assimp.Append(CPPFLAGS=['-DPLATFORM_DARWIN'])
- env_assimp.Append(CPPFLAGS=['-DPLATFORM=DARWIN'])
+ env_assimp.Append(CPPDEFINES=['PLATFORM_DARWIN'])
+ env_assimp.Append(CPPDEFINES=[('PLATFORM', 'DARWIN')])
env_thirdparty = env_assimp.Clone()
env_thirdparty.disable_warnings()
diff --git a/modules/assimp/editor_scene_importer_assimp.cpp b/modules/assimp/editor_scene_importer_assimp.cpp
index 8c3c04674b..f23c66dbcf 100644
--- a/modules/assimp/editor_scene_importer_assimp.cpp
+++ b/modules/assimp/editor_scene_importer_assimp.cpp
@@ -848,13 +848,13 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
if (AI_SUCCESS == ai_material->GetTexture(tex_normal, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) {
filename = _assimp_raw_string_to_string(ai_filename);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
Ref<Texture> texture = _load_texture(state, path);
- if (texture != NULL) {
+ if (texture.is_valid()) {
_set_texture_mapping_mode(map_mode, texture);
mat->set_feature(SpatialMaterial::Feature::FEATURE_NORMAL_MAPPING, true);
mat->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
@@ -869,7 +869,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_NORMAL_TEXTURE, ai_filename)) {
filename = _assimp_raw_string_to_string(ai_filename);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -892,7 +892,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
if (AI_SUCCESS == ai_material->GetTexture(tex_emissive, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) {
filename = _assimp_raw_string_to_string(ai_filename);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -914,7 +914,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiTextureMapMode map_mode[2];
if (AI_SUCCESS == ai_material->GetTexture(tex_albedo, 0, &ai_filename, NULL, NULL, NULL, NULL, map_mode)) {
filename = _assimp_raw_string_to_string(ai_filename);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -944,7 +944,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiTextureMapMode map_mode[2];
if (AI_SUCCESS == ai_material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE, &tex_gltf_base_color_path, NULL, NULL, NULL, NULL, map_mode)) {
String filename = _assimp_raw_string_to_string(tex_gltf_base_color_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -973,7 +973,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiString tex_fbx_pbs_base_color_path = aiString();
if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_BASE_COLOR_TEXTURE, tex_fbx_pbs_base_color_path)) {
String filename = _assimp_raw_string_to_string(tex_fbx_pbs_base_color_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -1005,7 +1005,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiString tex_fbx_pbs_normal_path = aiString();
if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_NORMAL_TEXTURE, tex_fbx_pbs_normal_path)) {
String filename = _assimp_raw_string_to_string(tex_fbx_pbs_normal_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -1027,7 +1027,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiString tex_fbx_stingray_normal_path = aiString();
if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_NORMAL_TEXTURE, tex_fbx_stingray_normal_path)) {
String filename = _assimp_raw_string_to_string(tex_fbx_stingray_normal_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -1045,7 +1045,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiString tex_fbx_pbs_base_color_path = aiString();
if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_COLOR_TEXTURE, tex_fbx_pbs_base_color_path)) {
String filename = _assimp_raw_string_to_string(tex_fbx_pbs_base_color_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -1077,7 +1077,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiString tex_fbx_pbs_emissive_path = aiString();
if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_EMISSIVE_TEXTURE, tex_fbx_pbs_emissive_path)) {
String filename = _assimp_raw_string_to_string(tex_fbx_pbs_emissive_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -1107,7 +1107,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiString tex_gltf_pbr_metallicroughness_path;
if (AI_SUCCESS == ai_material->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, &tex_gltf_pbr_metallicroughness_path)) {
String filename = _assimp_raw_string_to_string(tex_gltf_pbr_metallicroughness_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -1134,7 +1134,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiString tex_fbx_pbs_metallic_path;
if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_METALLIC_TEXTURE, tex_fbx_pbs_metallic_path)) {
String filename = _assimp_raw_string_to_string(tex_fbx_pbs_metallic_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -1154,7 +1154,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiString tex_fbx_pbs_rough_path;
if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_STINGRAY_ROUGHNESS_TEXTURE, tex_fbx_pbs_rough_path)) {
String filename = _assimp_raw_string_to_string(tex_fbx_pbs_rough_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -1177,7 +1177,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiString tex_fbx_pbs_metallic_path;
if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_METALNESS_TEXTURE, tex_fbx_pbs_metallic_path)) {
String filename = _assimp_raw_string_to_string(tex_fbx_pbs_metallic_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -1197,7 +1197,7 @@ Ref<Material> EditorSceneImporterAssimp::_generate_material_from_index(ImportSta
aiString tex_fbx_pbs_rough_path;
if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_DIFFUSE_ROUGHNESS_TEXTURE, tex_fbx_pbs_rough_path)) {
String filename = _assimp_raw_string_to_string(tex_fbx_pbs_rough_path);
- String path = state.path.get_base_dir() + "/" + filename.replace("\\", "/");
+ String path = state.path.get_base_dir().plus_file(filename.replace("\\", "/"));
bool found = false;
_find_texture_path(state.path, path, found);
if (found) {
@@ -1684,7 +1684,7 @@ void EditorSceneImporterAssimp::_find_texture_path(const String &p_path, _Direct
path = name;
return;
}
- String name_ignore_sub_directory = p_path.get_base_dir() + "/" + path.get_file().get_basename() + extension;
+ String name_ignore_sub_directory = p_path.get_base_dir().plus_file(path.get_file().get_basename()) + extension;
if (dir.file_exists(name_ignore_sub_directory)) {
found = true;
path = name_ignore_sub_directory;
diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp
index bcc992db24..88732dff33 100644
--- a/modules/bmp/image_loader_bmp.cpp
+++ b/modules/bmp/image_loader_bmp.cpp
@@ -47,9 +47,6 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image,
size_t height = (size_t)p_header.bmp_info_header.bmp_height;
size_t bits_per_pixel = (size_t)p_header.bmp_info_header.bmp_bit_count;
- if (p_header.bmp_info_header.bmp_compression != BI_RGB) {
- err = FAILED;
- }
// Check whether we can load it
if (bits_per_pixel == 1) {
@@ -238,11 +235,16 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f,
bmp_header.bmp_info_header.bmp_colors_used = f->get_32();
bmp_header.bmp_info_header.bmp_important_colors = f->get_32();
- // Compressed bitmaps not supported, stop parsing
- if (bmp_header.bmp_info_header.bmp_compression != BI_RGB) {
- ERR_EXPLAIN("Unsupported bmp file: " + f->get_path());
- f->close();
- ERR_FAIL_V(ERR_UNAVAILABLE);
+ switch (bmp_header.bmp_info_header.bmp_compression) {
+ case BI_RLE8:
+ case BI_RLE4:
+ case BI_CMYKRLE8:
+ case BI_CMYKRLE4: {
+ // Stop parsing
+ ERR_EXPLAIN("Compressed BMP files are not supported: " + f->get_path());
+ f->close();
+ ERR_FAIL_V(ERR_UNAVAILABLE);
+ } break;
}
// Don't rely on sizeof(bmp_file_header) as structure padding
// adds 2 bytes offset leading to misaligned color table reading
@@ -257,16 +259,14 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f,
if (bmp_header.bmp_info_header.bmp_bit_count <= 8) {
// Support 256 colors max
color_table_size = 1 << bmp_header.bmp_info_header.bmp_bit_count;
+ ERR_FAIL_COND_V(color_table_size == 0, ERR_BUG);
}
- ERR_FAIL_COND_V(color_table_size == 0, ERR_BUG);
PoolVector<uint8_t> bmp_color_table;
- if (color_table_size > 0) {
- // Color table is usually 4 bytes per color -> [B][G][R][0]
- err = bmp_color_table.resize(color_table_size * 4);
- PoolVector<uint8_t>::Write bmp_color_table_w = bmp_color_table.write();
- f->get_buffer(bmp_color_table_w.ptr(), color_table_size * 4);
- }
+ // Color table is usually 4 bytes per color -> [B][G][R][0]
+ bmp_color_table.resize(color_table_size * 4);
+ PoolVector<uint8_t>::Write bmp_color_table_w = bmp_color_table.write();
+ f->get_buffer(bmp_color_table_w.ptr(), color_table_size * 4);
f->seek(bmp_header.bmp_file_header.bmp_file_offset);
diff --git a/modules/bmp/image_loader_bmp.h b/modules/bmp/image_loader_bmp.h
index 0082cf778a..2debb19a1c 100644
--- a/modules/bmp/image_loader_bmp.h
+++ b/modules/bmp/image_loader_bmp.h
@@ -42,15 +42,15 @@ protected:
enum bmp_compression_s {
BI_RGB = 0x00,
- BI_RLE8 = 0x01,
- BI_RLE4 = 0x02,
+ BI_RLE8 = 0x01, // compressed
+ BI_RLE4 = 0x02, // compressed
BI_BITFIELDS = 0x03,
BI_JPEG = 0x04,
BI_PNG = 0x05,
BI_ALPHABITFIELDS = 0x06,
BI_CMYK = 0x0b,
- BI_CMYKRLE8 = 0x0c,
- BI_CMYKRLE4 = 0x0d
+ BI_CMYKRLE8 = 0x0c, // compressed
+ BI_CMYKRLE4 = 0x0d // compressed
};
struct bmp_header_s {
diff --git a/modules/bullet/SCsub b/modules/bullet/SCsub
index 16d694c238..ecc8a9b481 100644
--- a/modules/bullet/SCsub
+++ b/modules/bullet/SCsub
@@ -186,9 +186,13 @@ if env['builtin_bullet']:
thirdparty_sources = [thirdparty_dir + file for file in bullet2_src]
- env_bullet.Prepend(CPPPATH=[thirdparty_dir])
+ # Treat Bullet headers as system headers to avoid raising warnings. Not supported on MSVC.
+ if not env.msvc:
+ env_bullet.Append(CPPFLAGS=['-isystem', Dir(thirdparty_dir).path])
+ else:
+ env_bullet.Prepend(CPPPATH=[thirdparty_dir])
# if env['target'] == "debug" or env['target'] == "release_debug":
- # env_bullet.Append(CPPFLAGS=['-DBT_DEBUG'])
+ # env_bullet.Append(CPPDEFINES=['BT_DEBUG'])
env_thirdparty = env_bullet.Clone()
env_thirdparty.disable_warnings()
diff --git a/modules/bullet/bullet_physics_server.cpp b/modules/bullet/bullet_physics_server.cpp
index be4e0b88e8..038001996d 100644
--- a/modules/bullet/bullet_physics_server.cpp
+++ b/modules/bullet/bullet_physics_server.cpp
@@ -267,7 +267,7 @@ RID BulletPhysicsServer::area_get_space(RID p_area) const {
void BulletPhysicsServer::area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) {
AreaBullet *area = area_owner.get(p_area);
- ERR_FAIL_COND(!area)
+ ERR_FAIL_COND(!area);
area->set_spOv_mode(p_mode);
}
diff --git a/modules/bullet/bullet_physics_server.h b/modules/bullet/bullet_physics_server.h
index 0b8ad53658..4c598c84f2 100644
--- a/modules/bullet/bullet_physics_server.h
+++ b/modules/bullet/bullet_physics_server.h
@@ -45,7 +45,7 @@
*/
class BulletPhysicsServer : public PhysicsServer {
- GDCLASS(BulletPhysicsServer, PhysicsServer)
+ GDCLASS(BulletPhysicsServer, PhysicsServer);
friend class BulletPhysicsDirectSpaceState;
diff --git a/modules/bullet/collision_object_bullet.cpp b/modules/bullet/collision_object_bullet.cpp
index 166d7e6158..e1800fd3eb 100644
--- a/modules/bullet/collision_object_bullet.cpp
+++ b/modules/bullet/collision_object_bullet.cpp
@@ -305,7 +305,7 @@ void RigidCollisionObjectBullet::set_shape_transform(int p_index, const Transfor
ERR_FAIL_INDEX(p_index, get_shape_count());
shapes.write[p_index].set_transform(p_transform);
- reload_shapes();
+ shape_changed(p_index);
}
const btTransform &RigidCollisionObjectBullet::get_bt_shape_transform(int p_index) const {
diff --git a/modules/bullet/cone_twist_joint_bullet.cpp b/modules/bullet/cone_twist_joint_bullet.cpp
index d9a82d6179..bc7fd52cf6 100644
--- a/modules/bullet/cone_twist_joint_bullet.cpp
+++ b/modules/bullet/cone_twist_joint_bullet.cpp
@@ -84,7 +84,7 @@ void ConeTwistJointBullet::set_param(PhysicsServer::ConeTwistJointParam p_param,
break;
default:
ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated");
- WARN_DEPRECATED
+ WARN_DEPRECATED;
break;
}
}
diff --git a/modules/bullet/generic_6dof_joint_bullet.cpp b/modules/bullet/generic_6dof_joint_bullet.cpp
index 8fed933854..0d2c46c579 100644
--- a/modules/bullet/generic_6dof_joint_bullet.cpp
+++ b/modules/bullet/generic_6dof_joint_bullet.cpp
@@ -175,7 +175,7 @@ void Generic6DOFJointBullet::set_param(Vector3::Axis p_axis, PhysicsServer::G6DO
break;
default:
ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated");
- WARN_DEPRECATED
+ WARN_DEPRECATED;
break;
}
}
@@ -256,7 +256,7 @@ void Generic6DOFJointBullet::set_flag(Vector3::Axis p_axis, PhysicsServer::G6DOF
break;
default:
ERR_EXPLAIN("This flag " + itos(p_flag) + " is deprecated");
- WARN_DEPRECATED
+ WARN_DEPRECATED;
break;
}
}
diff --git a/modules/bullet/hinge_joint_bullet.cpp b/modules/bullet/hinge_joint_bullet.cpp
index 7b99d3d89f..b7e1e1a4c2 100644
--- a/modules/bullet/hinge_joint_bullet.cpp
+++ b/modules/bullet/hinge_joint_bullet.cpp
@@ -118,7 +118,7 @@ void HingeJointBullet::set_param(PhysicsServer::HingeJointParam p_param, real_t
break;
default:
ERR_EXPLAIN("The HingeJoint parameter " + itos(p_param) + " is deprecated.");
- WARN_DEPRECATED
+ WARN_DEPRECATED;
break;
}
}
diff --git a/modules/bullet/pin_joint_bullet.cpp b/modules/bullet/pin_joint_bullet.cpp
index 58b090006a..c9c4d1af7e 100644
--- a/modules/bullet/pin_joint_bullet.cpp
+++ b/modules/bullet/pin_joint_bullet.cpp
@@ -86,7 +86,7 @@ real_t PinJointBullet::get_param(PhysicsServer::PinJointParam p_param) const {
return p2pConstraint->m_setting.m_impulseClamp;
default:
ERR_EXPLAIN("This parameter " + itos(p_param) + " is deprecated");
- WARN_DEPRECATED
+ WARN_DEPRECATED;
return 0;
}
}
diff --git a/modules/bullet/rigid_body_bullet.cpp b/modules/bullet/rigid_body_bullet.cpp
index 733a900396..8d21b25b20 100644
--- a/modules/bullet/rigid_body_bullet.cpp
+++ b/modules/bullet/rigid_body_bullet.cpp
@@ -728,12 +728,12 @@ bool RigidBodyBullet::is_axis_locked(PhysicsServer::BodyAxis p_axis) const {
void RigidBodyBullet::reload_axis_lock() {
- btBody->setLinearFactor(btVector3(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_X), !is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Y), !is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Z)));
+ btBody->setLinearFactor(btVector3(float(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_X)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Y)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_LINEAR_Z))));
if (PhysicsServer::BODY_MODE_CHARACTER == mode) {
/// When character angular is always locked
btBody->setAngularFactor(btVector3(0., 0., 0.));
} else {
- btBody->setAngularFactor(btVector3(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_X), !is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Y), !is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Z)));
+ btBody->setAngularFactor(btVector3(float(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_X)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Y)), float(!is_axis_locked(PhysicsServer::BODY_AXIS_ANGULAR_Z))));
}
}
@@ -866,7 +866,7 @@ void RigidBodyBullet::on_enter_area(AreaBullet *p_area) {
if (p_area->is_spOv_gravityPoint()) {
++countGravityPointSpaces;
- assert(0 < countGravityPointSpaces);
+ ERR_FAIL_COND(countGravityPointSpaces <= 0);
}
}
@@ -888,7 +888,7 @@ void RigidBodyBullet::on_exit_area(AreaBullet *p_area) {
if (wasTheAreaFound) {
if (p_area->is_spOv_gravityPoint()) {
--countGravityPointSpaces;
- assert(0 <= countGravityPointSpaces);
+ ERR_FAIL_COND(countGravityPointSpaces < 0);
}
--areaWhereIamCount;
diff --git a/modules/bullet/rigid_body_bullet.h b/modules/bullet/rigid_body_bullet.h
index 1e1bea846a..2c9bdb8b0b 100644
--- a/modules/bullet/rigid_body_bullet.h
+++ b/modules/bullet/rigid_body_bullet.h
@@ -54,7 +54,7 @@ class BulletPhysicsDirectBodyState;
/// created by BulletPhysicsServer and is held by the "singleton" variable of this class
/// Each time something require it, the body must be set again.
class BulletPhysicsDirectBodyState : public PhysicsDirectBodyState {
- GDCLASS(BulletPhysicsDirectBodyState, PhysicsDirectBodyState)
+ GDCLASS(BulletPhysicsDirectBodyState, PhysicsDirectBodyState);
static BulletPhysicsDirectBodyState *singleton;
diff --git a/modules/bullet/space_bullet.h b/modules/bullet/space_bullet.h
index 6b3d65edf6..eb4a065e54 100644
--- a/modules/bullet/space_bullet.h
+++ b/modules/bullet/space_bullet.h
@@ -68,7 +68,8 @@ class btGjkEpaPenetrationDepthSolver;
extern ContactAddedCallback gContactAddedCallback;
class BulletPhysicsDirectSpaceState : public PhysicsDirectSpaceState {
- GDCLASS(BulletPhysicsDirectSpaceState, PhysicsDirectSpaceState)
+ GDCLASS(BulletPhysicsDirectSpaceState, PhysicsDirectSpaceState);
+
private:
SpaceBullet *space;
diff --git a/modules/csg/csg.cpp b/modules/csg/csg.cpp
index 3a61afa023..fd0d36eddf 100644
--- a/modules/csg/csg.cpp
+++ b/modules/csg/csg.cpp
@@ -45,7 +45,7 @@ void CSGBrush::build_from_faces(const PoolVector<Vector3> &p_vertices, const Poo
int vc = p_vertices.size();
- ERR_FAIL_COND((vc % 3) != 0)
+ ERR_FAIL_COND((vc % 3) != 0);
PoolVector<Vector3>::Read rv = p_vertices.read();
int uvc = p_uvs.size();
@@ -1018,15 +1018,15 @@ int CSGBrushOperation::MeshMerge::_create_bvh(BVH *p_bvh, BVH **p_bb, int p_from
max_depth = p_depth;
}
- if (p_size <= BVH_LIMIT) {
+ if (p_size == 0) {
+
+ return -1;
+ } else if (p_size <= BVH_LIMIT) {
for (int i = 0; i < p_size - 1; i++) {
p_bb[p_from + i]->next = p_bb[p_from + i + 1] - p_bvh;
}
return p_bb[p_from] - p_bvh;
- } else if (p_size == 0) {
-
- return -1;
}
AABB aabb;
diff --git a/modules/csg/csg_gizmos.cpp b/modules/csg/csg_gizmos.cpp
index d4069b901f..e6bfa5525d 100644
--- a/modules/csg/csg_gizmos.cpp
+++ b/modules/csg/csg_gizmos.cpp
@@ -34,8 +34,18 @@
CSGShapeSpatialGizmoPlugin::CSGShapeSpatialGizmoPlugin() {
- Color gizmo_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/csg", Color(0.2, 0.5, 1, 0.1));
- create_material("shape_material", gizmo_color);
+ Color gizmo_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/csg", Color(0.0, 0.4, 1, 0.15));
+ create_material("shape_union_material", gizmo_color);
+ create_material("shape_union_solid_material", gizmo_color);
+ gizmo_color.invert();
+ create_material("shape_subtraction_material", gizmo_color);
+ create_material("shape_subtraction_solid_material", gizmo_color);
+ gizmo_color.r = 0.95;
+ gizmo_color.g = 0.95;
+ gizmo_color.b = 0.95;
+ create_material("shape_intersection_material", gizmo_color);
+ create_material("shape_intersection_solid_material", gizmo_color);
+
create_handle_material("handles");
}
@@ -120,6 +130,10 @@ void CSGShapeSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_i
Vector3 ra, rb;
Geometry::get_closest_points_between_segments(Vector3(), Vector3(4096, 0, 0), sg[0], sg[1], ra, rb);
float d = ra.x;
+ if (SpatialEditor::get_singleton()->is_snap_enabled()) {
+ d = Math::stepify(d, SpatialEditor::get_singleton()->get_translate_snap());
+ }
+
if (d < 0.001)
d = 0.001;
@@ -135,6 +149,10 @@ void CSGShapeSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_i
Vector3 ra, rb;
Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
float d = ra[p_idx];
+ if (SpatialEditor::get_singleton()->is_snap_enabled()) {
+ d = Math::stepify(d, SpatialEditor::get_singleton()->get_translate_snap());
+ }
+
if (d < 0.001)
d = 0.001;
@@ -154,6 +172,9 @@ void CSGShapeSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_i
Vector3 ra, rb;
Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
float d = axis.dot(ra);
+ if (SpatialEditor::get_singleton()->is_snap_enabled()) {
+ d = Math::stepify(d, SpatialEditor::get_singleton()->get_translate_snap());
+ }
if (d < 0.001)
d = 0.001;
@@ -173,6 +194,9 @@ void CSGShapeSpatialGizmoPlugin::set_handle(EditorSpatialGizmo *p_gizmo, int p_i
Vector3 ra, rb;
Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
float d = axis.dot(ra);
+ if (SpatialEditor::get_singleton()->is_snap_enabled()) {
+ d = Math::stepify(d, SpatialEditor::get_singleton()->get_translate_snap());
+ }
if (d < 0.001)
d = 0.001;
@@ -297,7 +321,19 @@ void CSGShapeSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
p_gizmo->clear();
- Ref<Material> material = get_material("shape_material", p_gizmo);
+ Ref<Material> material;
+ switch (cs->get_operation()) {
+ case CSGShape::OPERATION_UNION:
+ material = get_material("shape_union_material", p_gizmo);
+ break;
+ case CSGShape::OPERATION_INTERSECTION:
+ material = get_material("shape_intersection_material", p_gizmo);
+ break;
+ case CSGShape::OPERATION_SUBTRACTION:
+ material = get_material("shape_subtraction_material", p_gizmo);
+ break;
+ }
+
Ref<Material> handles_material = get_material("handles");
PoolVector<Vector3> faces = cs->get_brush_faces();
@@ -320,6 +356,30 @@ void CSGShapeSpatialGizmoPlugin::redraw(EditorSpatialGizmo *p_gizmo) {
p_gizmo->add_lines(lines, material);
p_gizmo->add_collision_segments(lines);
+ if (p_gizmo->is_selected()) {
+ // Draw a translucent representation of the CSG node
+ Ref<ArrayMesh> mesh = memnew(ArrayMesh);
+ Array array;
+ array.resize(Mesh::ARRAY_MAX);
+ array[Mesh::ARRAY_VERTEX] = faces;
+ mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, array);
+
+ Ref<Material> solid_material;
+ switch (cs->get_operation()) {
+ case CSGShape::OPERATION_UNION:
+ solid_material = get_material("shape_union_solid_material", p_gizmo);
+ break;
+ case CSGShape::OPERATION_INTERSECTION:
+ solid_material = get_material("shape_intersection_solid_material", p_gizmo);
+ break;
+ case CSGShape::OPERATION_SUBTRACTION:
+ solid_material = get_material("shape_subtraction_solid_material", p_gizmo);
+ break;
+ }
+
+ p_gizmo->add_mesh(mesh, false, RID(), solid_material);
+ }
+
if (Object::cast_to<CSGSphere>(cs)) {
CSGSphere *s = Object::cast_to<CSGSphere>(cs);
diff --git a/modules/csg/csg_gizmos.h b/modules/csg/csg_gizmos.h
index 0915d05111..d38dafc936 100644
--- a/modules/csg/csg_gizmos.h
+++ b/modules/csg/csg_gizmos.h
@@ -55,7 +55,8 @@ public:
};
class EditorPluginCSG : public EditorPlugin {
- GDCLASS(EditorPluginCSG, EditorPlugin)
+ GDCLASS(EditorPluginCSG, EditorPlugin);
+
public:
EditorPluginCSG(EditorNode *p_editor);
};
diff --git a/modules/csg/csg_shape.cpp b/modules/csg/csg_shape.cpp
index 1d27b9b6f4..23725c4960 100644
--- a/modules/csg/csg_shape.cpp
+++ b/modules/csg/csg_shape.cpp
@@ -436,10 +436,10 @@ void CSGShape::_update_shape() {
}
// unset write access
- surfaces.write[i].verticesw = PoolVector<Vector3>::Write();
- surfaces.write[i].normalsw = PoolVector<Vector3>::Write();
- surfaces.write[i].uvsw = PoolVector<Vector2>::Write();
- surfaces.write[i].tansw = PoolVector<float>::Write();
+ surfaces.write[i].verticesw.release();
+ surfaces.write[i].normalsw.release();
+ surfaces.write[i].uvsw.release();
+ surfaces.write[i].tansw.release();
if (surfaces[i].last_added == 0)
continue;
@@ -557,6 +557,7 @@ void CSGShape::set_operation(Operation p_operation) {
operation = p_operation;
_make_dirty();
+ update_gizmo();
}
CSGShape::Operation CSGShape::get_operation() const {
@@ -1816,11 +1817,9 @@ CSGBrush *CSGPolygon::_build_brush() {
path_cache = path;
- if (path_cache) {
- path_cache->connect("tree_exited", this, "_path_exited");
- path_cache->connect("curve_changed", this, "_path_changed");
- path_cache = NULL;
- }
+ path_cache->connect("tree_exited", this, "_path_exited");
+ path_cache->connect("curve_changed", this, "_path_changed");
+ path_cache = NULL;
}
curve = path->get_curve();
if (curve.is_null())
diff --git a/modules/csg/csg_shape.h b/modules/csg/csg_shape.h
index a5b2238e6b..6c9419b3c2 100644
--- a/modules/csg/csg_shape.h
+++ b/modules/csg/csg_shape.h
@@ -116,9 +116,9 @@ protected:
virtual void _validate_property(PropertyInfo &property) const;
+public:
Array get_meshes() const;
-public:
void set_operation(Operation p_operation);
Operation get_operation() const;
@@ -156,7 +156,8 @@ public:
VARIANT_ENUM_CAST(CSGShape::Operation)
class CSGCombiner : public CSGShape {
- GDCLASS(CSGCombiner, CSGShape)
+ GDCLASS(CSGCombiner, CSGShape);
+
private:
virtual CSGBrush *_build_brush();
@@ -165,7 +166,7 @@ public:
};
class CSGPrimitive : public CSGShape {
- GDCLASS(CSGPrimitive, CSGShape)
+ GDCLASS(CSGPrimitive, CSGShape);
private:
bool invert_faces;
@@ -182,7 +183,7 @@ public:
};
class CSGMesh : public CSGPrimitive {
- GDCLASS(CSGMesh, CSGPrimitive)
+ GDCLASS(CSGMesh, CSGPrimitive);
virtual CSGBrush *_build_brush();
@@ -204,7 +205,7 @@ public:
class CSGSphere : public CSGPrimitive {
- GDCLASS(CSGSphere, CSGPrimitive)
+ GDCLASS(CSGSphere, CSGPrimitive);
virtual CSGBrush *_build_brush();
Ref<Material> material;
@@ -237,7 +238,7 @@ public:
class CSGBox : public CSGPrimitive {
- GDCLASS(CSGBox, CSGPrimitive)
+ GDCLASS(CSGBox, CSGPrimitive);
virtual CSGBrush *_build_brush();
Ref<Material> material;
@@ -266,7 +267,7 @@ public:
class CSGCylinder : public CSGPrimitive {
- GDCLASS(CSGCylinder, CSGPrimitive)
+ GDCLASS(CSGCylinder, CSGPrimitive);
virtual CSGBrush *_build_brush();
Ref<Material> material;
@@ -303,7 +304,7 @@ public:
class CSGTorus : public CSGPrimitive {
- GDCLASS(CSGTorus, CSGPrimitive)
+ GDCLASS(CSGTorus, CSGPrimitive);
virtual CSGBrush *_build_brush();
Ref<Material> material;
@@ -340,7 +341,7 @@ public:
class CSGPolygon : public CSGPrimitive {
- GDCLASS(CSGPolygon, CSGPrimitive)
+ GDCLASS(CSGPolygon, CSGPrimitive);
public:
enum Mode {
@@ -403,7 +404,7 @@ public:
void set_spin_degrees(float p_spin_degrees);
float get_spin_degrees() const;
- void set_spin_sides(int p_sides);
+ void set_spin_sides(int p_spin_sides);
int get_spin_sides() const;
void set_path_node(const NodePath &p_path);
diff --git a/modules/csg/doc_classes/CSGBox.xml b/modules/csg/doc_classes/CSGBox.xml
index e508468415..14f5a1952e 100644
--- a/modules/csg/doc_classes/CSGBox.xml
+++ b/modules/csg/doc_classes/CSGBox.xml
@@ -11,16 +11,16 @@
<methods>
</methods>
<members>
- <member name="depth" type="float" setter="set_depth" getter="get_depth">
+ <member name="depth" type="float" setter="set_depth" getter="get_depth" default="2.0">
Depth of the box measured from the center of the box.
</member>
- <member name="height" type="float" setter="set_height" getter="get_height">
+ <member name="height" type="float" setter="set_height" getter="get_height" default="2.0">
Height of the box measured from the center of the box.
</member>
<member name="material" type="Material" setter="set_material" getter="get_material">
The material used to render the box.
</member>
- <member name="width" type="float" setter="set_width" getter="get_width">
+ <member name="width" type="float" setter="set_width" getter="get_width" default="2.0">
Width of the box measured from the center of the box.
</member>
</members>
diff --git a/modules/csg/doc_classes/CSGCylinder.xml b/modules/csg/doc_classes/CSGCylinder.xml
index 24c3f8ba2e..9fc0281887 100644
--- a/modules/csg/doc_classes/CSGCylinder.xml
+++ b/modules/csg/doc_classes/CSGCylinder.xml
@@ -11,22 +11,22 @@
<methods>
</methods>
<members>
- <member name="cone" type="bool" setter="set_cone" getter="is_cone">
+ <member name="cone" type="bool" setter="set_cone" getter="is_cone" default="false">
If [code]true[/code] a cone is created, the [member radius] will only apply to one side.
</member>
- <member name="height" type="float" setter="set_height" getter="get_height">
+ <member name="height" type="float" setter="set_height" getter="get_height" default="1.0">
The height of the cylinder.
</member>
<member name="material" type="Material" setter="set_material" getter="get_material">
The material used to render the cylinder.
</member>
- <member name="radius" type="float" setter="set_radius" getter="get_radius">
+ <member name="radius" type="float" setter="set_radius" getter="get_radius" default="1.0">
The radius of the cylinder.
</member>
- <member name="sides" type="int" setter="set_sides" getter="get_sides">
+ <member name="sides" type="int" setter="set_sides" getter="get_sides" default="8">
The number of sides of the cylinder, the higher this number the more detail there will be in the cylinder.
</member>
- <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces">
+ <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces" default="true">
If [code]true[/code] the normals of the cylinder are set to give a smooth effect making the cylinder seem rounded. If [code]false[/code] the cylinder will have a flat shaded look.
</member>
</members>
diff --git a/modules/csg/doc_classes/CSGPolygon.xml b/modules/csg/doc_classes/CSGPolygon.xml
index 2c5d298222..0ecee92cd5 100644
--- a/modules/csg/doc_classes/CSGPolygon.xml
+++ b/modules/csg/doc_classes/CSGPolygon.xml
@@ -11,13 +11,13 @@
<methods>
</methods>
<members>
- <member name="depth" type="float" setter="set_depth" getter="get_depth">
+ <member name="depth" type="float" setter="set_depth" getter="get_depth" default="1.0">
Extrusion depth when [member mode] is [constant MODE_DEPTH].
</member>
<member name="material" type="Material" setter="set_material" getter="get_material">
Material to use for the resulting mesh.
</member>
- <member name="mode" type="int" setter="set_mode" getter="get_mode" enum="CSGPolygon.Mode">
+ <member name="mode" type="int" setter="set_mode" getter="get_mode" enum="CSGPolygon.Mode" default="0">
Extrusion mode.
</member>
<member name="path_continuous_u" type="bool" setter="set_path_continuous_u" getter="is_path_continuous_u">
@@ -38,10 +38,10 @@
<member name="path_rotation" type="int" setter="set_path_rotation" getter="get_path_rotation" enum="CSGPolygon.PathRotation">
The method by which each slice is rotated along the path when [member mode] is [constant MODE_PATH].
</member>
- <member name="polygon" type="PoolVector2Array" setter="set_polygon" getter="get_polygon">
+ <member name="polygon" type="PoolVector2Array" setter="set_polygon" getter="get_polygon" default="PoolVector2Array( 0, 0, 0, 1, 1, 1, 1, 0 )">
Point array that defines the shape that we'll extrude.
</member>
- <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces">
+ <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces" default="false">
Generates smooth normals so smooth shading is applied to our mesh.
</member>
<member name="spin_degrees" type="float" setter="set_spin_degrees" getter="get_spin_degrees">
diff --git a/modules/csg/doc_classes/CSGPrimitive.xml b/modules/csg/doc_classes/CSGPrimitive.xml
index 869e4006fe..6c2f837637 100644
--- a/modules/csg/doc_classes/CSGPrimitive.xml
+++ b/modules/csg/doc_classes/CSGPrimitive.xml
@@ -10,7 +10,7 @@
<methods>
</methods>
<members>
- <member name="invert_faces" type="bool" setter="set_invert_faces" getter="is_inverting_faces">
+ <member name="invert_faces" type="bool" setter="set_invert_faces" getter="is_inverting_faces" default="false">
Invert the faces of the mesh.
</member>
</members>
diff --git a/modules/csg/doc_classes/CSGShape.xml b/modules/csg/doc_classes/CSGShape.xml
index 7fa7c78534..755d8df67e 100644
--- a/modules/csg/doc_classes/CSGShape.xml
+++ b/modules/csg/doc_classes/CSGShape.xml
@@ -64,23 +64,23 @@
</method>
</methods>
<members>
- <member name="calculate_tangents" type="bool" setter="set_calculate_tangents" getter="is_calculating_tangents">
+ <member name="calculate_tangents" type="bool" setter="set_calculate_tangents" getter="is_calculating_tangents" default="true">
Calculate tangents for the CSG shape which allows the use of normal maps. This is only applied on the root shape, this setting is ignored on any child.
</member>
- <member name="collision_layer" type="int" setter="set_collision_layer" getter="get_collision_layer">
+ <member name="collision_layer" type="int" setter="set_collision_layer" getter="get_collision_layer" default="1">
The physics layers this area is in.
Collidable objects can exist in any of 32 different layers. These layers work like a tagging system, and are not visual. A collidable can use these layers to select with which objects it can collide, using the collision_mask property.
A contact is detected if object A is in any of the layers that object B scans, or object B is in any layer scanned by object A.
</member>
- <member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask">
+ <member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask" default="1">
The physics layers this CSG shape scans for collisions.
</member>
- <member name="operation" type="int" setter="set_operation" getter="get_operation" enum="CSGShape.Operation">
+ <member name="operation" type="int" setter="set_operation" getter="get_operation" enum="CSGShape.Operation" default="0">
The operation that is performed on this shape. This is ignored for the first CSG child node as the operation is between this node and the previous child of this nodes parent.
</member>
- <member name="snap" type="float" setter="set_snap" getter="get_snap">
+ <member name="snap" type="float" setter="set_snap" getter="get_snap" default="0.001">
</member>
- <member name="use_collision" type="bool" setter="set_use_collision" getter="is_using_collision">
+ <member name="use_collision" type="bool" setter="set_use_collision" getter="is_using_collision" default="false">
Adds a collision shape to the physics engine for our CSG shape. This will always act like a static body. Note that the collision shape is still active even if the CSG shape itself is hidden.
</member>
</members>
@@ -92,7 +92,7 @@
Only intersecting geometry remains, the rest is removed.
</constant>
<constant name="OPERATION_SUBTRACTION" value="2" enum="Operation">
- The second shape is susbtracted from the first, leaving a dent with it's shape.
+ The second shape is subtracted from the first, leaving a dent with its shape.
</constant>
</constants>
</class>
diff --git a/modules/csg/doc_classes/CSGSphere.xml b/modules/csg/doc_classes/CSGSphere.xml
index 2a12cf84db..714e725acb 100644
--- a/modules/csg/doc_classes/CSGSphere.xml
+++ b/modules/csg/doc_classes/CSGSphere.xml
@@ -14,16 +14,16 @@
<member name="material" type="Material" setter="set_material" getter="get_material">
The material used to render the sphere.
</member>
- <member name="radial_segments" type="int" setter="set_radial_segments" getter="get_radial_segments">
+ <member name="radial_segments" type="int" setter="set_radial_segments" getter="get_radial_segments" default="12">
Number of vertical slices for the sphere.
</member>
- <member name="radius" type="float" setter="set_radius" getter="get_radius">
+ <member name="radius" type="float" setter="set_radius" getter="get_radius" default="1.0">
Radius of the sphere.
</member>
- <member name="rings" type="int" setter="set_rings" getter="get_rings">
+ <member name="rings" type="int" setter="set_rings" getter="get_rings" default="6">
Number of horizontal slices for the sphere.
</member>
- <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces">
+ <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces" default="true">
If [code]true[/code] the normals of the sphere are set to give a smooth effect making the sphere seem rounded. If [code]false[/code] the sphere will have a flat shaded look.
</member>
</members>
diff --git a/modules/csg/doc_classes/CSGTorus.xml b/modules/csg/doc_classes/CSGTorus.xml
index 0d4437d87f..5dc6bb8380 100644
--- a/modules/csg/doc_classes/CSGTorus.xml
+++ b/modules/csg/doc_classes/CSGTorus.xml
@@ -11,22 +11,22 @@
<methods>
</methods>
<members>
- <member name="inner_radius" type="float" setter="set_inner_radius" getter="get_inner_radius">
+ <member name="inner_radius" type="float" setter="set_inner_radius" getter="get_inner_radius" default="2.0">
The inner radius of the torus.
</member>
<member name="material" type="Material" setter="set_material" getter="get_material">
The material used to render the torus.
</member>
- <member name="outer_radius" type="float" setter="set_outer_radius" getter="get_outer_radius">
+ <member name="outer_radius" type="float" setter="set_outer_radius" getter="get_outer_radius" default="3.0">
The outer radius of the torus.
</member>
- <member name="ring_sides" type="int" setter="set_ring_sides" getter="get_ring_sides">
+ <member name="ring_sides" type="int" setter="set_ring_sides" getter="get_ring_sides" default="6">
The number of edges each ring of the torus is constructed of.
</member>
- <member name="sides" type="int" setter="set_sides" getter="get_sides">
+ <member name="sides" type="int" setter="set_sides" getter="get_sides" default="8">
The number of slices the torus is constructed of.
</member>
- <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces">
+ <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces" default="true">
If [code]true[/code] the normals of the torus are set to give a smooth effect making the torus seem rounded. If [code]false[/code] the torus will have a flat shaded look.
</member>
</members>
diff --git a/modules/csg/icons/icon_c_s_g_box.svg b/modules/csg/icons/icon_c_s_g_box.svg
new file mode 100644
index 0000000000..67e34df444
--- /dev/null
+++ b/modules/csg/icons/icon_c_s_g_box.svg
@@ -0,0 +1,6 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g transform="translate(0 -1036.4)">
+<path transform="translate(0 1036.4)" d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1h-2zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1v-1z" fill="#84c2ff"/>
+<path transform="translate(0 1036.4)" d="m8 0.94531-7 3.5v7.2227l7 3.5 0.29492-0.14844c-0.18282-0.30101-0.29492-0.64737-0.29492-1.0195v-2c0-0.72651 0.40824-1.3664 1-1.7168v-1.6699l4-2v1.3867h1c0.36419 0 0.70336 0.10754 1 0.2832v-3.8379zm0 2.1152 3.9395 1.9707-3.9395 1.9688-3.9395-1.9688zm-5 3.5527 4 2v3.9414l-4-2.002z" fill="#fc9c9c" stroke-width="1.0667"/>
+</g>
+</svg>
diff --git a/modules/csg/icons/icon_c_s_g_capsule.svg b/modules/csg/icons/icon_c_s_g_capsule.svg
new file mode 100644
index 0000000000..92a7b5a870
--- /dev/null
+++ b/modules/csg/icons/icon_c_s_g_capsule.svg
@@ -0,0 +1,6 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g>
+<path d="m8 1c-2.7527 0-5 2.2418-5 4.9902v4.0176c0 2.7484 2.2473 4.9922 5 4.9922 0.092943 0 0.18367-0.008623 0.27539-0.013672-0.17055-0.29341-0.27539-0.62792-0.27539-0.98633v-2c0-0.72887 0.41095-1.3691 1.0059-1.7188v-0.28125c0.34771-0.034464 0.68259-0.10691 1.0156-0.19922 0.10394-0.99856 0.95603-1.8008 1.9785-1.8008h1v-2.0098c0-2.7484-2.2473-4.9902-5-4.9902zm-1.0059 2.127v4.8574c-0.66556-0.1047-1.2974-0.37231-1.9941-0.66211v-1.3223c0-1.3474 0.79841-2.4642 1.9941-2.873zm2.0117 0c1.1957 0.4088 1.9941 1.5256 1.9941 2.873v1.3457c-0.68406 0.3054-1.3142 0.57292-1.9941 0.66602v-4.8848zm-4.0059 6.334c0.67836 0.2231 1.3126 0.44599 1.9941 0.52539v2.8848c-1.1957-0.4092-1.9941-1.5237-1.9941-2.8711v-0.53906z" fill="#fc9c9c"/>
+<path d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1z" fill="#84c2ff"/>
+</g>
+</svg>
diff --git a/modules/csg/icons/icon_c_s_g_combiner.svg b/modules/csg/icons/icon_c_s_g_combiner.svg
new file mode 100644
index 0000000000..cce2902e24
--- /dev/null
+++ b/modules/csg/icons/icon_c_s_g_combiner.svg
@@ -0,0 +1,8 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g transform="translate(0 -1036.4)">
+<path transform="translate(0 1036.4)" d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1h-2zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1v-1z" fill="#84c2ff"/>
+<g fill="#fc9c9c">
+<path transform="translate(0 1036.4)" d="m3 1c-1.1046 0-2 0.89543-2 2h2zm2 0v2h2v-2zm4 0v2h2v-2zm4 0v2h2c0-1.1046-0.89543-2-2-2zm-12 4v2h2v-2zm12 0v2h2v-2zm-12 4v2h2v-2zm0 4c0 1.1046 0.89543 2 2 2v-2zm4 0v2h2v-2z" fill="#fc9c9c"/>
+</g>
+</g>
+</svg>
diff --git a/modules/csg/icons/icon_c_s_g_cylinder.svg b/modules/csg/icons/icon_c_s_g_cylinder.svg
new file mode 100644
index 0000000000..645a74c79b
--- /dev/null
+++ b/modules/csg/icons/icon_c_s_g_cylinder.svg
@@ -0,0 +1,6 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 14.999999 14.999999" xmlns="http://www.w3.org/2000/svg">
+<g>
+<path transform="scale(.9375)" d="m8 1c-1.7469 0-3.328 0.22648-4.5586 0.63672-0.61528 0.20512-1.1471 0.45187-1.5898 0.80078-0.44272 0.34891-0.85156 0.88101-0.85156 1.5625v8c0 0.68149 0.40884 1.2155 0.85156 1.5645 0.44272 0.34891 0.97457 0.59577 1.5898 0.80078 1.2306 0.41024 2.8117 0.63477 4.5586 0.63477 0.095648 0 0.18467-0.008426 0.2793-0.009766-0.1722-0.29446-0.2793-0.62995-0.2793-0.99023v-1c-1.5668 0-2.9867-0.2195-3.9277-0.5332-0.46329-0.15435-0.90474-0.33752-1.0723-0.4668v-5.8125c0.1468 0.058667 0.2835 0.12515 0.44141 0.17773 1.2306 0.41024 2.8117 0.63477 4.5586 0.63477s3.328-0.22453 4.5586-0.63477c0.15791-0.052267 0.29461-0.11864 0.44141-0.17773v1.8125h1c0.36396 0 0.70348 0.10774 1 0.2832v-4.2832c0-0.68149-0.40884-1.2136-0.85156-1.5625-0.44272-0.34891-0.97457-0.59566-1.5898-0.80078-1.2306-0.41024-2.8117-0.63672-4.5586-0.63672zm0 2c1.5668 0 2.9867 0.22145 3.9277 0.53516 0.46368 0.15456 0.80138 0.33741 0.96875 0.4668-0.16752 0.12928-0.50546 0.3105-0.96875 0.46484-0.94102 0.31371-2.361 0.5332-3.9277 0.5332s-2.9867-0.2195-3.9277-0.5332c-0.46329-0.15435-0.80123-0.33556-0.96875-0.46484 0.16737-0.12939 0.50507-0.31224 0.96875-0.4668 0.94102-0.31371 2.361-0.53516 3.9277-0.53516z" fill="#fc9c9c" stroke-width="1.0667"/>
+<path d="m11.25 8.4375c-0.51938 0-0.9375 0.41812-0.9375 0.9375v0.9375h1.875v1.875h0.9375c0.51938 0 0.9375-0.41812 0.9375-0.9375v-1.875c0-0.51938-0.41812-0.9375-0.9375-0.9375zm0.9375 3.75h-1.875v-1.875h-0.9375c-0.51938 0-0.9375 0.41812-0.9375 0.9375v1.875c0 0.51938 0.41812 0.9375 0.9375 0.9375h1.875c0.51938 0 0.9375-0.41812 0.9375-0.9375z" fill="#84c2ff"/>
+</g>
+</svg>
diff --git a/modules/csg/icons/icon_c_s_g_mesh.svg b/modules/csg/icons/icon_c_s_g_mesh.svg
new file mode 100644
index 0000000000..6e940a4aa5
--- /dev/null
+++ b/modules/csg/icons/icon_c_s_g_mesh.svg
@@ -0,0 +1,6 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g>
+<path d="m3 1c-1.1046 0-2 0.89543-2 2 5.649e-4 0.71397 0.38169 1.3735 1 1.7305v6.541c-0.61771 0.35663-0.99874 1.0152-1 1.7285 0 1.1046 0.89543 2 2 2 0.71397-5.65e-4 1.3735-0.38169 1.7305-1h3.2695v-2h-3.2715c-0.17478-0.30301-0.42598-0.55488-0.72852-0.73047v-5.8555l4.916 4.916c0.31428-0.20669 0.68609-0.33008 1.084-0.33008 0-0.3979 0.12338-0.76971 0.33008-1.084l-4.916-4.916h5.8574c0.17478 0.30301 0.42598 0.55488 0.72852 0.73047v3.2695h2v-3.2715c0.61771-0.35663 0.99874-1.0152 1-1.7285 0-1.1046-0.89543-2-2-2-0.71397 5.648e-4 -1.3735 0.38169-1.7305 1h-6.541c-0.35663-0.61771-1.0152-0.99874-1.7285-1z" fill="#fc9c9c"/>
+<path d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1z" fill="#84c2ff"/>
+</g>
+</svg>
diff --git a/modules/csg/icons/icon_c_s_g_polygon.svg b/modules/csg/icons/icon_c_s_g_polygon.svg
new file mode 100644
index 0000000000..71b03cb8e6
--- /dev/null
+++ b/modules/csg/icons/icon_c_s_g_polygon.svg
@@ -0,0 +1,6 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g transform="translate(0 -1036.4)">
+<path transform="translate(0 1036.4)" d="m7.9629 1.002c-0.14254 0.00487-0.28238 0.04016-0.41016 0.10352l-6 3c-0.33878 0.16944-0.55276 0.51574-0.55273 0.89453v5.832c-0.105 0.61631 0.37487 1.1768 1 1.168h5v2c2.16e-5 0.67546 0.64487 1.1297 1.2617 0.95898-0.16118-0.28721-0.26172-0.61135-0.26172-0.95898v-2c0-0.72673 0.40794-1.3664 1-1.7168v-1.666l4-2v1.3828h1c0.36397 0 0.70348 0.10774 1 0.2832v-3.2773c6e-6 -0.00195 6e-6 -0.0039094 0-0.0058594 2.6e-5 -0.37879-0.21395-0.72509-0.55273-0.89453l-6-3c-0.15022-0.074574-0.31679-0.11017-0.48438-0.10352zm0.037109 2.1172l3.7637 1.8809-2.7637 1.3809v-1.3809c-5.52e-5 -0.55226-0.44774-0.99994-1-1h-1.7617l1.7617-0.88086zm-5 2.8809h4v4h-4v-4z" color="#000000" color-rendering="auto" dominant-baseline="auto" fill="#fc9c9c" image-rendering="auto" shape-rendering="auto" solid-color="#000000" style="font-feature-settings:normal;font-variant-alternates:normal;font-variant-caps:normal;font-variant-ligatures:normal;font-variant-numeric:normal;font-variant-position:normal;isolation:auto;mix-blend-mode:normal;shape-padding:0;text-decoration-color:#000000;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-orientation:mixed;text-transform:none;white-space:normal"/>
+<path transform="translate(0 1036.4)" d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1h-2zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1v-1z" fill="#84c2ff"/>
+</g>
+</svg>
diff --git a/modules/csg/icons/icon_c_s_g_sphere.svg b/modules/csg/icons/icon_c_s_g_sphere.svg
new file mode 100644
index 0000000000..f81b566993
--- /dev/null
+++ b/modules/csg/icons/icon_c_s_g_sphere.svg
@@ -0,0 +1,6 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g>
+<path d="m8 1c-3.8541 0-7 3.1459-7 7 0 3.8542 3.1459 7 7 7 0.093042 0 0.18321-0.01004 0.27539-0.013672-0.17055-0.29341-0.27539-0.62792-0.27539-0.98633v-2c0-0.72673 0.40794-1.3664 1-1.7168v-0.33398c0.34074-0.019259 0.67728-0.069097 1.0156-0.10547 0.083091-1.0187 0.94713-1.8438 1.9844-1.8438h2c0.35841 0 0.69292 0.10484 0.98633 0.27539 0.003633-0.092184 0.013672-0.18235 0.013672-0.27539 0-3.8541-3.1459-7-7-7zm-1 2.0977v4.8711c-1.2931-0.071342-2.6061-0.29819-3.9434-0.69141 0.30081-2.0978 1.8852-3.7665 3.9434-4.1797zm2 0c2.0549 0.41253 3.637 2.0767 3.9414 4.1699-1.3046 0.36677-2.6158 0.60259-3.9414 0.6875v-4.8574zm-5.7793 6.2988c1.2733 0.31892 2.5337 0.50215 3.7793 0.5625v2.9414c-1.8291-0.36719-3.266-1.7339-3.7793-3.5039z" fill="#fc9c9c"/>
+<path d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1z" fill="#84c2ff"/>
+</g>
+</svg>
diff --git a/modules/csg/icons/icon_c_s_g_torus.svg b/modules/csg/icons/icon_c_s_g_torus.svg
new file mode 100644
index 0000000000..3d30aa47b2
--- /dev/null
+++ b/modules/csg/icons/icon_c_s_g_torus.svg
@@ -0,0 +1,6 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g transform="translate(0 -1036.4)">
+<path transform="translate(0 1036.4)" d="m8 3c-1.8145 0-3.4691 0.41721-4.7461 1.1621-1.277 0.745-2.2539 1.9082-2.2539 3.3379 0 1.4298 0.9769 2.5949 2.2539 3.3398 1.277 0.7449 2.9316 1.1602 4.7461 1.1602 0-1.0907 0.90931-2 2-2 0-0.080836 0.013744-0.15778 0.023438-0.23633-0.61769 0.14673-1.3008 0.23633-2.0234 0.23633-1.4992 0-2.8437-0.36687-3.7383-0.88867-0.89456-0.5219-1.2617-1.108-1.2617-1.6113 0-0.5032 0.36716-1.0876 1.2617-1.6094 0.89456-0.5219 2.2391-0.89062 3.7383-0.89062s2.8437 0.36872 3.7383 0.89062c0.89456 0.5218 1.2617 1.1062 1.2617 1.6094 0 0.15978-0.053679 0.32822-0.13281 0.5h1.1328c0.32481 0 0.62893 0.088408 0.90234 0.23047 0.057552-0.23582 0.097656-0.47718 0.097656-0.73047 0-1.4297-0.9769-2.5929-2.2539-3.3379-1.277-0.7449-2.9316-1.1621-4.7461-1.1621z" color="#000000" color-rendering="auto" dominant-baseline="auto" fill="#fc9c9c" image-rendering="auto" shape-rendering="auto" solid-color="#000000" style="font-feature-settings:normal;font-variant-alternates:normal;font-variant-caps:normal;font-variant-ligatures:normal;font-variant-numeric:normal;font-variant-position:normal;isolation:auto;mix-blend-mode:normal;shape-padding:0;text-decoration-color:#000000;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-orientation:mixed;text-transform:none;white-space:normal"/>
+<path transform="translate(0 1036.4)" d="m12 9c-0.55401 0-1 0.44599-1 1v1h2v2h1c0.55401 0 1-0.44599 1-1v-2c0-0.55401-0.44599-1-1-1h-2zm1 4h-2v-2h-1c-0.55401 0-1 0.44599-1 1v2c0 0.55401 0.44599 1 1 1h2c0.55401 0 1-0.44599 1-1v-1z" fill="#84c2ff"/>
+</g>
+</svg>
diff --git a/modules/cvtt/image_compress_cvtt.cpp b/modules/cvtt/image_compress_cvtt.cpp
index 0a70ff535f..17b0038780 100644
--- a/modules/cvtt/image_compress_cvtt.cpp
+++ b/modules/cvtt/image_compress_cvtt.cpp
@@ -145,7 +145,7 @@ void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::CompressS
int h = p_image->get_height();
bool is_ldr = (p_image->get_format() <= Image::FORMAT_RGBA8);
- bool is_hdr = (p_image->get_format() == Image::FORMAT_RGBH);
+ bool is_hdr = (p_image->get_format() >= Image::FORMAT_RH) && (p_image->get_format() <= Image::FORMAT_RGBE9995);
if (!is_ldr && !is_hdr) {
return; // Not a usable source format
@@ -175,6 +175,10 @@ void image_compress_cvtt(Image *p_image, float p_lossy_quality, Image::CompressS
bool is_signed = false;
if (is_hdr) {
+ if (p_image->get_format() != Image::FORMAT_RGBH) {
+ p_image->convert(Image::FORMAT_RGBH);
+ }
+
PoolVector<uint8_t>::Read rb = p_image->get_data().read();
const uint16_t *source_data = reinterpret_cast<const uint16_t *>(&rb[0]);
@@ -384,8 +388,8 @@ void image_decompress_cvtt(Image *p_image) {
h >>= 1;
}
- rb = PoolVector<uint8_t>::Read();
- wb = PoolVector<uint8_t>::Write();
+ rb.release();
+ wb.release();
p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data);
}
diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp
index 059c06c37c..4628bd9a5b 100644
--- a/modules/dds/texture_loader_dds.cpp
+++ b/modules/dds/texture_loader_dds.cpp
@@ -31,6 +31,8 @@
#include "texture_loader_dds.h"
#include "core/os/file_access.h"
+#define PF_FOURCC(s) ((uint32_t)(((s)[3] << 24U) | ((s)[2] << 16U) | ((s)[1] << 8U) | ((s)[0])))
+
enum {
DDS_MAGIC = 0x20534444,
DDSD_CAPS = 0x00000001,
@@ -51,6 +53,7 @@ enum DDSFormat {
DDS_DXT5,
DDS_ATI1,
DDS_ATI2,
+ DDS_A2XY,
DDS_BGRA8,
DDS_BGR8,
DDS_RGBA8, //flipped in dds
@@ -74,9 +77,12 @@ struct DDSFormatInfo {
};
static const DDSFormatInfo dds_format_info[DDS_MAX] = {
- { "DXT1", true, false, 4, 8, Image::FORMAT_DXT1 },
- { "DXT3", true, false, 4, 16, Image::FORMAT_DXT3 },
- { "DXT5", true, false, 4, 16, Image::FORMAT_DXT5 },
+ { "DXT1/BC1", true, false, 4, 8, Image::FORMAT_DXT1 },
+ { "DXT3/BC2", true, false, 4, 16, Image::FORMAT_DXT3 },
+ { "DXT5/BC3", true, false, 4, 16, Image::FORMAT_DXT5 },
+ { "ATI1/BC4", true, false, 4, 8, Image::FORMAT_RGTC_R },
+ { "ATI2/3DC/BC5", true, false, 4, 16, Image::FORMAT_RGTC_RG },
+ { "A2XY/DXN/BC5", true, false, 4, 16, Image::FORMAT_RGTC_RG },
{ "BGRA8", false, false, 1, 4, Image::FORMAT_RGBA8 },
{ "BGR8", false, false, 1, 3, Image::FORMAT_RGB8 },
{ "RGBA8", false, false, 1, 4, Image::FORMAT_RGBA8 },
@@ -158,22 +164,25 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
DDSFormat dds_format;
- if (format_flags & DDPF_FOURCC && format_fourcc == 0x31545844) { //'1TXD'
+ if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("DXT1")) {
dds_format = DDS_DXT1;
- } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x33545844) { //'3TXD'
+ } else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("DXT3")) {
dds_format = DDS_DXT3;
- } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x35545844) { //'5TXD'
+ } else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("DXT5")) {
dds_format = DDS_DXT5;
- } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x31495441) { //'1ITA'
+ } else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("ATI1")) {
dds_format = DDS_ATI1;
- } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x32495441) { //'2ITA'
+ } else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("ATI2")) {
dds_format = DDS_ATI2;
+ } else if (format_flags & DDPF_FOURCC && format_fourcc == PF_FOURCC("A2XY")) {
+
+ dds_format = DDS_A2XY;
} else if (format_flags & DDPF_RGB && format_flags & DDPF_ALPHAPIXELS && format_rgb_bits == 32 && format_red_mask == 0xff0000 && format_green_mask == 0xff00 && format_blue_mask == 0xff && format_alpha_mask == 0xff000000) {
@@ -242,7 +251,6 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
src_data.resize(size);
PoolVector<uint8_t>::Write wb = src_data.write();
f->get_buffer(wb.ptr(), size);
- wb = PoolVector<uint8_t>::Write();
} else if (info.palette) {
@@ -287,8 +295,6 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
if (colsize == 4)
wb[dst_ofs + 3] = palette[src_ofs + 3];
}
-
- wb = PoolVector<uint8_t>::Write();
} else {
//uncompressed generic...
@@ -435,8 +441,6 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path,
default: {
}
}
-
- wb = PoolVector<uint8_t>::Write();
}
Ref<Image> img = memnew(Image(width, height, mipmaps - 1, info.format, src_data));
diff --git a/modules/dds/texture_loader_dds.h b/modules/dds/texture_loader_dds.h
index 585f2891bf..6ddef4e770 100644
--- a/modules/dds/texture_loader_dds.h
+++ b/modules/dds/texture_loader_dds.h
@@ -35,7 +35,6 @@
#include "scene/resources/texture.h"
class ResourceFormatDDS : public ResourceFormatLoader {
- GDCLASS(ResourceFormatDDS, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/enet/SCsub b/modules/enet/SCsub
index 78d8d43414..485c33b1a8 100644
--- a/modules/enet/SCsub
+++ b/modules/enet/SCsub
@@ -22,7 +22,7 @@ if env['builtin_enet']:
thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
env_enet.Prepend(CPPPATH=[thirdparty_dir])
- env_enet.Append(CPPFLAGS=["-DGODOT_ENET"])
+ env_enet.Append(CPPDEFINES=["GODOT_ENET"])
env_thirdparty = env_enet.Clone()
env_thirdparty.disable_warnings()
diff --git a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml b/modules/enet/doc_classes/NetworkedMultiplayerENet.xml
index d3d1e58b7b..84ed5fd9ee 100644
--- a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml
+++ b/modules/enet/doc_classes/NetworkedMultiplayerENet.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="NetworkedMultiplayerENet" inherits="NetworkedMultiplayerPeer" category="Core" version="3.2">
<brief_description>
- PacketPeer implementation using the ENet library.
+ PacketPeer implementation using the [url=http://enet.bespin.org/index.html]ENet[/url] library.
</brief_description>
<description>
A PacketPeer implementation that should be passed to [member SceneTree.network_peer] after being initialized as either a client or server. Events can then be handled by connecting to [SceneTree] signals.
@@ -34,7 +34,7 @@
<argument index="4" name="client_port" type="int" default="0">
</argument>
<description>
- Create client that connects to a server at [code]address[/code] using specified [code]port[/code]. The given address needs to be either a fully qualified domain name (e.g. [code]www.example.com[/code]) or an IP address in IPv4 or IPv6 format (e.g. [code]192.168.1.1[/code]). The [code]port[/code] is the port the server is listening on. The [code]in_bandwidth[/code] and [code]out_bandwidth[/code] parameters can be used to limit the incoming and outgoing bandwidth to the given number of bytes per second. The default of 0 means unlimited bandwidth. Note that ENet will strategically drop packets on specific sides of a connection between peers to ensure the peer's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. Returns [code]OK[/code] if a client was created, [code]ERR_ALREADY_IN_USE[/code] if this NetworkedMultiplayerEnet instance already has an open connection (in which case you need to call [method close_connection] first) or [code]ERR_CANT_CREATE[/code] if the client could not be created. If [code]client_port[/code] is specified, the client will also listen to the given port, this is useful in some NAT traversal technique.
+ Create client that connects to a server at [code]address[/code] using specified [code]port[/code]. The given address needs to be either a fully qualified domain name (e.g. [code]"www.example.com"[/code]) or an IP address in IPv4 or IPv6 format (e.g. [code]"192.168.1.1"[/code]). The [code]port[/code] is the port the server is listening on. The [code]in_bandwidth[/code] and [code]out_bandwidth[/code] parameters can be used to limit the incoming and outgoing bandwidth to the given number of bytes per second. The default of 0 means unlimited bandwidth. Note that ENet will strategically drop packets on specific sides of a connection between peers to ensure the peer's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. Returns [constant OK] if a client was created, [constant ERR_ALREADY_IN_USE] if this NetworkedMultiplayerENet instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the client could not be created. If [code]client_port[/code] is specified, the client will also listen to the given port; this is useful for some NAT traversal techniques.
</description>
</method>
<method name="create_server">
@@ -49,7 +49,7 @@
<argument index="3" name="out_bandwidth" type="int" default="0">
</argument>
<description>
- Create server that listens to connections via [code]port[/code]. The port needs to be an available, unused port between 0 and 65535. Note that ports below 1024 are privileged and may require elevated permissions depending on the platform. To change the interface the server listens on, use [method set_bind_ip]. The default IP is the wildcard [code]*[/code], which listens on all available interfaces. [code]max_clients[/code] is the maximum number of clients that are allowed at once, any number up to 4096 may be used, although the achievable number of simultaneous clients may be far lower and depends on the application. For additional details on the bandwidth parameters, see [method create_client]. Returns [code]OK[/code] if a server was created, [code]ERR_ALREADY_IN_USE[/code] if this NetworkedMultiplayerEnet instance already has an open connection (in which case you need to call [method close_connection] first) or [code]ERR_CANT_CREATE[/code] if the server could not be created.
+ Create server that listens to connections via [code]port[/code]. The port needs to be an available, unused port between 0 and 65535. Note that ports below 1024 are privileged and may require elevated permissions depending on the platform. To change the interface the server listens on, use [method set_bind_ip]. The default IP is the wildcard [code]"*"[/code], which listens on all available interfaces. [code]max_clients[/code] is the maximum number of clients that are allowed at once, any number up to 4096 may be used, although the achievable number of simultaneous clients may be far lower and depends on the application. For additional details on the bandwidth parameters, see [method create_client]. Returns [constant OK] if a server was created, [constant ERR_ALREADY_IN_USE] if this NetworkedMultiplayerENet instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the server could not be created.
</description>
</method>
<method name="disconnect_peer">
@@ -101,39 +101,39 @@
<argument index="0" name="ip" type="String">
</argument>
<description>
- The IP used when creating a server. This is set to the wildcard [code]*[/code] by default, which binds to all available interfaces. The given IP needs to be in IPv4 or IPv6 address format, for example: [code]192.168.1.1[/code].
+ The IP used when creating a server. This is set to the wildcard [code]"*"[/code] by default, which binds to all available interfaces. The given IP needs to be in IPv4 or IPv6 address format, for example: [code]"192.168.1.1"[/code].
</description>
</method>
</methods>
<members>
- <member name="always_ordered" type="bool" setter="set_always_ordered" getter="is_always_ordered">
- Always use [code]TRANSFER_MODE_ORDERED[/code] in place of [code]TRANSFER_MODE_UNRELIABLE[/code]. This is the only way to use ordering with the RPC system.
+ <member name="always_ordered" type="bool" setter="set_always_ordered" getter="is_always_ordered" default="false">
+ Enforce ordered packets when using [constant NetworkedMultiplayerPeer.TRANSFER_MODE_UNRELIABLE] (thus behaving similarly to [constant NetworkedMultiplayerPeer.TRANSFER_MODE_UNRELIABLE_ORDERED]). This is the only way to use ordering with the RPC system.
</member>
- <member name="channel_count" type="int" setter="set_channel_count" getter="get_channel_count">
- The number of channels to be used by ENet. Default: [code]3[/code]. Channels are used to separate different kinds of data. In reliable or ordered mode, for example, the packet delivery order is ensured on a per channel basis.
+ <member name="channel_count" type="int" setter="set_channel_count" getter="get_channel_count" default="3">
+ The number of channels to be used by ENet. Channels are used to separate different kinds of data. In reliable or ordered mode, for example, the packet delivery order is ensured on a per channel basis.
</member>
- <member name="compression_mode" type="int" setter="set_compression_mode" getter="get_compression_mode" enum="NetworkedMultiplayerENet.CompressionMode">
- The compression method used for network packets. Default is no compression. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all.
+ <member name="compression_mode" type="int" setter="set_compression_mode" getter="get_compression_mode" enum="NetworkedMultiplayerENet.CompressionMode" default="0">
+ The compression method used for network packets. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all.
</member>
- <member name="transfer_channel" type="int" setter="set_transfer_channel" getter="get_transfer_channel">
- Set the default channel to be used to transfer data. By default this value is [code]-1[/code] which means that ENet will only use 2 channels, one for reliable and one for unreliable packets. Channel [code]0[/code] is reserved, and cannot be used. Setting this member to any value between [code]0[/code] and [member channel_count] (excluded) will force ENet to use that channel for sending data.
+ <member name="transfer_channel" type="int" setter="set_transfer_channel" getter="get_transfer_channel" default="-1">
+ Set the default channel to be used to transfer data. By default, this value is [code]-1[/code] which means that ENet will only use 2 channels, one for reliable and one for unreliable packets. Channel [code]0[/code] is reserved, and cannot be used. Setting this member to any value between [code]0[/code] and [member channel_count] (excluded) will force ENet to use that channel for sending data.
</member>
</members>
<constants>
<constant name="COMPRESS_NONE" value="0" enum="CompressionMode">
- No compression.
+ No compression. This uses the most bandwidth, but has the upside of requiring the fewest CPU resources.
</constant>
<constant name="COMPRESS_RANGE_CODER" value="1" enum="CompressionMode">
- ENet's buildin range encoding.
+ ENet's built-in range encoding.
</constant>
<constant name="COMPRESS_FASTLZ" value="2" enum="CompressionMode">
- FastLZ compression.
+ [url=http://fastlz.org/]FastLZ[/url] compression. This option uses less CPU resources compared to [constant COMPRESS_ZLIB], at the expense of using more bandwidth.
</constant>
<constant name="COMPRESS_ZLIB" value="3" enum="CompressionMode">
- zlib compression.
+ [url=https://www.zlib.net/]Zlib[/url] compression. This option uses less bandwidth compared to [constant COMPRESS_FASTLZ], at the expense of using more CPU resources.
</constant>
<constant name="COMPRESS_ZSTD" value="4" enum="CompressionMode">
- ZStandard compression.
+ [url=https://facebook.github.io/zstd/]Zstandard[/url] compression.
</constant>
</constants>
</class>
diff --git a/modules/enet/networked_multiplayer_enet.cpp b/modules/enet/networked_multiplayer_enet.cpp
index 18dfe08e85..a5a356ced2 100644
--- a/modules/enet/networked_multiplayer_enet.cpp
+++ b/modules/enet/networked_multiplayer_enet.cpp
@@ -80,6 +80,7 @@ Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int
ERR_FAIL_COND_V(p_out_bandwidth < 0, ERR_INVALID_PARAMETER);
ENetAddress address;
+ memset(&address, 0, sizeof(address));
#ifdef GODOT_ENET
if (bind_ip.is_wildcard()) {
@@ -346,7 +347,7 @@ void NetworkedMultiplayerENet::poll() {
uint32_t *id = (uint32_t *)event.peer->data;
- ERR_CONTINUE(event.packet->dataLength < 8)
+ ERR_CONTINUE(event.packet->dataLength < 8);
uint32_t source = decode_uint32(&event.packet->data[0]);
int target = decode_uint32(&event.packet->data[4]);
@@ -462,7 +463,7 @@ void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) {
ERR_FAIL_COND(!active);
ERR_FAIL_COND(!is_server());
- ERR_FAIL_COND(!peer_map.has(p_peer))
+ ERR_FAIL_COND(!peer_map.has(p_peer));
if (now) {
enet_peer_disconnect_now(peer_map[p_peer], 0);
@@ -881,7 +882,9 @@ NetworkedMultiplayerENet::NetworkedMultiplayerENet() {
NetworkedMultiplayerENet::~NetworkedMultiplayerENet() {
- close_connection();
+ if (active) {
+ close_connection();
+ }
}
// Sets IP for ENet to bind when using create_server or create_client
diff --git a/modules/enet/networked_multiplayer_enet.h b/modules/enet/networked_multiplayer_enet.h
index 957d0830cb..8dcb202314 100644
--- a/modules/enet/networked_multiplayer_enet.h
+++ b/modules/enet/networked_multiplayer_enet.h
@@ -38,7 +38,8 @@
class NetworkedMultiplayerENet : public NetworkedMultiplayerPeer {
- GDCLASS(NetworkedMultiplayerENet, NetworkedMultiplayerPeer)
+ GDCLASS(NetworkedMultiplayerENet, NetworkedMultiplayerPeer);
+
public:
enum CompressionMode {
COMPRESS_NONE,
diff --git a/modules/etc/texture_loader_pkm.cpp b/modules/etc/texture_loader_pkm.cpp
index f302834222..ff925480b8 100644
--- a/modules/etc/texture_loader_pkm.cpp
+++ b/modules/etc/texture_loader_pkm.cpp
@@ -80,7 +80,7 @@ RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path,
src_data.resize(size);
PoolVector<uint8_t>::Write wb = src_data.write();
f->get_buffer(wb.ptr(), size);
- wb = PoolVector<uint8_t>::Write();
+ wb.release();
int mipmaps = h.format;
int width = h.origWidth;
diff --git a/modules/etc/texture_loader_pkm.h b/modules/etc/texture_loader_pkm.h
index 860fe8b5df..79c17953fc 100644
--- a/modules/etc/texture_loader_pkm.h
+++ b/modules/etc/texture_loader_pkm.h
@@ -35,7 +35,6 @@
#include "scene/resources/texture.h"
class ResourceFormatPKM : public ResourceFormatLoader {
- GDCLASS(ResourceFormatPKM, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/freetype/SCsub b/modules/freetype/SCsub
index 0ea581220e..b47377cbc4 100644
--- a/modules/freetype/SCsub
+++ b/modules/freetype/SCsub
@@ -65,16 +65,16 @@ if env['builtin_freetype']:
# Also needed in main env for scene/
env.Prepend(CPPPATH=[thirdparty_dir + "/include"])
- env_freetype.Append(CPPFLAGS=['-DFT2_BUILD_LIBRARY', '-DFT_CONFIG_OPTION_USE_PNG'])
+ env_freetype.Append(CPPDEFINES=['FT2_BUILD_LIBRARY', 'FT_CONFIG_OPTION_USE_PNG'])
if (env['target'] != 'release'):
- env_freetype.Append(CPPFLAGS=['-DZLIB_DEBUG'])
+ env_freetype.Append(CPPDEFINES=['ZLIB_DEBUG'])
# Also requires libpng headers
if env['builtin_libpng']:
env_freetype.Prepend(CPPPATH=["#thirdparty/libpng"])
sfnt = thirdparty_dir + 'src/sfnt/sfnt.c'
- # Must be done after all CPPFLAGS are being set so we can copy them.
+ # Must be done after all CPPDEFINES are being set so we can copy them.
if env['platform'] == 'javascript':
# Forcibly undefine this macro so SIMD is not used in this file,
# since currently unsupported in WASM
@@ -103,4 +103,4 @@ if env['builtin_freetype']:
# Godot source files
env_freetype.add_source_files(env.modules_sources, "*.cpp")
# Used in scene/, needs to be in main env
-env.Append(CPPFLAGS=['-DFREETYPE_ENABLED'])
+env.Append(CPPDEFINES=['FREETYPE_ENABLED'])
diff --git a/modules/gdnative/android/android_gdn.cpp b/modules/gdnative/android/android_gdn.cpp
index 8657935602..624ef19dec 100644
--- a/modules/gdnative/android/android_gdn.cpp
+++ b/modules/gdnative/android/android_gdn.cpp
@@ -34,6 +34,8 @@
// These entry points are only for the android platform and are simple stubs in all others.
#ifdef __ANDROID__
+#include "platform/android/java_godot_wrapper.h"
+#include "platform/android/os_android.h"
#include "platform/android/thread_jandroid.h"
#else
#define JNIEnv void
@@ -54,20 +56,31 @@ JNIEnv *GDAPI godot_android_get_env() {
jobject GDAPI godot_android_get_activity() {
#ifdef __ANDROID__
- JNIEnv *env = ThreadAndroid::get_env();
-
- jclass activityThread = env->FindClass("android/app/ActivityThread");
- jmethodID currentActivityThread = env->GetStaticMethodID(activityThread, "currentActivityThread", "()Landroid/app/ActivityThread;");
- jobject at = env->CallStaticObjectMethod(activityThread, currentActivityThread);
- jmethodID getApplication = env->GetMethodID(activityThread, "getApplication", "()Landroid/app/Application;");
- jobject context = env->CallObjectMethod(at, getApplication);
+ OS_Android *os_android = (OS_Android *)OS::get_singleton();
+ return os_android->get_godot_java()->get_activity();
+#else
+ return NULL;
+#endif
+}
- return env->NewGlobalRef(context);
+jobject GDAPI godot_android_get_surface() {
+#ifdef __ANDROID__
+ OS_Android *os_android = (OS_Android *)OS::get_singleton();
+ return os_android->get_godot_java()->get_surface();
#else
return NULL;
#endif
}
+bool GDAPI godot_android_is_activity_resumed() {
+#ifdef __ANDROID__
+ OS_Android *os_android = (OS_Android *)OS::get_singleton();
+ return os_android->get_godot_java()->is_activity_resumed();
+#else
+ return false;
+#endif
+}
+
#ifdef __cplusplus
}
#endif \ No newline at end of file
diff --git a/modules/gdnative/arvr/arvr_interface_gdnative.cpp b/modules/gdnative/arvr/arvr_interface_gdnative.cpp
index c3f8688adb..64e2c362b2 100644
--- a/modules/gdnative/arvr/arvr_interface_gdnative.cpp
+++ b/modules/gdnative/arvr/arvr_interface_gdnative.cpp
@@ -33,9 +33,13 @@
#include "servers/arvr/arvr_positional_tracker.h"
#include "servers/visual/visual_server_globals.h"
+void ARVRInterfaceGDNative::_bind_methods() {
+ ADD_PROPERTY_DEFAULT("interface_is_initialized", false);
+ ADD_PROPERTY_DEFAULT("ar_is_anchor_detection_enabled", false);
+}
+
ARVRInterfaceGDNative::ARVRInterfaceGDNative() {
- // testing
- printf("Construct gdnative interface\n");
+ print_verbose("Construct gdnative interface\n");
// we won't have our data pointer until our library gets set
data = NULL;
@@ -44,9 +48,9 @@ ARVRInterfaceGDNative::ARVRInterfaceGDNative() {
}
ARVRInterfaceGDNative::~ARVRInterfaceGDNative() {
- printf("Destruct gdnative interface\n");
+ print_verbose("Destruct gdnative interface\n");
- if (is_initialized()) {
+ if (interface != NULL && is_initialized()) {
uninitialize();
};
@@ -99,13 +103,10 @@ int ARVRInterfaceGDNative::get_capabilities() const {
}
bool ARVRInterfaceGDNative::get_anchor_detection_is_enabled() const {
- bool enabled;
ERR_FAIL_COND_V(interface == NULL, false);
- enabled = interface->get_anchor_detection_is_enabled(data);
-
- return enabled;
+ return interface->get_anchor_detection_is_enabled(data);
}
void ARVRInterfaceGDNative::set_anchor_detection_is_enabled(bool p_enable) {
@@ -115,6 +116,17 @@ void ARVRInterfaceGDNative::set_anchor_detection_is_enabled(bool p_enable) {
interface->set_anchor_detection_is_enabled(data, p_enable);
}
+int ARVRInterfaceGDNative::get_camera_feed_id() {
+
+ ERR_FAIL_COND_V(interface == NULL, 0);
+
+ if ((interface->version.major > 1) || ((interface->version.major) == 1 && (interface->version.minor >= 1))) {
+ return (unsigned int)interface->get_camera_feed_id(data);
+ } else {
+ return 0;
+ }
+}
+
bool ARVRInterfaceGDNative::is_stereo() {
bool stereo;
@@ -126,21 +138,16 @@ bool ARVRInterfaceGDNative::is_stereo() {
}
bool ARVRInterfaceGDNative::is_initialized() const {
- bool initialized;
ERR_FAIL_COND_V(interface == NULL, false);
- initialized = interface->is_initialized(data);
-
- return initialized;
+ return interface->is_initialized(data);
}
bool ARVRInterfaceGDNative::initialize() {
- bool initialized;
-
ERR_FAIL_COND_V(interface == NULL, false);
- initialized = interface->initialize(data);
+ bool initialized = interface->initialize(data);
if (initialized) {
// if we successfully initialize our interface and we don't have a primary interface yet, this becomes our primary interface
diff --git a/modules/gdnative/arvr/arvr_interface_gdnative.h b/modules/gdnative/arvr/arvr_interface_gdnative.h
index 86396b067a..ab7090876a 100644
--- a/modules/gdnative/arvr/arvr_interface_gdnative.h
+++ b/modules/gdnative/arvr/arvr_interface_gdnative.h
@@ -41,7 +41,7 @@
*/
class ARVRInterfaceGDNative : public ARVRInterface {
- GDCLASS(ARVRInterfaceGDNative, ARVRInterface)
+ GDCLASS(ARVRInterfaceGDNative, ARVRInterface);
void cleanup();
@@ -49,6 +49,8 @@ protected:
const godot_arvr_interface_gdnative *interface;
void *data;
+ static void _bind_methods();
+
public:
/** general interface information **/
ARVRInterfaceGDNative();
@@ -66,6 +68,7 @@ public:
/** specific to AR **/
virtual bool get_anchor_detection_is_enabled() const;
virtual void set_anchor_detection_is_enabled(bool p_enable);
+ virtual int get_camera_feed_id();
/** rendering and internal **/
virtual Size2 get_render_targetsize();
diff --git a/modules/gdnative/config.py b/modules/gdnative/config.py
index 7898de5523..b9e5afcdf3 100644
--- a/modules/gdnative/config.py
+++ b/modules/gdnative/config.py
@@ -6,6 +6,7 @@ def configure(env):
def get_doc_classes():
return [
+ "@NativeScript",
"ARVRInterfaceGDNative",
"GDNative",
"GDNativeLibrary",
@@ -13,7 +14,6 @@ def get_doc_classes():
"NativeScript",
"PacketPeerGDNative",
"PluginScript",
- "ResourceFormatLoaderVideoStreamGDNative",
"StreamPeerGDNative",
"VideoStreamGDNative",
"WebRTCPeerConnectionGDNative",
diff --git a/modules/stb_vorbis/doc_classes/ResourceImporterOGGVorbis.xml b/modules/gdnative/doc_classes/@NativeScript.xml
index 4dd77fed34..cb5de198ac 100644
--- a/modules/stb_vorbis/doc_classes/ResourceImporterOGGVorbis.xml
+++ b/modules/gdnative/doc_classes/@NativeScript.xml
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" ?>
-<class name="ResourceImporterOGGVorbis" inherits="ResourceImporter" category="Core" version="3.2">
+<class name="@NativeScript" category="Core" version="3.2">
<brief_description>
</brief_description>
<description>
diff --git a/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml b/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml
index efdb948660..47c2ee3358 100644
--- a/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml
+++ b/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml
@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="ARVRInterfaceGDNative" inherits="ARVRInterface" category="Core" version="3.2">
<brief_description>
- GDNative wrapper for an ARVR interface
+ GDNative wrapper for an ARVR interface.
</brief_description>
<description>
- This is a wrapper class for GDNative implementations of the ARVR interface. To use a GDNative ARVR interface simply instantiate this object and set your GDNative library containing the ARVR interface implementation.
+ This is a wrapper class for GDNative implementations of the ARVR interface. To use a GDNative ARVR interface, simply instantiate this object and set your GDNative library containing the ARVR interface implementation.
</description>
<tutorials>
</tutorials>
diff --git a/modules/gdnative/doc_classes/GDNativeLibrary.xml b/modules/gdnative/doc_classes/GDNativeLibrary.xml
index 8bfd386b8d..7e1cac243a 100644
--- a/modules/gdnative/doc_classes/GDNativeLibrary.xml
+++ b/modules/gdnative/doc_classes/GDNativeLibrary.xml
@@ -23,13 +23,13 @@
<members>
<member name="config_file" type="ConfigFile" setter="set_config_file" getter="get_config_file">
</member>
- <member name="load_once" type="bool" setter="set_load_once" getter="should_load_once">
+ <member name="load_once" type="bool" setter="set_load_once" getter="should_load_once" default="true">
</member>
- <member name="reloadable" type="bool" setter="set_reloadable" getter="is_reloadable">
+ <member name="reloadable" type="bool" setter="set_reloadable" getter="is_reloadable" default="true">
</member>
- <member name="singleton" type="bool" setter="set_singleton" getter="is_singleton">
+ <member name="singleton" type="bool" setter="set_singleton" getter="is_singleton" default="false">
</member>
- <member name="symbol_prefix" type="String" setter="set_symbol_prefix" getter="get_symbol_prefix">
+ <member name="symbol_prefix" type="String" setter="set_symbol_prefix" getter="get_symbol_prefix" default="&quot;godot_&quot;">
</member>
</members>
<constants>
diff --git a/modules/gdnative/doc_classes/NativeScript.xml b/modules/gdnative/doc_classes/NativeScript.xml
index ac8b793b22..e34e209374 100644
--- a/modules/gdnative/doc_classes/NativeScript.xml
+++ b/modules/gdnative/doc_classes/NativeScript.xml
@@ -51,13 +51,13 @@
</method>
</methods>
<members>
- <member name="class_name" type="String" setter="set_class_name" getter="get_class_name">
+ <member name="class_name" type="String" setter="set_class_name" getter="get_class_name" default="&quot;&quot;">
</member>
<member name="library" type="GDNativeLibrary" setter="set_library" getter="get_library">
</member>
- <member name="script_class_icon_path" type="String" setter="set_script_class_icon_path" getter="get_script_class_icon_path">
+ <member name="script_class_icon_path" type="String" setter="set_script_class_icon_path" getter="get_script_class_icon_path" default="&quot;&quot;">
</member>
- <member name="script_class_name" type="String" setter="set_script_class_name" getter="get_script_class_name">
+ <member name="script_class_name" type="String" setter="set_script_class_name" getter="get_script_class_name" default="&quot;&quot;">
</member>
</members>
<constants>
diff --git a/modules/gdnative/gdnative.cpp b/modules/gdnative/gdnative.cpp
index a27935bfe2..4eb9a2a0a3 100644
--- a/modules/gdnative/gdnative.cpp
+++ b/modules/gdnative/gdnative.cpp
@@ -48,7 +48,7 @@ static const bool default_reloadable = true;
// Defined in gdnative_api_struct.gen.cpp
extern const godot_gdnative_core_api_struct api_struct;
-Map<String, Vector<Ref<GDNative> > > *GDNativeLibrary::loaded_libraries = NULL;
+Map<String, Vector<Ref<GDNative> > > GDNativeLibrary::loaded_libraries;
GDNativeLibrary::GDNativeLibrary() {
config_file.instance();
@@ -57,10 +57,6 @@ GDNativeLibrary::GDNativeLibrary() {
load_once = default_load_once;
singleton = default_singleton;
reloadable = default_reloadable;
-
- if (GDNativeLibrary::loaded_libraries == NULL) {
- GDNativeLibrary::loaded_libraries = memnew((Map<String, Vector<Ref<GDNative> > >));
- }
}
GDNativeLibrary::~GDNativeLibrary() {
@@ -318,10 +314,10 @@ bool GDNative::initialize() {
#endif
if (library->should_load_once()) {
- if (GDNativeLibrary::loaded_libraries->has(lib_path)) {
+ if (GDNativeLibrary::loaded_libraries.has(lib_path)) {
// already loaded. Don't load again.
// copy some of the stuff instead
- this->native_handle = (*GDNativeLibrary::loaded_libraries)[lib_path][0]->native_handle;
+ this->native_handle = GDNativeLibrary::loaded_libraries[lib_path][0]->native_handle;
initialized = true;
return true;
}
@@ -377,11 +373,11 @@ bool GDNative::initialize() {
initialized = true;
- if (library->should_load_once() && !GDNativeLibrary::loaded_libraries->has(lib_path)) {
+ if (library->should_load_once() && !GDNativeLibrary::loaded_libraries.has(lib_path)) {
Vector<Ref<GDNative> > gdnatives;
gdnatives.resize(1);
gdnatives.write[0] = Ref<GDNative>(this);
- GDNativeLibrary::loaded_libraries->insert(lib_path, gdnatives);
+ GDNativeLibrary::loaded_libraries.insert(lib_path, gdnatives);
}
return true;
@@ -395,7 +391,7 @@ bool GDNative::terminate() {
}
if (library->should_load_once()) {
- Vector<Ref<GDNative> > *gdnatives = &(*GDNativeLibrary::loaded_libraries)[library->get_current_library_path()];
+ Vector<Ref<GDNative> > *gdnatives = &GDNativeLibrary::loaded_libraries[library->get_current_library_path()];
if (gdnatives->size() > 1) {
// there are other GDNative's still using this library, so we actually don't terminate
gdnatives->erase(Ref<GDNative>(this));
@@ -405,7 +401,7 @@ bool GDNative::terminate() {
// we're the last one, terminate!
gdnatives->clear();
// whew this looks scary, but all it does is remove the entry completely
- GDNativeLibrary::loaded_libraries->erase(GDNativeLibrary::loaded_libraries->find(library->get_current_library_path()));
+ GDNativeLibrary::loaded_libraries.erase(GDNativeLibrary::loaded_libraries.find(library->get_current_library_path()));
}
}
diff --git a/modules/gdnative/gdnative.h b/modules/gdnative/gdnative.h
index ef57387059..408af26753 100644
--- a/modules/gdnative/gdnative.h
+++ b/modules/gdnative/gdnative.h
@@ -45,9 +45,9 @@ class GDNativeLibraryResourceLoader;
class GDNative;
class GDNativeLibrary : public Resource {
- GDCLASS(GDNativeLibrary, Resource)
+ GDCLASS(GDNativeLibrary, Resource);
- static Map<String, Vector<Ref<GDNative> > > *loaded_libraries;
+ static Map<String, Vector<Ref<GDNative> > > loaded_libraries;
friend class GDNativeLibraryResourceLoader;
friend class GDNative;
@@ -137,7 +137,7 @@ struct GDNativeCallRegistry {
};
class GDNative : public Reference {
- GDCLASS(GDNative, Reference)
+ GDCLASS(GDNative, Reference);
Ref<GDNativeLibrary> library;
@@ -165,7 +165,6 @@ public:
};
class GDNativeLibraryResourceLoader : public ResourceFormatLoader {
- GDCLASS(GDNativeLibraryResourceLoader, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path, Error *r_error);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
@@ -174,7 +173,6 @@ public:
};
class GDNativeLibraryResourceSaver : public ResourceFormatSaver {
- GDCLASS(GDNativeLibraryResourceSaver, ResourceFormatSaver)
public:
virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags);
virtual bool recognize(const RES &p_resource) const;
diff --git a/modules/gdnative/gdnative/array.cpp b/modules/gdnative/gdnative/array.cpp
index 6849ff03d7..1ef8e9f900 100644
--- a/modules/gdnative/gdnative/array.cpp
+++ b/modules/gdnative/gdnative/array.cpp
@@ -305,13 +305,13 @@ void GDAPI godot_array_sort_custom(godot_array *p_self, godot_object *p_obj, con
godot_int GDAPI godot_array_bsearch(godot_array *p_self, const godot_variant *p_value, const godot_bool p_before) {
Array *self = (Array *)p_self;
- return self->bsearch((const Variant *)p_value, p_before);
+ return self->bsearch(*(const Variant *)p_value, p_before);
}
godot_int GDAPI godot_array_bsearch_custom(godot_array *p_self, const godot_variant *p_value, godot_object *p_obj, const godot_string *p_func, const godot_bool p_before) {
Array *self = (Array *)p_self;
const String *func = (const String *)p_func;
- return self->bsearch_custom((const Variant *)p_value, (Object *)p_obj, *func, p_before);
+ return self->bsearch_custom(*(const Variant *)p_value, (Object *)p_obj, *func, p_before);
}
void GDAPI godot_array_destroy(godot_array *p_self) {
diff --git a/modules/gdnative/gdnative/vector2.cpp b/modules/gdnative/gdnative/vector2.cpp
index 8fa29580d6..a2ac61b35e 100644
--- a/modules/gdnative/gdnative/vector2.cpp
+++ b/modules/gdnative/gdnative/vector2.cpp
@@ -119,6 +119,14 @@ godot_vector2 GDAPI godot_vector2_cubic_interpolate(const godot_vector2 *p_self,
return dest;
}
+godot_vector2 GDAPI godot_vector2_move_toward(const godot_vector2 *p_self, const godot_vector2 *p_to, const godot_real p_delta) {
+ godot_vector2 dest;
+ const Vector2 *self = (const Vector2 *)p_self;
+ const Vector2 *to = (const Vector2 *)p_to;
+ *((Vector2 *)&dest) = self->move_toward(*to, p_delta);
+ return dest;
+}
+
godot_vector2 GDAPI godot_vector2_rotated(const godot_vector2 *p_self, const godot_real p_phi) {
godot_vector2 dest;
const Vector2 *self = (const Vector2 *)p_self;
diff --git a/modules/gdnative/gdnative/vector3.cpp b/modules/gdnative/gdnative/vector3.cpp
index ef86c6f7e9..894683ab38 100644
--- a/modules/gdnative/gdnative/vector3.cpp
+++ b/modules/gdnative/gdnative/vector3.cpp
@@ -124,6 +124,14 @@ godot_vector3 GDAPI godot_vector3_cubic_interpolate(const godot_vector3 *p_self,
return dest;
}
+godot_vector3 GDAPI godot_vector3_move_toward(const godot_vector3 *p_self, const godot_vector3 *p_to, const godot_real p_delta) {
+ godot_vector3 dest;
+ const Vector3 *self = (const Vector3 *)p_self;
+ const Vector3 *to = (const Vector3 *)p_to;
+ *((Vector3 *)&dest) = self->move_toward(*to, p_delta);
+ return dest;
+}
+
godot_real GDAPI godot_vector3_dot(const godot_vector3 *p_self, const godot_vector3 *p_b) {
const Vector3 *self = (const Vector3 *)p_self;
const Vector3 *b = (const Vector3 *)p_b;
diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json
index 8afe988102..6c12ee6534 100644
--- a/modules/gdnative/gdnative_api.json
+++ b/modules/gdnative/gdnative_api.json
@@ -26,6 +26,24 @@
["const godot_dictionary *", "p_self"],
["const godot_bool", "p_deep"]
]
+ },
+ {
+ "name": "godot_vector3_move_toward",
+ "return_type": "godot_vector3",
+ "arguments": [
+ ["const godot_vector3 *", "p_self"],
+ ["const godot_vector3 *", "p_to"],
+ ["const godot_real", "p_delta"]
+ ]
+ },
+ {
+ "name": "godot_vector2_move_toward",
+ "return_type": "godot_vector2",
+ "arguments": [
+ ["const godot_vector2 *", "p_self"],
+ ["const godot_vector2 *", "p_to"],
+ ["const godot_real", "p_delta"]
+ ]
}
]
},
@@ -6286,7 +6304,7 @@
"type": "ANDROID",
"version": {
"major": 1,
- "minor": 0
+ "minor": 1
},
"next": null,
"api": [
@@ -6301,6 +6319,18 @@
"return_type": "jobject",
"arguments": [
]
+ },
+ {
+ "name": "godot_android_get_surface",
+ "return_type": "jobject",
+ "arguments": [
+ ]
+ },
+ {
+ "name": "godot_android_is_activity_resumed",
+ "return_type": "bool",
+ "arguments": [
+ ]
}
]
},
diff --git a/modules/gdnative/icons/icon_g_d_native_library.svg b/modules/gdnative/icons/icon_g_d_native_library.svg
new file mode 100644
index 0000000000..b494c7af6e
--- /dev/null
+++ b/modules/gdnative/icons/icon_g_d_native_library.svg
@@ -0,0 +1,5 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g transform="translate(0 -1036.4)">
+<path transform="translate(0 1036.4)" d="m7 1l-0.56445 2.2578a5 5 0 0 0 -0.68945 0.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -0.28516 0.68555l-2.2539 0.5625v2l2.2578 0.56445a5 5 0 0 0 0.2793 0.6875l-1.1934 1.9902 1.4141 1.4141 1.9941-1.1953a5 5 0 0 0 0.68555 0.28516l0.5625 2.2539v-5.2695a2 2 0 0 1 -1 -1.7305 2 2 0 0 1 1 -1.7285v-0.27148h1 4.5762a5 5 0 0 0 -0.11328 -0.25195l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -0.68555 -0.28516l-0.5625-2.2539h-2zm2 7v1 5 1h5c0.55228 0 1-0.4477 1-1v-5c0-0.5523-0.44772-1-1-1v4l-1-1-1 1v-4h-3z" fill="#e0e0e0"/>
+</g>
+</svg>
diff --git a/modules/gdnative/icons/icon_native_script.svg b/modules/gdnative/icons/icon_native_script.svg
new file mode 100644
index 0000000000..fb9e135627
--- /dev/null
+++ b/modules/gdnative/icons/icon_native_script.svg
@@ -0,0 +1,5 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g transform="translate(0 -1036.4)">
+<path transform="translate(0 1036.4)" d="m7 1l-0.56445 2.2578a5 5 0 0 0 -0.68945 0.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -0.28516 0.68555l-2.2539 0.5625h3v1 1h2v-0.95117a2 2 0 0 1 0 -0.048828 2 2 0 0 1 2 -2 2 2 0 0 1 2 2v1h5v-2l-2.2578-0.56445a5 5 0 0 0 -0.2793 -0.6875l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -0.68555 -0.28516l-0.5625-2.2539h-2zm-6 7v4 4h2a3 3 0 0 0 3 -3 3 3 0 0 0 -3 -3v-2h-2zm6 0v2h2v-2h-2zm3 2v6h2v-4a1 1 0 0 1 1 1v3h2v-3a3 3 0 0 0 -3 -3h-2zm-7 2a1 1 0 0 1 1 1 1 1 0 0 1 -1 1v-2zm4 0v4h2v-4h-2z" fill="#e0e0e0"/>
+</g>
+</svg>
diff --git a/modules/gdnative/include/android/godot_android.h b/modules/gdnative/include/android/godot_android.h
index 32e86838be..7063e1d2c5 100644
--- a/modules/gdnative/include/android/godot_android.h
+++ b/modules/gdnative/include/android/godot_android.h
@@ -46,6 +46,8 @@ extern "C" {
JNIEnv *GDAPI godot_android_get_env();
jobject GDAPI godot_android_get_activity();
+jobject GDAPI godot_android_get_surface();
+bool GDAPI godot_android_is_activity_resumed();
#ifdef __cplusplus
}
diff --git a/modules/gdnative/include/arvr/godot_arvr.h b/modules/gdnative/include/arvr/godot_arvr.h
index 657090fa70..d465bbde54 100644
--- a/modules/gdnative/include/arvr/godot_arvr.h
+++ b/modules/gdnative/include/arvr/godot_arvr.h
@@ -64,6 +64,7 @@ typedef struct {
// only in 1.1 onwards
godot_int (*get_external_texture_for_eye)(void *, godot_int);
void (*notification)(void *, godot_int);
+ godot_int (*get_camera_feed_id)(void *);
} godot_arvr_interface_gdnative;
void GDAPI godot_arvr_register_interface(const godot_arvr_interface_gdnative *p_interface);
diff --git a/modules/gdnative/include/gdnative/gdnative.h b/modules/gdnative/include/gdnative/gdnative.h
index 3c457bf5a7..884bcf60d2 100644
--- a/modules/gdnative/include/gdnative/gdnative.h
+++ b/modules/gdnative/include/gdnative/gdnative.h
@@ -67,7 +67,7 @@ extern "C" {
////// Error
typedef enum {
- GODOT_OK,
+ GODOT_OK, // (0)
GODOT_FAILED, ///< Generic fail error
GODOT_ERR_UNAVAILABLE, ///< What is requested is unsupported/unavailable
GODOT_ERR_UNCONFIGURED, ///< The object being used hasn't been properly set up yet
@@ -97,12 +97,12 @@ typedef enum {
GODOT_ERR_CONNECTION_ERROR,
GODOT_ERR_CANT_ACQUIRE_RESOURCE,
GODOT_ERR_CANT_FORK,
- GODOT_ERR_INVALID_DATA, ///< Data passed is invalid (30)
+ GODOT_ERR_INVALID_DATA, ///< Data passed is invalid (30)
GODOT_ERR_INVALID_PARAMETER, ///< Parameter passed is invalid
GODOT_ERR_ALREADY_EXISTS, ///< When adding, item already exists
GODOT_ERR_DOES_NOT_EXIST, ///< When retrieving/erasing, it item does not exist
GODOT_ERR_DATABASE_CANT_READ, ///< database is full
- GODOT_ERR_DATABASE_CANT_WRITE, ///< database is full (35)
+ GODOT_ERR_DATABASE_CANT_WRITE, ///< database is full (35)
GODOT_ERR_COMPILATION_FAILED,
GODOT_ERR_METHOD_NOT_FOUND,
GODOT_ERR_LINK_FAILED,
diff --git a/modules/gdnative/include/gdnative/vector2.h b/modules/gdnative/include/gdnative/vector2.h
index 9e37b8e0c6..7a5ae6afa9 100644
--- a/modules/gdnative/include/gdnative/vector2.h
+++ b/modules/gdnative/include/gdnative/vector2.h
@@ -83,6 +83,8 @@ godot_vector2 GDAPI godot_vector2_linear_interpolate(const godot_vector2 *p_self
godot_vector2 GDAPI godot_vector2_cubic_interpolate(const godot_vector2 *p_self, const godot_vector2 *p_b, const godot_vector2 *p_pre_a, const godot_vector2 *p_post_b, const godot_real p_t);
+godot_vector2 GDAPI godot_vector2_move_toward(const godot_vector2 *p_self, const godot_vector2 *p_to, const godot_real p_delta);
+
godot_vector2 GDAPI godot_vector2_rotated(const godot_vector2 *p_self, const godot_real p_phi);
godot_vector2 GDAPI godot_vector2_tangent(const godot_vector2 *p_self);
diff --git a/modules/gdnative/include/gdnative/vector3.h b/modules/gdnative/include/gdnative/vector3.h
index 61f0c6c62e..70ec6422ac 100644
--- a/modules/gdnative/include/gdnative/vector3.h
+++ b/modules/gdnative/include/gdnative/vector3.h
@@ -90,6 +90,8 @@ godot_vector3 GDAPI godot_vector3_linear_interpolate(const godot_vector3 *p_self
godot_vector3 GDAPI godot_vector3_cubic_interpolate(const godot_vector3 *p_self, const godot_vector3 *p_b, const godot_vector3 *p_pre_a, const godot_vector3 *p_post_b, const godot_real p_t);
+godot_vector3 GDAPI godot_vector3_move_toward(const godot_vector3 *p_self, const godot_vector3 *p_to, const godot_real p_delta);
+
godot_real GDAPI godot_vector3_dot(const godot_vector3 *p_self, const godot_vector3 *p_b);
godot_vector3 GDAPI godot_vector3_cross(const godot_vector3 *p_self, const godot_vector3 *p_b);
diff --git a/modules/gdnative/include/pluginscript/godot_pluginscript.h b/modules/gdnative/include/pluginscript/godot_pluginscript.h
index 968f91ae9f..a9e83d1524 100644
--- a/modules/gdnative/include/pluginscript/godot_pluginscript.h
+++ b/modules/gdnative/include/pluginscript/godot_pluginscript.h
@@ -136,7 +136,7 @@ typedef struct {
godot_bool (*validate)(godot_pluginscript_language_data *p_data, const godot_string *p_script, int *r_line_error, int *r_col_error, godot_string *r_test_error, const godot_string *p_path, godot_pool_string_array *r_functions);
int (*find_function)(godot_pluginscript_language_data *p_data, const godot_string *p_function, const godot_string *p_code); // Can be NULL
godot_string (*make_function)(godot_pluginscript_language_data *p_data, const godot_string *p_class, const godot_string *p_name, const godot_pool_string_array *p_args);
- godot_error (*complete_code)(godot_pluginscript_language_data *p_data, const godot_string *p_code, const godot_string *p_base_path, godot_object *p_owner, godot_array *r_options, godot_bool *r_force, godot_string *r_call_hint);
+ godot_error (*complete_code)(godot_pluginscript_language_data *p_data, const godot_string *p_code, const godot_string *p_path, godot_object *p_owner, godot_array *r_options, godot_bool *r_force, godot_string *r_call_hint);
void (*auto_indent_code)(godot_pluginscript_language_data *p_data, godot_string *p_code, int p_from_line, int p_to_line);
void (*add_global_constant)(godot_pluginscript_language_data *p_data, const godot_string *p_variable, const godot_variant *p_value);
diff --git a/modules/gdnative/nativescript/SCsub b/modules/gdnative/nativescript/SCsub
index 5841ad5531..92c9d6630d 100644
--- a/modules/gdnative/nativescript/SCsub
+++ b/modules/gdnative/nativescript/SCsub
@@ -4,7 +4,6 @@ Import('env')
Import('env_gdnative')
env_gdnative.add_source_files(env.modules_sources, '*.cpp')
-env_gdnative.Append(CPPFLAGS=['-DGDAPI_BUILT_IN'])
if "platform" in env and env["platform"] in ["x11", "iphone"]:
env.Append(LINKFLAGS=["-rdynamic"])
diff --git a/modules/gdnative/nativescript/nativescript.h b/modules/gdnative/nativescript/nativescript.h
index be1c499714..79a41df107 100644
--- a/modules/gdnative/nativescript/nativescript.h
+++ b/modules/gdnative/nativescript/nativescript.h
@@ -99,7 +99,7 @@ struct NativeScriptDesc {
};
class NativeScript : public Script {
- GDCLASS(NativeScript, Script)
+ GDCLASS(NativeScript, Script);
#ifdef TOOLS_ENABLED
Set<PlaceHolderScriptInstance *> placeholders;
@@ -370,7 +370,7 @@ inline NativeScriptDesc *NativeScript::get_script_desc() const {
}
class NativeReloadNode : public Node {
- GDCLASS(NativeReloadNode, Node)
+ GDCLASS(NativeReloadNode, Node);
bool unloaded;
public:
@@ -382,7 +382,6 @@ public:
};
class ResourceFormatLoaderNativeScript : public ResourceFormatLoader {
- GDCLASS(ResourceFormatLoaderNativeScript, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
@@ -391,7 +390,6 @@ public:
};
class ResourceFormatSaverNativeScript : public ResourceFormatSaver {
- GDCLASS(ResourceFormatSaverNativeScript, ResourceFormatSaver)
virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0);
virtual bool recognize(const RES &p_resource) const;
virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const;
diff --git a/modules/gdnative/net/multiplayer_peer_gdnative.cpp b/modules/gdnative/net/multiplayer_peer_gdnative.cpp
index bdeba149d2..d2c95efa77 100644
--- a/modules/gdnative/net/multiplayer_peer_gdnative.cpp
+++ b/modules/gdnative/net/multiplayer_peer_gdnative.cpp
@@ -113,6 +113,8 @@ NetworkedMultiplayerPeer::ConnectionStatus MultiplayerPeerGDNative::get_connecti
}
void MultiplayerPeerGDNative::_bind_methods() {
+ ADD_PROPERTY_DEFAULT("transfer_mode", TRANSFER_MODE_UNRELIABLE);
+ ADD_PROPERTY_DEFAULT("refuse_new_connections", true);
}
extern "C" {
diff --git a/modules/gdnative/net/multiplayer_peer_gdnative.h b/modules/gdnative/net/multiplayer_peer_gdnative.h
index 7d48dc60d1..6fbc62aaa1 100644
--- a/modules/gdnative/net/multiplayer_peer_gdnative.h
+++ b/modules/gdnative/net/multiplayer_peer_gdnative.h
@@ -36,7 +36,7 @@
#include "modules/gdnative/include/net/godot_net.h"
class MultiplayerPeerGDNative : public NetworkedMultiplayerPeer {
- GDCLASS(MultiplayerPeerGDNative, NetworkedMultiplayerPeer)
+ GDCLASS(MultiplayerPeerGDNative, NetworkedMultiplayerPeer);
protected:
static void _bind_methods();
diff --git a/modules/gdnative/net/packet_peer_gdnative.h b/modules/gdnative/net/packet_peer_gdnative.h
index 742fa4e7d5..8483217210 100644
--- a/modules/gdnative/net/packet_peer_gdnative.h
+++ b/modules/gdnative/net/packet_peer_gdnative.h
@@ -36,7 +36,7 @@
#include "modules/gdnative/include/net/godot_net.h"
class PacketPeerGDNative : public PacketPeer {
- GDCLASS(PacketPeerGDNative, PacketPeer)
+ GDCLASS(PacketPeerGDNative, PacketPeer);
protected:
static void _bind_methods();
diff --git a/modules/gdnative/pluginscript/pluginscript_language.cpp b/modules/gdnative/pluginscript/pluginscript_language.cpp
index c9d92c09ed..9de073fc8e 100644
--- a/modules/gdnative/pluginscript/pluginscript_language.cpp
+++ b/modules/gdnative/pluginscript/pluginscript_language.cpp
@@ -159,19 +159,20 @@ String PluginScriptLanguage::make_function(const String &p_class, const String &
return String();
}
-Error PluginScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_force, String &r_call_hint) {
+Error PluginScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_force, String &r_call_hint) {
if (_desc.complete_code) {
Array options;
godot_error tmp = _desc.complete_code(
_data,
(godot_string *)&p_code,
- (godot_string *)&p_base_path,
+ (godot_string *)&p_path,
(godot_object *)p_owner,
(godot_array *)&options,
&r_force,
(godot_string *)&r_call_hint);
for (int i = 0; i < options.size(); i++) {
- r_options->push_back(String(options[i]));
+ ScriptCodeCompletionOption option(options[i], ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ r_options->push_back(option);
}
return (Error)tmp;
}
@@ -216,7 +217,7 @@ void PluginScriptLanguage::get_public_constants(List<Pair<String, Variant> > *p_
Dictionary constants;
_desc.get_public_constants(_data, (godot_dictionary *)&constants);
for (const Variant *key = constants.next(); key; key = constants.next(key)) {
- Variant value = constants[key];
+ Variant value = constants[*key];
p_constants->push_back(Pair<String, Variant>(*key, value));
}
}
diff --git a/modules/gdnative/pluginscript/pluginscript_language.h b/modules/gdnative/pluginscript/pluginscript_language.h
index 991be0bf12..7b3844d0b0 100644
--- a/modules/gdnative/pluginscript/pluginscript_language.h
+++ b/modules/gdnative/pluginscript/pluginscript_language.h
@@ -81,7 +81,7 @@ public:
virtual bool can_inherit_from_file() { return true; }
virtual int find_function(const String &p_function, const String &p_code) const;
virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const;
- virtual Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_force, String &r_call_hint);
+ virtual Error complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_force, String &r_call_hint);
virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const;
virtual void add_global_constant(const StringName &p_variable, const Variant &p_value);
diff --git a/modules/gdnative/pluginscript/pluginscript_loader.h b/modules/gdnative/pluginscript/pluginscript_loader.h
index 69a2ac6bfe..6218037a15 100644
--- a/modules/gdnative/pluginscript/pluginscript_loader.h
+++ b/modules/gdnative/pluginscript/pluginscript_loader.h
@@ -40,8 +40,6 @@ class PluginScriptLanguage;
class ResourceFormatLoaderPluginScript : public ResourceFormatLoader {
- GDCLASS(ResourceFormatLoaderPluginScript, ResourceFormatLoader)
-
PluginScriptLanguage *_language;
public:
@@ -54,8 +52,6 @@ public:
class ResourceFormatSaverPluginScript : public ResourceFormatSaver {
- GDCLASS(ResourceFormatSaverPluginScript, ResourceFormatSaver)
-
PluginScriptLanguage *_language;
public:
diff --git a/modules/gdnative/pluginscript/pluginscript_script.cpp b/modules/gdnative/pluginscript/pluginscript_script.cpp
index 8dbbd2e4eb..3ecb29404a 100644
--- a/modules/gdnative/pluginscript/pluginscript_script.cpp
+++ b/modules/gdnative/pluginscript/pluginscript_script.cpp
@@ -39,12 +39,12 @@
#define ASSERT_SCRIPT_VALID() \
{ \
ERR_EXPLAIN(__ASSERT_SCRIPT_REASON); \
- ERR_FAIL_COND(!can_instance()) \
+ ERR_FAIL_COND(!can_instance()); \
}
-#define ASSERT_SCRIPT_VALID_V(ret) \
- { \
- ERR_EXPLAIN(__ASSERT_SCRIPT_REASON); \
- ERR_FAIL_COND_V(!can_instance(), ret) \
+#define ASSERT_SCRIPT_VALID_V(ret) \
+ { \
+ ERR_EXPLAIN(__ASSERT_SCRIPT_REASON); \
+ ERR_FAIL_COND_V(!can_instance(), ret); \
}
#else
#define ASSERT_SCRIPT_VALID()
@@ -77,7 +77,7 @@ PluginScriptInstance *PluginScript::_create_instance(const Variant **p_args, int
// There is currently no way to get the constructor function name of the script.
// instance->call("__init__", p_args, p_argcount, r_error);
if (p_argcount > 0) {
- WARN_PRINT("PluginScript doesn't support arguments in the constructor")
+ WARN_PRINT("PluginScript doesn't support arguments in the constructor");
}
return instance;
@@ -229,6 +229,8 @@ void PluginScript::set_source_code(const String &p_code) {
}
Error PluginScript::reload(bool p_keep_state) {
+ ERR_FAIL_COND_V(!_language, ERR_UNCONFIGURED);
+
_language->lock();
ERR_FAIL_COND_V(!p_keep_state && _instances.size(), ERR_ALREADY_IN_USE);
_language->unlock();
@@ -284,7 +286,7 @@ Error PluginScript::reload(bool p_keep_state) {
Dictionary *members = (Dictionary *)&manifest.member_lines;
for (const Variant *key = members->next(); key != NULL; key = members->next(key)) {
- _member_lines[*key] = (*members)[key];
+ _member_lines[*key] = (*members)[*key];
}
Array *methods = (Array *)&manifest.methods;
for (int i = 0; i < methods->size(); ++i) {
@@ -473,6 +475,8 @@ MultiplayerAPI::RPCMode PluginScript::get_rset_mode(const StringName &p_variable
PluginScript::PluginScript() :
_data(NULL),
+ _desc(NULL),
+ _language(NULL),
_tool(false),
_valid(false),
_script_list(this) {
@@ -490,11 +494,15 @@ void PluginScript::init(PluginScriptLanguage *language) {
}
PluginScript::~PluginScript() {
- _desc->finish(_data);
+ if (_desc && _data) {
+ _desc->finish(_data);
+ }
#ifdef DEBUG_ENABLED
- _language->lock();
- _language->_script_list.remove(&_script_list);
- _language->unlock();
+ if (_language) {
+ _language->lock();
+ _language->_script_list.remove(&_script_list);
+ _language->unlock();
+ }
#endif
}
diff --git a/modules/gdnative/register_types.cpp b/modules/gdnative/register_types.cpp
index 55d44ceec8..6ff6262b56 100644
--- a/modules/gdnative/register_types.cpp
+++ b/modules/gdnative/register_types.cpp
@@ -100,6 +100,11 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty
}
String entry_lib_path = config->get_value("entry", key);
+ if (!entry_lib_path.begins_with("res://")) {
+ print_line("Skipping export of out-of-project library " + entry_lib_path);
+ continue;
+ }
+
add_shared_object(entry_lib_path, tags);
}
}
@@ -129,6 +134,10 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty
Vector<String> dependency_paths = config->get_value("dependencies", key);
for (int i = 0; i < dependency_paths.size(); i++) {
+ if (!dependency_paths[i].begins_with("res://")) {
+ print_line("Skipping export of out-of-project library " + dependency_paths[i]);
+ continue;
+ }
add_shared_object(dependency_paths[i], tags);
}
}
diff --git a/modules/gdnative/videodecoder/video_stream_gdnative.h b/modules/gdnative/videodecoder/video_stream_gdnative.h
index aafd02f33d..b9f1c8e4da 100644
--- a/modules/gdnative/videodecoder/video_stream_gdnative.h
+++ b/modules/gdnative/videodecoder/video_stream_gdnative.h
@@ -197,7 +197,6 @@ public:
};
class ResourceFormatLoaderVideoStreamGDNative : public ResourceFormatLoader {
- GDCLASS(ResourceFormatLoaderVideoStreamGDNative, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/gdscript/config.py b/modules/gdscript/config.py
index 95b40d90af..a525eedaaa 100644
--- a/modules/gdscript/config.py
+++ b/modules/gdscript/config.py
@@ -6,6 +6,7 @@ def configure(env):
def get_doc_classes():
return [
+ "@GDScript",
"GDScript",
"GDScriptFunctionState",
"GDScriptNativeClass",
diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml
new file mode 100644
index 0000000000..a21b6a2907
--- /dev/null
+++ b/modules/gdscript/doc_classes/@GDScript.xml
@@ -0,0 +1,1347 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="@GDScript" category="Core" version="3.2">
+ <brief_description>
+ Built-in GDScript functions.
+ </brief_description>
+ <description>
+ List of core built-in GDScript functions. Math functions and other utilities. Everything else is provided by objects. (Keywords: builtin, built in, global functions.)
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="Color8">
+ <return type="Color">
+ </return>
+ <argument index="0" name="r8" type="int">
+ </argument>
+ <argument index="1" name="g8" type="int">
+ </argument>
+ <argument index="2" name="b8" type="int">
+ </argument>
+ <argument index="3" name="a8" type="int" default="255">
+ </argument>
+ <description>
+ Returns a 32 bit color with red, green, blue and alpha channels. Each channel has 8 bits of information ranging from 0 to 255.
+ [code]r8[/code] red channel
+ [code]g8[/code] green channel
+ [code]b8[/code] blue channel
+ [code]a8[/code] alpha channel
+ [codeblock]
+ red = Color8(255, 0, 0)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="ColorN">
+ <return type="Color">
+ </return>
+ <argument index="0" name="name" type="String">
+ </argument>
+ <argument index="1" name="alpha" type="float" default="1.0">
+ </argument>
+ <description>
+ Returns a color according to the standardised [code]name[/code] with [code]alpha[/code] ranging from 0 to 1.
+ [codeblock]
+ red = ColorN("red", 1)
+ [/codeblock]
+ Supported color names:
+ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflower", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "webgray", "green", "webgreen", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrod", "lightgray", "lightgreen", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "webmaroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navyblue", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "webpurple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen".
+ </description>
+ </method>
+ <method name="abs">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the absolute value of parameter [code]s[/code] (i.e. unsigned value, works for integer and float).
+ [codeblock]
+ # a is 1
+ a = abs(-1)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="acos">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the arc cosine of [code]s[/code] in radians. Use to get the angle of cosine [code]s[/code].
+ [codeblock]
+ # c is 0.523599 or 30 degrees if converted with rad2deg(s)
+ c = acos(0.866025)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="asin">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the arc sine of [code]s[/code] in radians. Use to get the angle of sine [code]s[/code].
+ [codeblock]
+ # s is 0.523599 or 30 degrees if converted with rad2deg(s)
+ s = asin(0.5)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="assert">
+ <return type="void">
+ </return>
+ <argument index="0" name="condition" type="bool">
+ </argument>
+ <description>
+ Asserts that the [code]condition[/code] is [code]true[/code] . If the [code]condition[/code] is [code]false[/code], an error is generated and the program is halted until you resume it. Only executes in debug builds, or when running the game from the editor. Use it for debugging purposes, to make sure a statement is [code]true[/code] during development.
+ [codeblock]
+ # Imagine we always want speed to be between 0 and 20
+ speed = -10
+ assert(speed &lt; 20) # True, the program will continue
+ assert(speed &gt;= 0) # False, the program will stop
+ assert(speed &gt;= 0 &amp;&amp; speed &lt; 20) # You can also combine the two conditional statements in one check
+ [/codeblock]
+ </description>
+ </method>
+ <method name="atan">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the arc tangent of [code]s[/code] in radians. Use it to get the angle from an angle's tangent in trigonometry: [code]atan(tan(angle)) == angle[/code].
+ The method cannot know in which quadrant the angle should fall. See [method atan2] if you always want an exact angle.
+ [codeblock]
+ a = atan(0.5) # a is 0.463648
+ [/codeblock]
+ </description>
+ </method>
+ <method name="atan2">
+ <return type="float">
+ </return>
+ <argument index="0" name="y" type="float">
+ </argument>
+ <argument index="1" name="x" type="float">
+ </argument>
+ <description>
+ Returns the arc tangent of [code]y/x[/code] in radians. Use to get the angle of tangent [code]y/x[/code]. To compute the value, the method takes into account the sign of both arguments in order to determine the quadrant.
+ [codeblock]
+ a = atan2(0, -1) # a is 3.141593
+ [/codeblock]
+ </description>
+ </method>
+ <method name="bytes2var">
+ <return type="Variant">
+ </return>
+ <argument index="0" name="bytes" type="PoolByteArray">
+ </argument>
+ <argument index="1" name="allow_objects" type="bool" default="false">
+ </argument>
+ <description>
+ Decodes a byte array back to a value. When [code]allow_objects[/code] is [code]true[/code] decoding objects is allowed.
+ [b]WARNING:[/b] Deserialized object can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats (remote code execution).
+ </description>
+ </method>
+ <method name="cartesian2polar">
+ <return type="Vector2">
+ </return>
+ <argument index="0" name="x" type="float">
+ </argument>
+ <argument index="1" name="y" type="float">
+ </argument>
+ <description>
+ Converts a 2D point expressed in the cartesian coordinate system (X and Y axis) to the polar coordinate system (a distance from the origin and an angle).
+ </description>
+ </method>
+ <method name="ceil">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Rounds [code]s[/code] upward, returning the smallest integral value that is not less than [code]s[/code].
+ [codeblock]
+ i = ceil(1.45) # i is 2
+ i = ceil(1.001) # i is 2
+ [/codeblock]
+ </description>
+ </method>
+ <method name="char">
+ <return type="String">
+ </return>
+ <argument index="0" name="ascii" type="int">
+ </argument>
+ <description>
+ Returns a character as a String of the given ASCII code.
+ [codeblock]
+ a = char(65) # a is "A"
+ a = char(65 + 32) # a is "a"
+ [/codeblock]
+ </description>
+ </method>
+ <method name="clamp">
+ <return type="float">
+ </return>
+ <argument index="0" name="value" type="float">
+ </argument>
+ <argument index="1" name="min" type="float">
+ </argument>
+ <argument index="2" name="max" type="float">
+ </argument>
+ <description>
+ Clamps [code]value[/code] and returns a value not less than [code]min[/code] and not more than [code]max[/code].
+ [codeblock]
+ speed = 1000
+ # a is 20
+ a = clamp(speed, 1, 20)
+
+ speed = -10
+ # a is 1
+ a = clamp(speed, 1, 20)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="convert">
+ <return type="Variant">
+ </return>
+ <argument index="0" name="what" type="Variant">
+ </argument>
+ <argument index="1" name="type" type="int">
+ </argument>
+ <description>
+ Converts from a type to another in the best way possible. The [code]type[/code] parameter uses the enum [code]TYPE_*[/code] in [@GlobalScope].
+ [codeblock]
+ a = Vector2(1, 0)
+ # Prints 1
+ print(a.length())
+ a = convert(a, TYPE_STRING)
+ # Prints 6 as "(1, 0)" is 6 characters
+ print(a.length())
+ [/codeblock]
+ </description>
+ </method>
+ <method name="cos">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the cosine of angle [code]s[/code] in radians.
+ [codeblock]
+ # Prints 1 then -1
+ print(cos(PI * 2))
+ print(cos(PI))
+ [/codeblock]
+ </description>
+ </method>
+ <method name="cosh">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the hyperbolic cosine of [code]s[/code] in radians.
+ [codeblock]
+ # Prints 1.543081
+ print(cosh(1))
+ [/codeblock]
+ </description>
+ </method>
+ <method name="db2linear">
+ <return type="float">
+ </return>
+ <argument index="0" name="db" type="float">
+ </argument>
+ <description>
+ Converts from decibels to linear energy (audio).
+ </description>
+ </method>
+ <method name="decimals">
+ <return type="int">
+ </return>
+ <argument index="0" name="step" type="float">
+ </argument>
+ <description>
+ Deprecated alias for [method step_decimals].
+ </description>
+ </method>
+ <method name="dectime">
+ <return type="float">
+ </return>
+ <argument index="0" name="value" type="float">
+ </argument>
+ <argument index="1" name="amount" type="float">
+ </argument>
+ <argument index="2" name="step" type="float">
+ </argument>
+ <description>
+ Returns the result of [code]value[/code] decreased by [code]step[/code] * [code]amount[/code].
+ [codeblock]
+ # a = 59
+ a = dectime(60, 10, 0.1))
+ [/codeblock]
+ </description>
+ </method>
+ <method name="deg2rad">
+ <return type="float">
+ </return>
+ <argument index="0" name="deg" type="float">
+ </argument>
+ <description>
+ Returns degrees converted to radians.
+ [codeblock]
+ # r is 3.141593
+ r = deg2rad(180)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="dict2inst">
+ <return type="Object">
+ </return>
+ <argument index="0" name="dict" type="Dictionary">
+ </argument>
+ <description>
+ Converts a previously converted instance to a dictionary, back into an instance. Useful for deserializing.
+ </description>
+ </method>
+ <method name="ease">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <argument index="1" name="curve" type="float">
+ </argument>
+ <description>
+ Easing function, based on exponent. 0 is constant, 1 is linear, 0 to 1 is ease-in, 1+ is ease out. Negative values are in-out/out in.
+ </description>
+ </method>
+ <method name="exp">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ The natural exponential function. It raises the mathematical constant [b]e[/b] to the power of [code]s[/code] and returns it.
+ [b]e[/b] has an approximate value of 2.71828.
+ [codeblock]
+ a = exp(2) # Approximately 7.39
+ [/codeblock]
+ </description>
+ </method>
+ <method name="floor">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Rounds [code]s[/code] to the closest smaller integer and returns it.
+ [codeblock]
+ # a is 2
+ a = floor(2.99)
+ # a is -3
+ a = floor(-2.99)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="fmod">
+ <return type="float">
+ </return>
+ <argument index="0" name="a" type="float">
+ </argument>
+ <argument index="1" name="b" type="float">
+ </argument>
+ <description>
+ Returns the floating-point remainder of [code]a/b[/code], keeping the sign of [code]a[/code].
+ [codeblock]
+ # Remainder is 1.5
+ var remainder = fmod(7, 5.5)
+ [/codeblock]
+ For the integer remainder operation, use the % operator.
+ </description>
+ </method>
+ <method name="fposmod">
+ <return type="float">
+ </return>
+ <argument index="0" name="a" type="float">
+ </argument>
+ <argument index="1" name="b" type="float">
+ </argument>
+ <description>
+ Returns the floating-point modulus of [code]a/b[/code] that wraps equally in positive and negative.
+ [codeblock]
+ var i = -6
+ while i &lt; 5:
+ prints(i, fposmod(i, 3))
+ i += 1
+ [/codeblock]
+ Produces:
+ [codeblock]
+ -6 0
+ -5 1
+ -4 2
+ -3 0
+ -2 1
+ -1 2
+ 0 0
+ 1 1
+ 2 2
+ 3 0
+ 4 1
+ [/codeblock]
+ </description>
+ </method>
+ <method name="posmod">
+ <return type="int">
+ </return>
+ <argument index="0" name="a" type="int">
+ </argument>
+ <argument index="1" name="b" type="int">
+ </argument>
+ <description>
+ Returns the integer modulus of [code]a/b[/code] that wraps equally in positive and negative.
+ [codeblock]
+ var i = -6
+ while i &lt; 5:
+ prints(i, posmod(i, 3))
+ i += 1
+ [/codeblock]
+ Produces:
+ [codeblock]
+ -6 0
+ -5 1
+ -4 2
+ -3 0
+ -2 1
+ -1 2
+ 0 0
+ 1 1
+ 2 2
+ 3 0
+ 4 1
+ [/codeblock]
+ </description>
+ </method>
+ <method name="funcref">
+ <return type="FuncRef">
+ </return>
+ <argument index="0" name="instance" type="Object">
+ </argument>
+ <argument index="1" name="funcname" type="String">
+ </argument>
+ <description>
+ Returns a reference to the specified function [code]funcname[/code] in the [code]instance[/code] node. As functions aren't first-class objects in GDscript, use [code]funcref[/code] to store a [FuncRef] in a variable and call it later.
+ [codeblock]
+ func foo():
+ return("bar")
+
+ a = funcref(self, "foo")
+ print(a.call_func()) # Prints bar
+ [/codeblock]
+ </description>
+ </method>
+ <method name="get_stack">
+ <return type="Array">
+ </return>
+ <description>
+ Returns an array of dictionaries representing the current call stack.
+ [codeblock]
+ func _ready():
+ foo()
+
+ func foo():
+ bar()
+
+ func bar():
+ print(get_stack())
+ [/codeblock]
+ would print
+ [codeblock]
+ [{function:bar, line:12, source:res://script.gd}, {function:foo, line:9, source:res://script.gd}, {function:_ready, line:6, source:res://script.gd}]
+ [/codeblock]
+ </description>
+ </method>
+ <method name="hash">
+ <return type="int">
+ </return>
+ <argument index="0" name="var" type="Variant">
+ </argument>
+ <description>
+ Returns the integer hash of the variable passed.
+ [codeblock]
+ print(hash("a")) # Prints 177670
+ [/codeblock]
+ </description>
+ </method>
+ <method name="inst2dict">
+ <return type="Dictionary">
+ </return>
+ <argument index="0" name="inst" type="Object">
+ </argument>
+ <description>
+ Returns the passed instance converted to a dictionary (useful for serializing).
+ [codeblock]
+ var foo = "bar"
+ func _ready():
+ var d = inst2dict(self)
+ print(d.keys())
+ print(d.values())
+ [/codeblock]
+ Prints out:
+ [codeblock]
+ [@subpath, @path, foo]
+ [, res://test.gd, bar]
+ [/codeblock]
+ </description>
+ </method>
+ <method name="instance_from_id">
+ <return type="Object">
+ </return>
+ <argument index="0" name="instance_id" type="int">
+ </argument>
+ <description>
+ Returns the Object that corresponds to [code]instance_id[/code]. All Objects have a unique instance ID.
+ [codeblock]
+ var foo = "bar"
+ func _ready():
+ var id = get_instance_id()
+ var inst = instance_from_id(id)
+ print(inst.foo) # Prints bar
+ [/codeblock]
+ </description>
+ </method>
+ <method name="inverse_lerp">
+ <return type="float">
+ </return>
+ <argument index="0" name="from" type="float">
+ </argument>
+ <argument index="1" name="to" type="float">
+ </argument>
+ <argument index="2" name="weight" type="float">
+ </argument>
+ <description>
+ Returns a normalized value considering the given range.
+ [codeblock]
+ inverse_lerp(3, 5, 4) # Returns 0.5
+ [/codeblock]
+ </description>
+ </method>
+ <method name="is_equal_approx">
+ <return type="bool">
+ </return>
+ <argument index="0" name="a" type="float">
+ </argument>
+ <argument index="1" name="b" type="float">
+ </argument>
+ <description>
+ Returns True/False whether [code]a[/code] and [code]b[/code] are approximately equal to each other.
+ </description>
+ </method>
+ <method name="is_inf">
+ <return type="bool">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns whether [code]s[/code] is an infinity value (either positive infinity or negative infinity).
+ </description>
+ </method>
+ <method name="is_instance_valid">
+ <return type="bool">
+ </return>
+ <argument index="0" name="instance" type="Object">
+ </argument>
+ <description>
+ Returns whether [code]instance[/code] is a valid object (e.g. has not been deleted from memory).
+ </description>
+ </method>
+ <method name="is_nan">
+ <return type="bool">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns whether [code]s[/code] is a NaN (Not-A-Number) value.
+ </description>
+ </method>
+ <method name="is_zero_approx">
+ <return type="bool">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns True/False whether [code]s[/code] is zero or almost zero.
+ </description>
+ </method>
+ <method name="len">
+ <return type="int">
+ </return>
+ <argument index="0" name="var" type="Variant">
+ </argument>
+ <description>
+ Returns length of Variant [code]var[/code]. Length is the character count of String, element count of Array, size of Dictionary, etc.
+ [b]Note:[/b] Generates a fatal error if Variant can not provide a length.
+ [codeblock]
+ a = [1, 2, 3, 4]
+ len(a) # Returns 4
+ [/codeblock]
+ </description>
+ </method>
+ <method name="lerp">
+ <return type="Variant">
+ </return>
+ <argument index="0" name="from" type="Variant">
+ </argument>
+ <argument index="1" name="to" type="Variant">
+ </argument>
+ <argument index="2" name="weight" type="float">
+ </argument>
+ <description>
+ Linearly interpolates between two values by a normalized value.
+ If the [code]from[/code] and [code]to[/code] arguments are of type [int] or [float], the return value is a [float].
+ If both are of the same vector type ([Vector2], [Vector3] or [Color]), the return value will be of the same type ([code]lerp[/code] then calls the vector type's [code]linear_interpolate[/code] method).
+ [codeblock]
+ lerp(0, 4, 0.75) # Returns 3.0
+ lerp(Vector2(1, 5), Vector2(3, 2), 0.5) # Returns Vector2(2, 3.5)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="linear2db">
+ <return type="float">
+ </return>
+ <argument index="0" name="nrg" type="float">
+ </argument>
+ <description>
+ Converts from linear energy to decibels (audio).
+ </description>
+ </method>
+ <method name="load">
+ <return type="Resource">
+ </return>
+ <argument index="0" name="path" type="String">
+ </argument>
+ <description>
+ Loads a resource from the filesystem located at [code]path[/code].
+ [b]Note:[/b] Resource paths can be obtained by right-clicking on a resource in the FileSystem dock and choosing [b]Copy Path[/b].
+ [codeblock]
+ # Load a scene called main located in the root of the project directory
+ var main = load("res://main.tscn")
+ [/codeblock]
+ </description>
+ </method>
+ <method name="log">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Natural logarithm. The amount of time needed to reach a certain level of continuous growth.
+ [b]Note:[/b] This is not the same as the "log" function on most calculators, which uses a base 10 logarithm.
+ [codeblock]
+ log(10) # Returns 2.302585
+ [/codeblock]
+ </description>
+ </method>
+ <method name="max">
+ <return type="float">
+ </return>
+ <argument index="0" name="a" type="float">
+ </argument>
+ <argument index="1" name="b" type="float">
+ </argument>
+ <description>
+ Returns the maximum of two values.
+ [codeblock]
+ max(1, 2) # Returns 2
+ max(-3.99, -4) # Returns -3.99
+ [/codeblock]
+ </description>
+ </method>
+ <method name="min">
+ <return type="float">
+ </return>
+ <argument index="0" name="a" type="float">
+ </argument>
+ <argument index="1" name="b" type="float">
+ </argument>
+ <description>
+ Returns the minimum of two values.
+ [codeblock]
+ min(1, 2) # Returns 1
+ min(-3.99, -4) # Returns -4
+ [/codeblock]
+ </description>
+ </method>
+ <method name="move_toward">
+ <return type="float">
+ </return>
+ <argument index="0" name="from" type="float">
+ </argument>
+ <argument index="1" name="to" type="float">
+ </argument>
+ <argument index="2" name="delta" type="float">
+ </argument>
+ <description>
+ Moves [code]from[/code] toward [code]to[/code] by the [code]delta[/code] value.
+ Use a negative [code]delta[/code] value to move away.
+ [codeblock]
+ move_toward(10, 5, 4) # Returns 6
+ [/codeblock]
+ </description>
+ </method>
+ <method name="nearest_po2">
+ <return type="int">
+ </return>
+ <argument index="0" name="value" type="int">
+ </argument>
+ <description>
+ Returns the nearest larger power of 2 for integer [code]value[/code].
+ [codeblock]
+ nearest_po2(3) # Returns 4
+ nearest_po2(4) # Returns 4
+ nearest_po2(5) # Returns 8
+ [/codeblock]
+ </description>
+ </method>
+ <method name="parse_json">
+ <return type="Variant">
+ </return>
+ <argument index="0" name="json" type="String">
+ </argument>
+ <description>
+ Parse JSON text to a Variant (use [method typeof] to check if it is what you expect).
+ Be aware that the JSON specification does not define integer or float types, but only a number type. Therefore, parsing a JSON text will convert all numerical values to [float] types.
+ Note that JSON objects do not preserve key order like Godot dictionaries, thus you should not rely on keys being in a certain order if a dictionary is constructed from JSON. In contrast, JSON arrays retain the order of their elements:
+ [codeblock]
+ p = parse_json('["a", "b", "c"]')
+ if typeof(p) == TYPE_ARRAY:
+ print(p[0]) # Prints a
+ else:
+ print("unexpected results")
+ [/codeblock]
+ </description>
+ </method>
+ <method name="polar2cartesian">
+ <return type="Vector2">
+ </return>
+ <argument index="0" name="r" type="float">
+ </argument>
+ <argument index="1" name="th" type="float">
+ </argument>
+ <description>
+ Converts a 2D point expressed in the polar coordinate system (a distance from the origin [code]r[/code] and an angle [code]th[/code]) to the cartesian coordinate system (X and Y axis).
+ </description>
+ </method>
+ <method name="pow">
+ <return type="float">
+ </return>
+ <argument index="0" name="x" type="float">
+ </argument>
+ <argument index="1" name="y" type="float">
+ </argument>
+ <description>
+ Returns the result of [code]x[/code] raised to the power of [code]y[/code].
+ [codeblock]
+ pow(2, 5) # Returns 32
+ [/codeblock]
+ </description>
+ </method>
+ <method name="preload">
+ <return type="Resource">
+ </return>
+ <argument index="0" name="path" type="String">
+ </argument>
+ <description>
+ Returns a resource from the filesystem that is loaded during script parsing.
+ [b]Note:[/b] Resource paths can be obtained by right clicking on a resource in the Assets Panel and choosing "Copy Path".
+ [codeblock]
+ # Load a scene called main located in the root of the project directory
+ var main = preload("res://main.tscn")
+ [/codeblock]
+ </description>
+ </method>
+ <method name="print" qualifiers="vararg">
+ <return type="void">
+ </return>
+ <description>
+ Converts one or more arguments to strings in the best way possible and prints them to the console.
+ [codeblock]
+ a = [1, 2, 3]
+ print("a", "b", a) # Prints ab[1, 2, 3]
+ [/codeblock]
+ </description>
+ </method>
+ <method name="print_debug" qualifiers="vararg">
+ <return type="void">
+ </return>
+ <description>
+ Like [method print], but prints only when used in debug mode.
+ </description>
+ </method>
+ <method name="print_stack">
+ <return type="void">
+ </return>
+ <description>
+ Prints a stack track at code location, only works when running with debugger turned on.
+ Output in the console would look something like this:
+ [codeblock]
+ Frame 0 - res://test.gd:16 in function '_process'
+ [/codeblock]
+ </description>
+ </method>
+ <method name="printerr" qualifiers="vararg">
+ <return type="void">
+ </return>
+ <description>
+ Prints one or more arguments to strings in the best way possible to standard error line.
+ [codeblock]
+ printerr("prints to stderr")
+ [/codeblock]
+ </description>
+ </method>
+ <method name="printraw" qualifiers="vararg">
+ <return type="void">
+ </return>
+ <description>
+ Prints one or more arguments to strings in the best way possible to console. No newline is added at the end.
+ [codeblock]
+ printraw("A")
+ printraw("B")
+ # Prints AB
+ [/codeblock]
+ </description>
+ </method>
+ <method name="prints" qualifiers="vararg">
+ <return type="void">
+ </return>
+ <description>
+ Prints one or more arguments to the console with a space between each argument.
+ [codeblock]
+ prints("A", "B", "C") # Prints A B C
+ [/codeblock]
+ </description>
+ </method>
+ <method name="printt" qualifiers="vararg">
+ <return type="void">
+ </return>
+ <description>
+ Prints one or more arguments to the console with a tab between each argument.
+ [codeblock]
+ printt("A", "B", "C") # Prints A B C
+ [/codeblock]
+ </description>
+ </method>
+ <method name="push_error">
+ <return type="void">
+ </return>
+ <argument index="0" name="message" type="String">
+ </argument>
+ <description>
+ Pushes an error message to Godot's built-in debugger and to the OS terminal.
+ [codeblock]
+ push_error("test error") # Prints "test error" to debugger and terminal as error call
+ [/codeblock]
+ </description>
+ </method>
+ <method name="push_warning">
+ <return type="void">
+ </return>
+ <argument index="0" name="message" type="String">
+ </argument>
+ <description>
+ Pushes a warning message to Godot's built-in debugger and to the OS terminal.
+ [codeblock]
+ push_warning("test warning") # Prints "test warning" to debugger and terminal as warning call
+ [/codeblock]
+ </description>
+ </method>
+ <method name="rad2deg">
+ <return type="float">
+ </return>
+ <argument index="0" name="rad" type="float">
+ </argument>
+ <description>
+ Converts from radians to degrees.
+ [codeblock]
+ rad2deg(0.523599) # Returns 30
+ [/codeblock]
+ </description>
+ </method>
+ <method name="rand_range">
+ <return type="float">
+ </return>
+ <argument index="0" name="from" type="float">
+ </argument>
+ <argument index="1" name="to" type="float">
+ </argument>
+ <description>
+ Random range, any floating point value between [code]from[/code] and [code]to[/code].
+ [codeblock]
+ prints(rand_range(0, 1), rand_range(0, 1)) # Prints e.g. 0.135591 0.405263
+ [/codeblock]
+ </description>
+ </method>
+ <method name="rand_seed">
+ <return type="Array">
+ </return>
+ <argument index="0" name="seed" type="int">
+ </argument>
+ <description>
+ Random from seed: pass a [code]seed[/code], and an array with both number and new seed is returned. "Seed" here refers to the internal state of the pseudo random number generator. The internal state of the current implementation is 64 bits.
+ </description>
+ </method>
+ <method name="randf">
+ <return type="float">
+ </return>
+ <description>
+ Returns a random floating point value on the interval [code][0, 1][/code].
+ [codeblock]
+ randf() # Returns e.g. 0.375671
+ [/codeblock]
+ </description>
+ </method>
+ <method name="randi">
+ <return type="int">
+ </return>
+ <description>
+ Returns a random unsigned 32 bit integer. Use remainder to obtain a random value in the interval [code][0, N][/code] (where N is smaller than 2^32 -1).
+ [codeblock]
+ randi() # Returns random integer between 0 and 2^32 - 1
+ randi() % 20 # Returns random integer between 0 and 19
+ randi() % 100 # Returns random integer between 0 and 99
+ randi() % 100 + 1 # Returns random integer between 1 and 100
+ [/codeblock]
+ </description>
+ </method>
+ <method name="randomize">
+ <return type="void">
+ </return>
+ <description>
+ Randomizes the seed (or the internal state) of the random number generator. Current implementation reseeds using a number based on time.
+ [codeblock]
+ func _ready():
+ randomize()
+ [/codeblock]
+ </description>
+ </method>
+ <method name="range" qualifiers="vararg">
+ <return type="Array">
+ </return>
+ <description>
+ Returns an array with the given range. Range can be 1 argument N (0 to N-1), two arguments (initial, final-1) or three arguments (initial, final-1, increment).
+ [codeblock]
+ for i in range(4):
+ print(i)
+ for i in range(2, 5):
+ print(i)
+ for i in range(0, 6, 2):
+ print(i)
+ [/codeblock]
+ Output:
+ [codeblock]
+ 0
+ 1
+ 2
+ 3
+
+ 2
+ 3
+ 4
+
+ 0
+ 2
+ 4
+ [/codeblock]
+ </description>
+ </method>
+ <method name="range_lerp">
+ <return type="float">
+ </return>
+ <argument index="0" name="value" type="float">
+ </argument>
+ <argument index="1" name="istart" type="float">
+ </argument>
+ <argument index="2" name="istop" type="float">
+ </argument>
+ <argument index="3" name="ostart" type="float">
+ </argument>
+ <argument index="4" name="ostop" type="float">
+ </argument>
+ <description>
+ Maps a [code]value[/code] from range [code][istart, istop][/code] to [code][ostart, ostop][/code].
+ [codeblock]
+ range_lerp(75, 0, 100, -1, 1) # Returns 0.5
+ [/codeblock]
+ </description>
+ </method>
+ <method name="round">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the integral value that is nearest to [code]s[/code], with halfway cases rounded away from zero.
+ [codeblock]
+ round(2.6) # Returns 3
+ [/codeblock]
+ </description>
+ </method>
+ <method name="seed">
+ <return type="void">
+ </return>
+ <argument index="0" name="seed" type="int">
+ </argument>
+ <description>
+ Sets seed for the random number generator.
+ [codeblock]
+ my_seed = "Godot Rocks"
+ seed(my_seed.hash())
+ [/codeblock]
+ </description>
+ </method>
+ <method name="sign">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the sign of [code]s[/code]: -1 or 1. Returns 0 if [code]s[/code] is 0.
+ [codeblock]
+ sign(-6) # Returns -1
+ sign(0) # Returns 0
+ sign(6) # Returns 1
+ [/codeblock]
+ </description>
+ </method>
+ <method name="sin">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the sine of angle [code]s[/code] in radians.
+ [codeblock]
+ sin(0.523599) # Returns 0.5
+ [/codeblock]
+ </description>
+ </method>
+ <method name="sinh">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the hyperbolic sine of [code]s[/code].
+ [codeblock]
+ a = log(2.0) # Returns 0.693147
+ sinh(a) # Returns 0.75
+ [/codeblock]
+ </description>
+ </method>
+ <method name="smoothstep">
+ <return type="float">
+ </return>
+ <argument index="0" name="from" type="float">
+ </argument>
+ <argument index="1" name="to" type="float">
+ </argument>
+ <argument index="2" name="weight" type="float">
+ </argument>
+ <description>
+ Returns a number smoothly interpolated between the [code]from[/code] and [code]to[/code], based on the [code]weight[/code]. Similar to [method lerp], but interpolates faster at the beginning and slower at the end.
+ [codeblock]
+ smoothstep(0, 2, 0.5) # Returns 0.15
+ smoothstep(0, 2, 1.0) # Returns 0.5
+ smoothstep(0, 2, 2.0) # Returns 1.0
+ [/codeblock]
+ </description>
+ </method>
+ <method name="sqrt">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the square root of [code]s[/code].
+ [codeblock]
+ sqrt(9) # Returns 3
+ [/codeblock]
+ </description>
+ </method>
+ <method name="step_decimals">
+ <return type="int">
+ </return>
+ <argument index="0" name="step" type="float">
+ </argument>
+ <description>
+ Returns the position of the first non-zero digit, after the decimal point.
+ [codeblock]
+ # n is 0
+ n = step_decimals(5)
+ # n is 4
+ n = step_decimals(1.0005)
+ # n is 9
+ n = step_decimals(0.000000005)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="stepify">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <argument index="1" name="step" type="float">
+ </argument>
+ <description>
+ Snaps float value [code]s[/code] to a given [code]step[/code].
+ </description>
+ </method>
+ <method name="str" qualifiers="vararg">
+ <return type="String">
+ </return>
+ <description>
+ Converts one or more arguments to string in the best way possible.
+ [codeblock]
+ var a = [10, 20, 30]
+ var b = str(a);
+ len(a) # Returns 3
+ len(b) # Returns 12
+ [/codeblock]
+ </description>
+ </method>
+ <method name="str2var">
+ <return type="Variant">
+ </return>
+ <argument index="0" name="string" type="String">
+ </argument>
+ <description>
+ Converts a formatted string that was returned by [method var2str] to the original value.
+ [codeblock]
+ a = '{ "a": 1, "b": 2 }'
+ b = str2var(a)
+ print(b["a"]) # Prints 1
+ [/codeblock]
+ </description>
+ </method>
+ <method name="tan">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the tangent of angle [code]s[/code] in radians.
+ [codeblock]
+ tan(deg2rad(45)) # Returns 1
+ [/codeblock]
+ </description>
+ </method>
+ <method name="tanh">
+ <return type="float">
+ </return>
+ <argument index="0" name="s" type="float">
+ </argument>
+ <description>
+ Returns the hyperbolic tangent of [code]s[/code].
+ [codeblock]
+ a = log(2.0) # Returns 0.693147
+ tanh(a) # Returns 0.6
+ [/codeblock]
+ </description>
+ </method>
+ <method name="to_json">
+ <return type="String">
+ </return>
+ <argument index="0" name="var" type="Variant">
+ </argument>
+ <description>
+ Converts a Variant [code]var[/code] to JSON text and return the result. Useful for serializing data to store or send over the network.
+ [codeblock]
+ a = { "a": 1, "b": 2 }
+ b = to_json(a)
+ print(b) # {"a":1, "b":2}
+ [/codeblock]
+ </description>
+ </method>
+ <method name="type_exists">
+ <return type="bool">
+ </return>
+ <argument index="0" name="type" type="String">
+ </argument>
+ <description>
+ Returns whether the given class exists in [ClassDB].
+ [codeblock]
+ type_exists("Sprite") # Returns true
+ type_exists("Variant") # Returns false
+ [/codeblock]
+ </description>
+ </method>
+ <method name="typeof">
+ <return type="int">
+ </return>
+ <argument index="0" name="what" type="Variant">
+ </argument>
+ <description>
+ Returns the internal type of the given Variant object, using the [code]TYPE_*[/code] enum in [@GlobalScope].
+ [codeblock]
+ p = parse_json('["a", "b", "c"]')
+ if typeof(p) == TYPE_ARRAY:
+ print(p[0]) # Prints a
+ else:
+ print("unexpected results")
+ [/codeblock]
+ </description>
+ </method>
+ <method name="validate_json">
+ <return type="String">
+ </return>
+ <argument index="0" name="json" type="String">
+ </argument>
+ <description>
+ Checks that [code]json[/code] is valid JSON data. Returns empty string if valid. Returns error message if not valid.
+ [codeblock]
+ j = to_json([1, 2, 3])
+ v = validate_json(j)
+ if not v:
+ print("valid")
+ else:
+ prints("invalid", v)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="var2bytes">
+ <return type="PoolByteArray">
+ </return>
+ <argument index="0" name="var" type="Variant">
+ </argument>
+ <argument index="1" name="full_objects" type="bool" default="false">
+ </argument>
+ <description>
+ Encodes a variable value to a byte array. When [code]full_objects[/code] is [code]true[/code] encoding objects is allowed (and can potentially include code).
+ </description>
+ </method>
+ <method name="var2str">
+ <return type="String">
+ </return>
+ <argument index="0" name="var" type="Variant">
+ </argument>
+ <description>
+ Converts a Variant [code]var[/code] to a formatted string that can later be parsed using [method str2var].
+ [codeblock]
+ a = { "a": 1, "b": 2 }
+ print(var2str(a))
+ [/codeblock]
+ prints
+ [codeblock]
+ {
+ "a": 1,
+ "b": 2
+ }
+ [/codeblock]
+ </description>
+ </method>
+ <method name="weakref">
+ <return type="WeakRef">
+ </return>
+ <argument index="0" name="obj" type="Object">
+ </argument>
+ <description>
+ Returns a weak reference to an object.
+ A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.
+ </description>
+ </method>
+ <method name="wrapf">
+ <return type="float">
+ </return>
+ <argument index="0" name="value" type="float">
+ </argument>
+ <argument index="1" name="min" type="float">
+ </argument>
+ <argument index="2" name="max" type="float">
+ </argument>
+ <description>
+ Wraps float [code]value[/code] between [code]min[/code] and [code]max[/code].
+ Usable for creating loop-alike behavior or infinite surfaces.
+ [codeblock]
+ # a is 0.5
+ a = wrapf(10.5, 0.0, 10.0)
+ [/codeblock]
+ [codeblock]
+ # a is 9.5
+ a = wrapf(-0.5, 0.0, 10.0)
+ [/codeblock]
+ [codeblock]
+ # Infinite loop between 0.0 and 0.99
+ f = wrapf(f + 0.1, 0.0, 1.0)
+ [/codeblock]
+ [codeblock]
+ # Infinite rotation (in radians)
+ angle = wrapf(angle + 0.1, 0.0, TAU)
+ [/codeblock]
+ [b]Note:[/b] If you just want to wrap between 0.0 and [code]n[/code] (where [code]n[/code] is a positive floating-point value), it is better for performance to use the [method fmod] method like [code]fmod(number, n)[/code].
+ [code]wrapf[/code] is more flexible than using the [method fmod] approach by giving the user a simple control over the minimum value. It also fully supports negative numbers, e.g.
+ [codeblock]
+ # Infinite rotation (in radians)
+ angle = wrapf(angle + 0.1, -PI, PI)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="wrapi">
+ <return type="int">
+ </return>
+ <argument index="0" name="value" type="int">
+ </argument>
+ <argument index="1" name="min" type="int">
+ </argument>
+ <argument index="2" name="max" type="int">
+ </argument>
+ <description>
+ Wraps integer [code]value[/code] between [code]min[/code] and [code]max[/code].
+ Usable for creating loop-alike behavior or infinite surfaces.
+ [codeblock]
+ # a is 0
+ a = wrapi(10, 0, 10)
+ [/codeblock]
+ [codeblock]
+ # a is 9
+ a = wrapi(-1, 0, 10)
+ [/codeblock]
+ [codeblock]
+ # Infinite loop between 0 and 9
+ frame = wrapi(frame + 1, 0, 10)
+ [/codeblock]
+ [b]Note:[/b] If you just want to wrap between 0 and [code]n[/code] (where [code]n[/code] is a positive integer value), it is better for performance to use the modulo operator like [code]number % n[/code].
+ [code]wrapi[/code] is more flexible than using the modulo approach by giving the user a simple control over the minimum value. It also fully supports negative numbers, e.g.
+ [codeblock]
+ # result is -2
+ var result = wrapi(-6, -5, -1)
+ [/codeblock]
+ </description>
+ </method>
+ <method name="yield">
+ <return type="GDScriptFunctionState">
+ </return>
+ <argument index="0" name="object" type="Object" default="null">
+ </argument>
+ <argument index="1" name="signal" type="String" default="&quot;&quot;">
+ </argument>
+ <description>
+ Stops the function execution and returns the current suspended state to the calling function.
+ From the caller, call [method GDScriptFunctionState.resume] on the state to resume execution. This invalidates the state. Within the resumed function, [code]yield()[/code] returns whatever was passed to the [code]resume()[/code] function call.
+ If passed an object and a signal, the execution is resumed when the object emits the given signal. In this case, [code]yield()[/code] returns the argument passed to [code]emit_signal()[/code] if the signal takes only one argument, or an array containing all the arguments passed to [code]emit_signal()[/code] if the signal takes multiple arguments.
+ </description>
+ </method>
+ </methods>
+ <constants>
+ <constant name="PI" value="3.141593">
+ Constant that represents how many times the diameter of a circle fits around its perimeter.
+ </constant>
+ <constant name="TAU" value="6.283185">
+ The circle constant, the circumference of the unit circle.
+ </constant>
+ <constant name="INF" value="inf">
+ A positive infinity. (For negative infinity, use -INF).
+ </constant>
+ <constant name="NAN" value="nan">
+ Macro constant that expands to an expression of type float that represents a NaN.
+ The NaN values are used to identify undefined or non-representable values for floating-point elements, such as the square root of negative numbers or the result of 0/0.
+ </constant>
+ </constants>
+</class>
diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp
index 060a9d6c91..963b40529d 100644
--- a/modules/gdscript/editor/gdscript_highlighter.cpp
+++ b/modules/gdscript/editor/gdscript_highlighter.cpp
@@ -56,6 +56,10 @@ static bool _is_hex_symbol(CharType c) {
return ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
}
+static bool _is_bin_symbol(CharType c) {
+ return (c == '0' || c == '1');
+}
+
Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) {
Map<int, TextEdit::HighlighterInfo> color_map;
@@ -76,6 +80,7 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
bool in_member_variable = false;
bool in_node_path = false;
bool is_hex_notation = false;
+ bool is_bin_notation = false;
bool expect_type = false;
Color keyword_color;
Color color;
@@ -118,14 +123,26 @@ Map<int, TextEdit::HighlighterInfo> GDScriptSyntaxHighlighter::_get_line_syntax_
is_hex_notation = false;
}
+ // disallow anything not a 0 or 1
+ if (is_bin_notation && (_is_bin_symbol(str[j]))) {
+ is_number = true;
+ } else if (is_bin_notation) {
+ is_bin_notation = false;
+ is_number = false;
+ } else {
+ is_bin_notation = false;
+ }
+
// check for dot or underscore or 'x' for hex notation in floating point number or 'e' for scientific notation
- if ((str[j] == '.' || str[j] == 'x' || str[j] == '_' || str[j] == 'e') && !in_word && prev_is_number && !is_number) {
+ if ((str[j] == '.' || str[j] == 'x' || str[j] == 'b' || str[j] == '_' || str[j] == 'e') && !in_word && prev_is_number && !is_number) {
is_number = true;
is_symbol = false;
is_char = false;
if (str[j] == 'x' && str[j - 1] == '0') {
is_hex_notation = true;
+ } else if (str[j] == 'b' && str[j - 1] == '0') {
+ is_bin_notation = true;
}
}
@@ -353,8 +370,8 @@ void GDScriptSyntaxHighlighter::_update_cache() {
bool default_theme = text_editor_color_theme == "Default";
bool dark_theme = settings->is_dark_theme();
- function_definition_color = Color::html(default_theme ? "#01e1ff" : dark_theme ? "#01e1ff" : "#00a5ba");
- node_path_color = Color::html(default_theme ? "#64c15a" : dark_theme ? "64c15a" : "#518b4b");
+ function_definition_color = default_theme ? Color(0.0, 0.88, 1.0) : dark_theme ? Color(0.0, 0.88, 1.0) : Color(0.0, 0.65, 0.73);
+ node_path_color = default_theme ? Color(0.39, 0.76, 0.35) : dark_theme ? Color(0.39, 0.76, 0.35) : Color(0.32, 0.55, 0.29);
EDITOR_DEF("text_editor/highlighting/gdscript/function_definition_color", function_definition_color);
EDITOR_DEF("text_editor/highlighting/gdscript/node_path_color", node_path_color);
diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp
index 3fb9268702..bc28f7009e 100644
--- a/modules/gdscript/gdscript.cpp
+++ b/modules/gdscript/gdscript.cpp
@@ -69,7 +69,7 @@ Variant GDScriptNativeClass::_new() {
Object *o = instance();
if (!o) {
ERR_EXPLAIN("Class type: '" + String(name) + "' is not instantiable.");
- ERR_FAIL_COND_V(!o, Variant());
+ ERR_FAIL_V(Variant());
}
Reference *ref = Object::cast_to<Reference>(o);
@@ -332,7 +332,7 @@ ScriptInstance *GDScript::instance_create(Object *p_this) {
}
Variant::CallError unchecked_error;
- return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this), unchecked_error);
+ return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this) != NULL, unchecked_error);
}
PlaceHolderScriptInstance *GDScript::placeholder_instance_create(Object *p_this) {
diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h
index 716f536e89..a5ad23c75d 100644
--- a/modules/gdscript/gdscript.h
+++ b/modules/gdscript/gdscript.h
@@ -458,9 +458,9 @@ public:
virtual bool can_inherit_from_file() { return true; }
virtual int find_function(const String &p_function, const String &p_code) const;
virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const;
- virtual Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_forced, String &r_call_hint);
+ virtual Error complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint);
#ifdef TOOLS_ENABLED
- virtual Error lookup_code(const String &p_code, const String &p_symbol, const String &p_base_path, Object *p_owner, LookupResult &r_result);
+ virtual Error lookup_code(const String &p_code, const String &p_symbol, const String &p_path, Object *p_owner, LookupResult &r_result);
#endif
virtual String _get_indentation() const;
virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const;
@@ -509,7 +509,6 @@ public:
};
class ResourceFormatLoaderGDScript : public ResourceFormatLoader {
- GDCLASS(ResourceFormatLoaderGDScript, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
@@ -519,7 +518,6 @@ public:
};
class ResourceFormatSaverGDScript : public ResourceFormatSaver {
- GDCLASS(ResourceFormatSaverGDScript, ResourceFormatSaver)
public:
virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0);
virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const;
diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp
index f7be0ce37c..4c976bd2e0 100644
--- a/modules/gdscript/gdscript_compiler.cpp
+++ b/modules/gdscript/gdscript_compiler.cpp
@@ -1073,7 +1073,7 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser::
int set_index;
bool named = false;
- if (static_cast<const GDScriptParser::OperatorNode *>(op)->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED) {
+ if (op->op == GDScriptParser::OperatorNode::OP_INDEX_NAMED) {
set_index = codegen.get_name_map_pos(static_cast<const GDScriptParser::IdentifierNode *>(op->arguments[1])->name);
named = true;
@@ -1259,8 +1259,6 @@ int GDScriptCompiler::_parse_expression(CodeGen &codegen, const GDScriptParser::
ERR_FAIL_V(-1); //unreachable code
} break;
}
-
- ERR_FAIL_V(-1); //unreachable code
}
Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::BlockNode *p_block, int p_stack_level, int p_break_addr, int p_continue_addr) {
@@ -1977,12 +1975,12 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar
for (int i = 0; i < p_class->subclasses.size(); i++) {
StringName name = p_class->subclasses[i]->name;
-
- GDScript *subclass = p_script->subclasses[name].ptr();
+ Ref<GDScript> &subclass = p_script->subclasses[name];
+ GDScript *subclass_ptr = subclass.ptr();
// Subclass might still be parsing, just skip it
- if (!parsed_classes.has(subclass) && !parsing_classes.has(subclass)) {
- Error err = _parse_class_level(subclass, p_class->subclasses[i], p_keep_state);
+ if (!parsed_classes.has(subclass_ptr) && !parsing_classes.has(subclass_ptr)) {
+ Error err = _parse_class_level(subclass_ptr, p_class->subclasses[i], p_keep_state);
if (err)
return err;
}
diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp
index d91e32249e..521b5ed538 100644
--- a/modules/gdscript/gdscript_editor.cpp
+++ b/modules/gdscript/gdscript_editor.cpp
@@ -159,7 +159,11 @@ bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int &
for (int i = 0; i < cl->subclasses.size(); i++) {
for (int j = 0; j < cl->subclasses[i]->functions.size(); j++) {
- funcs[cl->subclasses[i]->functions[j]->line] = String(cl->subclasses[i]->name) + "." + String(cl->subclasses[i]->functions[j]->name);
+ funcs[cl->subclasses[i]->functions[j]->line] = String(cl->subclasses[i]->name) + "." + cl->subclasses[i]->functions[j]->name;
+ }
+ for (int j = 0; j < cl->subclasses[i]->static_functions.size(); j++) {
+
+ funcs[cl->subclasses[i]->static_functions[j]->line] = String(cl->subclasses[i]->name) + "." + cl->subclasses[i]->static_functions[j]->name;
}
}
@@ -509,12 +513,14 @@ struct GDScriptCompletionIdentifier {
assigned_expression(NULL) {}
};
-static void _get_directory_contents(EditorFileSystemDirectory *p_dir, Set<String> &r_list) {
+static void _get_directory_contents(EditorFileSystemDirectory *p_dir, Map<String, ScriptCodeCompletionOption> &r_list) {
const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\"";
for (int i = 0; i < p_dir->get_file_count(); i++) {
- r_list.insert(quote_style + p_dir->get_file_path(i) + quote_style);
+ ScriptCodeCompletionOption option(p_dir->get_file_path(i), ScriptCodeCompletionOption::KIND_FILE_PATH);
+ option.insert_text = quote_style + option.display + quote_style;
+ r_list.insert(option.display, option);
}
for (int i = 0; i < p_dir->get_subdir_count(); i++) {
@@ -1807,14 +1813,15 @@ static String _make_arguments_hint(const GDScriptParser::FunctionNode *p_functio
return arghint;
}
-static void _find_enumeration_candidates(const String p_enum_hint, Set<String> &r_result) {
+static void _find_enumeration_candidates(const String p_enum_hint, Map<String, ScriptCodeCompletionOption> &r_result) {
if (p_enum_hint.find(".") == -1) {
// Global constant
StringName current_enum = p_enum_hint;
for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) {
if (GlobalConstants::get_global_constant_enum(i) == current_enum) {
- r_result.insert(GlobalConstants::get_global_constant_name(i));
+ ScriptCodeCompletionOption option(GlobalConstants::get_global_constant_name(i), ScriptCodeCompletionOption::KIND_ENUM);
+ r_result.insert(option.display, option);
}
}
} else {
@@ -1829,15 +1836,17 @@ static void _find_enumeration_candidates(const String p_enum_hint, Set<String> &
ClassDB::get_enum_constants(class_name, enum_name, &enum_constants);
for (List<StringName>::Element *E = enum_constants.front(); E; E = E->next()) {
String candidate = class_name + "." + E->get();
- r_result.insert(candidate);
+ ScriptCodeCompletionOption option(candidate, ScriptCodeCompletionOption::KIND_ENUM);
+ r_result.insert(option.display, option);
}
}
}
-static void _find_identifiers_in_block(const GDScriptCompletionContext &p_context, Set<String> &r_result) {
+static void _find_identifiers_in_block(const GDScriptCompletionContext &p_context, Map<String, ScriptCodeCompletionOption> &r_result) {
for (Map<StringName, GDScriptParser::LocalVarNode *>::Element *E = p_context.block->variables.front(); E; E = E->next()) {
if (E->get()->line < p_context.line) {
- r_result.insert(E->key().operator String());
+ ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_VARIABLE);
+ r_result.insert(option.display, option);
}
}
if (p_context.block->parent_block) {
@@ -1847,40 +1856,47 @@ static void _find_identifiers_in_block(const GDScriptCompletionContext &p_contex
}
}
-static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Set<String> &r_result);
+static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result);
-static void _find_identifiers_in_class(const GDScriptCompletionContext &p_context, bool p_static, bool p_only_functions, bool p_parent_only, Set<String> &r_result) {
+static void _find_identifiers_in_class(const GDScriptCompletionContext &p_context, bool p_static, bool p_only_functions, bool p_parent_only, Map<String, ScriptCodeCompletionOption> &r_result) {
if (!p_parent_only) {
if (!p_static && !p_only_functions) {
for (int i = 0; i < p_context._class->variables.size(); i++) {
- r_result.insert(p_context._class->variables[i].identifier);
+ ScriptCodeCompletionOption option(p_context._class->variables[i].identifier, ScriptCodeCompletionOption::KIND_MEMBER);
+ r_result.insert(option.display, option);
}
}
if (!p_only_functions) {
for (Map<StringName, GDScriptParser::ClassNode::Constant>::Element *E = p_context._class->constant_expressions.front(); E; E = E->next()) {
- r_result.insert(E->key());
+ ScriptCodeCompletionOption option(E->key(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ r_result.insert(option.display, option);
}
for (int i = 0; i < p_context._class->subclasses.size(); i++) {
- r_result.insert(p_context._class->subclasses[i]->name);
+ ScriptCodeCompletionOption option(p_context._class->subclasses[i]->name, ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
}
}
for (int i = 0; i < p_context._class->static_functions.size(); i++) {
+ ScriptCodeCompletionOption option(p_context._class->static_functions[i]->name.operator String(), ScriptCodeCompletionOption::KIND_FUNCTION);
if (p_context._class->static_functions[i]->arguments.size()) {
- r_result.insert(p_context._class->static_functions[i]->name.operator String() + "(");
+ option.insert_text += "(";
} else {
- r_result.insert(p_context._class->static_functions[i]->name.operator String() + "()");
+ option.insert_text += "()";
}
+ r_result.insert(option.display, option);
}
if (!p_static) {
for (int i = 0; i < p_context._class->functions.size(); i++) {
+ ScriptCodeCompletionOption option(p_context._class->functions[i]->name.operator String(), ScriptCodeCompletionOption::KIND_FUNCTION);
if (p_context._class->functions[i]->arguments.size()) {
- r_result.insert(p_context._class->functions[i]->name.operator String() + "(");
+ option.insert_text += "(";
} else {
- r_result.insert(p_context._class->functions[i]->name.operator String() + "()");
+ option.insert_text += "()";
}
+ r_result.insert(option.display, option);
}
}
}
@@ -1898,12 +1914,14 @@ static void _find_identifiers_in_class(const GDScriptCompletionContext &p_contex
_find_identifiers_in_base(c, base_type, p_only_functions, r_result);
}
-static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Set<String> &r_result) {
+static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result) {
GDScriptParser::DataType base_type = p_base.type;
bool _static = base_type.is_meta_type;
if (_static && base_type.kind != GDScriptParser::DataType::BUILTIN) {
- r_result.insert("new(");
+ ScriptCodeCompletionOption option("new", ScriptCodeCompletionOption::KIND_FUNCTION);
+ option.insert_text += "(";
+ r_result.insert(option.display, option);
}
while (base_type.has_type) {
@@ -1921,26 +1939,31 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context
if (script.is_valid()) {
if (!_static && !p_only_functions) {
for (const Set<StringName>::Element *E = script->get_members().front(); E; E = E->next()) {
- r_result.insert(E->get().operator String());
+ ScriptCodeCompletionOption option(E->get().operator String(), ScriptCodeCompletionOption::KIND_MEMBER);
+ r_result.insert(option.display, option);
}
}
if (!p_only_functions) {
for (const Map<StringName, Variant>::Element *E = script->get_constants().front(); E; E = E->next()) {
- r_result.insert(E->key().operator String());
+ ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ r_result.insert(option.display, option);
}
}
for (const Map<StringName, GDScriptFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) {
if (!_static || E->get()->is_static()) {
+ ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_FUNCTION);
if (E->get()->get_argument_count()) {
- r_result.insert(E->key().operator String() + "(");
+ option.insert_text += "(";
} else {
- r_result.insert(E->key().operator String() + "()");
+ option.insert_text += "()";
}
+ r_result.insert(option.display, option);
}
}
if (!p_only_functions) {
for (const Map<StringName, Ref<GDScript> >::Element *E = script->get_subclasses().front(); E; E = E->next()) {
- r_result.insert(E->key().operator String());
+ ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
}
}
base_type = GDScriptParser::DataType();
@@ -1964,25 +1987,29 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context
List<PropertyInfo> members;
scr->get_script_property_list(&members);
for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) {
- r_result.insert(E->get().name);
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER);
+ r_result.insert(option.display, option);
}
}
if (!p_only_functions) {
Map<StringName, Variant> constants;
scr->get_constants(&constants);
for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) {
- r_result.insert(E->key().operator String());
+ ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ r_result.insert(option.display, option);
}
}
List<MethodInfo> methods;
scr->get_script_method_list(&methods);
for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION);
if (E->get().arguments.size()) {
- r_result.insert(E->get().name + "(");
+ option.insert_text += "(";
} else {
- r_result.insert(E->get().name + "()");
+ option.insert_text += "()";
}
+ r_result.insert(option.display, option);
}
Ref<Script> base_script = scr->get_base_script();
@@ -2009,7 +2036,8 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context
List<String> constants;
ClassDB::get_integer_constant_list(type, &constants);
for (List<String>::Element *E = constants.front(); E; E = E->next()) {
- r_result.insert(E->get());
+ ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ r_result.insert(option.display, option);
}
if (!_static) {
@@ -2022,7 +2050,8 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context
if (E->get().name.find("/") != -1) {
continue;
}
- r_result.insert(E->get().name);
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER);
+ r_result.insert(option.display, option);
}
}
}
@@ -2035,11 +2064,13 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context
if (E->get().name.begins_with("_")) {
continue;
}
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION);
if (E->get().arguments.size()) {
- r_result.insert(E->get().name + "(");
+ option.insert_text += "(";
} else {
- r_result.insert(E->get().name + "()");
+ option.insert_text += "()";
}
+ r_result.insert(option.display, option);
}
}
@@ -2054,11 +2085,12 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context
if (!p_only_functions) {
List<PropertyInfo> members;
- tmp.get_property_list(&members);
+ p_base.value.get_property_list(&members);
for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) {
if (String(E->get().name).find("/") == -1) {
- r_result.insert(E->get().name);
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER);
+ r_result.insert(option.display, option);
}
}
}
@@ -2066,11 +2098,13 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context
List<MethodInfo> methods;
tmp.get_method_list(&methods);
for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION);
if (E->get().arguments.size()) {
- r_result.insert(E->get().name + "(");
+ option.insert_text += "(";
} else {
- r_result.insert(E->get().name + "()");
+ option.insert_text += "()";
}
+ r_result.insert(option.display, option);
}
return;
@@ -2082,7 +2116,7 @@ static void _find_identifiers_in_base(const GDScriptCompletionContext &p_context
}
}
-static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p_only_functions, Set<String> &r_result) {
+static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result) {
const GDScriptParser::BlockNode *block = p_context.block;
@@ -2091,7 +2125,8 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p
const GDScriptParser::FunctionNode *f = p_context.function;
for (int i = 0; i < f->arguments.size(); i++) {
- r_result.insert(f->arguments[i].operator String());
+ ScriptCodeCompletionOption option(f->arguments[i].operator String(), ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ r_result.insert(option.display, option);
}
}
@@ -2116,11 +2151,13 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p
for (int i = 0; i < GDScriptFunctions::FUNC_MAX; i++) {
MethodInfo mi = GDScriptFunctions::get_info(GDScriptFunctions::Function(i));
+ ScriptCodeCompletionOption option(String(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i))), ScriptCodeCompletionOption::KIND_FUNCTION);
if (mi.arguments.size() || (mi.flags & METHOD_FLAG_VARARG)) {
- r_result.insert(String(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i))) + "(");
+ option.insert_text += "(";
} else {
- r_result.insert(String(GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i))) + "()");
+ option.insert_text += "()";
}
+ r_result.insert(option.display, option);
}
static const char *_type_names[Variant::VARIANT_MAX] = {
@@ -2130,7 +2167,8 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p
};
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- r_result.insert(_type_names[i]);
+ ScriptCodeCompletionOption option(_type_names[i], ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
}
static const char *_keywords[] = {
@@ -2144,7 +2182,8 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p
const char **kw = _keywords;
while (*kw) {
- r_result.insert(*kw);
+ ScriptCodeCompletionOption option(*kw, ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ r_result.insert(option.display, option);
kw++;
}
@@ -2158,7 +2197,8 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p
}
String path = ProjectSettings::get_singleton()->get(s);
if (path.begins_with("*")) {
- r_result.insert(s.get_slice("/", 1));
+ ScriptCodeCompletionOption option(s.get_slice("/", 1), ScriptCodeCompletionOption::KIND_CONSTANT);
+ r_result.insert(option.display, option);
}
}
@@ -2166,16 +2206,18 @@ static void _find_identifiers(const GDScriptCompletionContext &p_context, bool p
List<StringName> named_scripts;
ScriptServer::get_global_class_list(&named_scripts);
for (List<StringName>::Element *E = named_scripts.front(); E; E = E->next()) {
- r_result.insert(E->get().operator String());
+ ScriptCodeCompletionOption option(E->get().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
}
// Native classes
for (const Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) {
- r_result.insert(E->key().operator String());
+ ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
+ r_result.insert(option.display, option);
}
}
-static void _find_call_arguments(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, int p_argidx, bool p_static, Set<String> &r_result, String &r_arghint) {
+static void _find_call_arguments(const GDScriptCompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, int p_argidx, bool p_static, Map<String, ScriptCodeCompletionOption> &r_result, String &r_arghint) {
Variant base = p_base.value;
GDScriptParser::DataType base_type = p_base.type;
@@ -2199,7 +2241,9 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con
if ((p_method == "connect" || p_method == "emit_signal") && p_argidx == 0) {
for (int i = 0; i < base_type.class_type->_signals.size(); i++) {
- r_result.insert(quote_style + base_type.class_type->_signals[i].name.operator String() + quote_style);
+ ScriptCodeCompletionOption option(base_type.class_type->_signals[i].name.operator String(), ScriptCodeCompletionOption::KIND_SIGNAL);
+ option.insert_text = quote_style + option.display + quote_style;
+ r_result.insert(option.display, option);
}
}
@@ -2212,7 +2256,9 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con
List<MethodInfo> signals;
gds->get_script_signal_list(&signals);
for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
- r_result.insert(quote_style + E->get().name + quote_style);
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_SIGNAL);
+ option.insert_text = quote_style + option.display + quote_style;
+ r_result.insert(option.display, option);
}
}
Ref<GDScript> base_script = gds->get_base_script();
@@ -2250,7 +2296,8 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con
List<String> options;
obj->get_argument_options(p_method, p_argidx, &options);
for (List<String>::Element *F = options.front(); F; F = F->next()) {
- r_result.insert(F->get());
+ ScriptCodeCompletionOption option(F->get(), ScriptCodeCompletionOption::KIND_FUNCTION);
+ r_result.insert(option.display, option);
}
}
}
@@ -2271,7 +2318,9 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con
List<MethodInfo> signals;
ClassDB::get_signal_list(class_name, &signals);
for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
- r_result.insert(quote_style + E->get().name + quote_style);
+ ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_SIGNAL);
+ option.insert_text = quote_style + option.display + quote_style;
+ r_result.insert(option.display, option);
}
}
@@ -2286,7 +2335,9 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con
continue;
}
String name = s.get_slice("/", 1);
- r_result.insert(quote_style + "/root/" + name + quote_style);
+ ScriptCodeCompletionOption option("/root/" + name, ScriptCodeCompletionOption::KIND_NODE_PATH);
+ option.insert_text = quote_style + option.display + quote_style;
+ r_result.insert(option.display, option);
}
}
@@ -2300,7 +2351,9 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con
continue;
}
String name = s.get_slice("/", 1);
- r_result.insert(quote_style + name + quote_style);
+ ScriptCodeCompletionOption option(name, ScriptCodeCompletionOption::KIND_CONSTANT);
+ option.insert_text = quote_style + option.display + quote_style;
+ r_result.insert(option.display, option);
}
}
@@ -2333,7 +2386,7 @@ static void _find_call_arguments(const GDScriptCompletionContext &p_context, con
}
}
-static void _find_call_arguments(GDScriptCompletionContext &p_context, const GDScriptParser::Node *p_node, int p_argidx, Set<String> &r_result, bool &r_forced, String &r_arghint) {
+static void _find_call_arguments(GDScriptCompletionContext &p_context, const GDScriptParser::Node *p_node, int p_argidx, Map<String, ScriptCodeCompletionOption> &r_result, bool &r_forced, String &r_arghint) {
const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\"";
@@ -2451,25 +2504,27 @@ static void _find_call_arguments(GDScriptCompletionContext &p_context, const GDS
_find_call_arguments(p_context, ci, function, p_argidx, _static, r_result, r_arghint);
if (function == "connect" && p_argidx == 2) {
- Set<String> methods;
+ Map<String, ScriptCodeCompletionOption> methods;
_find_identifiers_in_base(p_context, connect_base, true, methods);
- for (Set<String>::Element *E = methods.front(); E; E = E->next()) {
- r_result.insert(quote_style + E->get().replace("(", "").replace(")", "") + quote_style);
+ for (Map<String, ScriptCodeCompletionOption>::Element *E = methods.front(); E; E = E->next()) {
+ ScriptCodeCompletionOption &option = E->value();
+ option.insert_text = quote_style + option.display + quote_style;
+ r_result.insert(option.display, option);
}
}
r_forced = r_result.size() > 0;
}
-Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_forced, String &r_call_hint) {
+Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint) {
const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\"";
GDScriptParser parser;
- parser.parse(p_code, p_base_path, false, "", true);
+ parser.parse(p_code, p_path.get_base_dir(), false, p_path, true);
r_forced = false;
- Set<String> options;
+ Map<String, ScriptCodeCompletionOption> options;
GDScriptCompletionContext context;
context._class = parser.get_completion_class();
context.block = parser.get_completion_block();
@@ -2478,7 +2533,7 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
if (!context._class || context._class->owner == NULL) {
context.base = p_owner;
- context.base_path = p_base_path;
+ context.base_path = p_path.get_base_dir();
}
bool is_function = false;
@@ -2490,7 +2545,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
List<StringName> constants;
Variant::get_constants_for_type(parser.get_completion_built_in_constant(), &constants);
for (List<StringName>::Element *E = constants.front(); E; E = E->next()) {
- options.insert(E->get().operator String());
+ ScriptCodeCompletionOption option(E->get().operator String(), ScriptCodeCompletionOption::KIND_CONSTANT);
+ options.insert(option.display, option);
}
} break;
case GDScriptParser::COMPLETION_PARENT_FUNCTION: {
@@ -2498,7 +2554,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
} break;
case GDScriptParser::COMPLETION_FUNCTION: {
is_function = true;
- } // fallthrough
+ FALLTHROUGH;
+ }
case GDScriptParser::COMPLETION_IDENTIFIER: {
_find_identifiers(context, is_function, options);
} break;
@@ -2514,9 +2571,11 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
r_forced = true;
String idopt = opt.unquote();
if (idopt.replace("/", "_").is_valid_identifier()) {
- options.insert(idopt);
+ ScriptCodeCompletionOption option(idopt, ScriptCodeCompletionOption::KIND_NODE_PATH);
+ options.insert(option.display, option);
} else {
- options.insert(opt);
+ ScriptCodeCompletionOption option(opt, ScriptCodeCompletionOption::KIND_NODE_PATH);
+ options.insert(option.display, option);
}
}
}
@@ -2531,13 +2590,15 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
continue;
}
String name = s.get_slice("/", 1);
- options.insert(quote_style + "/root/" + name + quote_style);
+ ScriptCodeCompletionOption option(quote_style + "/root/" + name + quote_style, ScriptCodeCompletionOption::KIND_NODE_PATH);
+ options.insert(option.display, option);
}
}
} break;
case GDScriptParser::COMPLETION_METHOD: {
is_function = true;
- } // fallthrough
+ FALLTHROUGH;
+ }
case GDScriptParser::COMPLETION_INDEX: {
const GDScriptParser::Node *node = parser.get_completion_node();
if (node->type != GDScriptParser::Node::TYPE_OPERATOR) {
@@ -2653,7 +2714,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
}
method_hint += ":";
- options.insert(method_hint);
+ ScriptCodeCompletionOption option(method_hint, ScriptCodeCompletionOption::KIND_FUNCTION);
+ options.insert(option.display, option);
}
} break;
case GDScriptParser::COMPLETION_YIELD: {
@@ -2671,7 +2733,9 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
switch (base_type.kind) {
case GDScriptParser::DataType::CLASS: {
for (int i = 0; i < base_type.class_type->_signals.size(); i++) {
- options.insert(quote_style + base_type.class_type->_signals[i].name.operator String() + quote_style);
+ ScriptCodeCompletionOption option(base_type.class_type->_signals[i].name.operator String(), ScriptCodeCompletionOption::KIND_SIGNAL);
+ option.insert_text = quote_style + option.display + quote_style;
+ options.insert(option.display, option);
}
base_type = base_type.class_type->base_type;
} break;
@@ -2682,7 +2746,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
List<MethodInfo> signals;
scr->get_script_signal_list(&signals);
for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
- options.insert(quote_style + E->get().name + quote_style);
+ ScriptCodeCompletionOption option(quote_style + E->get().name + quote_style, ScriptCodeCompletionOption::KIND_SIGNAL);
+ options.insert(option.display, option);
}
Ref<Script> base_script = scr->get_base_script();
if (base_script.is_valid()) {
@@ -2709,7 +2774,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
List<MethodInfo> signals;
ClassDB::get_signal_list(class_name, &signals);
for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
- options.insert(quote_style + E->get().name + quote_style);
+ ScriptCodeCompletionOption option(quote_style + E->get().name + quote_style, ScriptCodeCompletionOption::KIND_SIGNAL);
+ options.insert(option.display, option);
}
} break;
default: {
@@ -2746,18 +2812,21 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
c.line = E->value().expression->line;
if (_guess_expression_type(c, E->value().expression, constant)) {
if (constant.type.has_type && constant.type.is_meta_type) {
- options.insert(E->key().operator String());
+ ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
+ options.insert(option.display, option);
}
}
}
for (int i = 0; i < clss->subclasses.size(); i++) {
if (clss->subclasses[i]->name != StringName()) {
- options.insert(clss->subclasses[i]->name.operator String());
+ ScriptCodeCompletionOption option(clss->subclasses[i]->name.operator String(), ScriptCodeCompletionOption::KIND_CLASS);
+ options.insert(option.display, option);
}
}
clss = clss->owner;
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- options.insert(Variant::get_type_name((Variant::Type)i));
+ ScriptCodeCompletionOption option(Variant::get_type_name((Variant::Type)i), ScriptCodeCompletionOption::KIND_CLASS);
+ options.insert(option.display, option);
}
}
@@ -2771,18 +2840,21 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
if (Engine::get_singleton()->has_singleton(class_name)) {
continue;
}
- options.insert(class_name);
+ ScriptCodeCompletionOption option(class_name, ScriptCodeCompletionOption::KIND_CLASS);
+ options.insert(option.display, option);
}
// Named scripts
List<StringName> named_scripts;
ScriptServer::get_global_class_list(&named_scripts);
for (List<StringName>::Element *E = named_scripts.front(); E; E = E->next()) {
- options.insert(E->get().operator String());
+ ScriptCodeCompletionOption option(E->get().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
+ options.insert(option.display, option);
}
if (parser.get_completion_identifier_is_function()) {
- options.insert("void");
+ ScriptCodeCompletionOption option("void", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
+ options.insert(option.display, option);
}
r_forced = true;
} break;
@@ -2829,13 +2901,15 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
c2.line = E->value().expression->line;
if (_guess_expression_type(c2, E->value().expression, constant)) {
if (constant.type.has_type && constant.type.is_meta_type) {
- options.insert(E->key().operator String());
+ ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
+ options.insert(option.display, option);
}
}
}
for (int i = 0; i < base_type.class_type->subclasses.size(); i++) {
if (base_type.class_type->subclasses[i]->name != StringName()) {
- options.insert(base_type.class_type->subclasses[i]->name.operator String());
+ ScriptCodeCompletionOption option(base_type.class_type->subclasses[i]->name.operator String(), ScriptCodeCompletionOption::KIND_CLASS);
+ options.insert(option.display, option);
}
}
@@ -2853,7 +2927,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) {
Ref<Script> const_scr = E->value();
if (const_scr.is_valid()) {
- options.insert(E->key().operator String());
+ ScriptCodeCompletionOption option(E->key().operator String(), ScriptCodeCompletionOption::KIND_CLASS);
+ options.insert(option.display, option);
}
}
Ref<Script> base_script = scr->get_base_script();
@@ -2875,7 +2950,7 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
} break;
}
- for (Set<String>::Element *E = options.front(); E; E = E->next()) {
+ for (Map<String, ScriptCodeCompletionOption>::Element *E = options.front(); E; E = E->next()) {
r_options->push_back(E->get());
}
@@ -2884,7 +2959,7 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base
#else
-Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_forced, String &r_call_hint) {
+Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint) {
return OK;
}
@@ -3155,7 +3230,7 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co
return ERR_CANT_RESOLVE;
}
-Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_base_path, Object *p_owner, LookupResult &r_result) {
+Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_path, Object *p_owner, LookupResult &r_result) {
//before parsing, try the usual stuff
if (ClassDB::class_exists(p_symbol)) {
@@ -3197,7 +3272,7 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
}
GDScriptParser parser;
- parser.parse(p_code, p_base_path, false, "", true);
+ parser.parse(p_code, p_path.get_base_dir(), false, p_path, true);
if (parser.get_completion_type() == GDScriptParser::COMPLETION_NONE) {
return ERR_CANT_RESOLVE;
@@ -3209,7 +3284,7 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
context.block = parser.get_completion_block();
context.line = parser.get_completion_line();
context.base = p_owner;
- context.base_path = p_base_path;
+ context.base_path = p_path.get_base_dir();
if (context._class && context._class->extends_class.size() > 0) {
bool success = false;
@@ -3234,7 +3309,8 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
case GDScriptParser::COMPLETION_PARENT_FUNCTION:
case GDScriptParser::COMPLETION_FUNCTION: {
is_function = true;
- } // fallthrough
+ FALLTHROUGH;
+ }
case GDScriptParser::COMPLETION_IDENTIFIER: {
if (!is_function) {
@@ -3365,7 +3441,8 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol
} break;
case GDScriptParser::COMPLETION_METHOD: {
is_function = true;
- } // fallthrough
+ FALLTHROUGH;
+ }
case GDScriptParser::COMPLETION_INDEX: {
const GDScriptParser::Node *node = parser.get_completion_node();
if (node->type != GDScriptParser::Node::TYPE_OPERATOR) {
diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp
index cff9ba55b8..42f349ffc0 100644
--- a/modules/gdscript/gdscript_function.cpp
+++ b/modules/gdscript/gdscript_function.cpp
@@ -133,35 +133,13 @@ Variant *GDScriptFunction::_get_variant(int p_address, GDScriptInstance *p_insta
return NULL;
}
-String GDScriptFunction::_get_call_error(const Variant::CallError &p_err, const String &p_where, const Variant **argptrs) const {
-
- String err_text;
-
- if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
- int errorarg = p_err.argument;
- err_text = "Invalid type in " + p_where + ". Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(p_err.expected) + ".";
- } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
- err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments.";
- } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
- err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments.";
- } else if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) {
- err_text = "Invalid call. Nonexistent " + p_where + ".";
- } else if (p_err.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
- err_text = "Attempt to call " + p_where + " on a null instance.";
- } else {
- err_text = "Bug, call error: #" + itos(p_err.error);
- }
-
- return err_text;
-}
-
#ifdef DEBUG_ENABLED
-static String _get_var_type(const Variant *p_type) {
+static String _get_var_type(const Variant *p_var) {
String basestr;
- if (p_type->get_type() == Variant::OBJECT) {
- Object *bobj = *p_type;
+ if (p_var->get_type() == Variant::OBJECT) {
+ Object *bobj = *p_var;
if (!bobj) {
basestr = "null instance";
} else {
@@ -176,12 +154,42 @@ static String _get_var_type(const Variant *p_type) {
}
} else {
- basestr = Variant::get_type_name(p_type->get_type());
+ basestr = Variant::get_type_name(p_var->get_type());
}
return basestr;
}
-#endif
+#endif // DEBUG_ENABLED
+
+String GDScriptFunction::_get_call_error(const Variant::CallError &p_err, const String &p_where, const Variant **argptrs) const {
+
+ String err_text;
+
+ if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
+ int errorarg = p_err.argument;
+ // Handle the Object to Object case separately as we don't have further class details.
+#ifdef DEBUG_ENABLED
+ if (p_err.expected == Variant::OBJECT && argptrs[errorarg]->get_type() == p_err.expected) {
+ err_text = "Invalid type in " + p_where + ". The Object-derived class of argument " + itos(errorarg + 1) + " (" + _get_var_type(argptrs[errorarg]) + ") is not a subclass of the expected argument class.";
+ } else
+#endif // DEBUG_ENABLED
+ {
+ err_text = "Invalid type in " + p_where + ". Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(p_err.expected) + ".";
+ }
+ } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
+ err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments.";
+ } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
+ err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments.";
+ } else if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) {
+ err_text = "Invalid call. Nonexistent " + p_where + ".";
+ } else if (p_err.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
+ err_text = "Attempt to call " + p_where + " on a null instance.";
+ } else {
+ err_text = "Bug, call error: #" + itos(p_err.error);
+ }
+
+ return err_text;
+}
#if defined(__GNUC__)
#define OPCODES_TABLE \
@@ -1548,14 +1556,14 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
//error
// function, file, line, error, explanation
String err_file;
- if (p_instance)
+ if (p_instance && p_instance->script->is_valid() && p_instance->script->path != "")
err_file = p_instance->script->path;
else if (script)
err_file = script->path;
if (err_file == "")
err_file = "<built-in>";
String err_func = name;
- if (p_instance && p_instance->script->name != "")
+ if (p_instance && p_instance->script->is_valid() && p_instance->script->name != "")
err_func = p_instance->script->name + "." + err_func;
int err_line = line;
if (err_text == "") {
@@ -1583,15 +1591,26 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a
GDScriptLanguage::get_singleton()->script_frame_time += time_taken - function_call_time;
}
- if (ScriptDebugger::get_singleton())
- GDScriptLanguage::get_singleton()->exit_function();
+ bool yielded = retvalue.is_ref() && Object::cast_to<GDScriptFunctionState>(retvalue);
+
+ // Check if this is the last time the function is resuming from yield
+ // Will be true if never yielded as well
+ // When it's the last resume it will postpone the exit from stack,
+ // so the debugger knows which function triggered the resume of the next function (if any)
+ if (!p_state || yielded) {
+ if (ScriptDebugger::get_singleton())
+ GDScriptLanguage::get_singleton()->exit_function();
#endif
- if (_stack_size) {
- //free stack
- for (int i = 0; i < _stack_size; i++)
- stack[i].~Variant();
+ if (_stack_size) {
+ //free stack
+ for (int i = 0; i < _stack_size; i++)
+ stack[i].~Variant();
+ }
+
+#ifdef DEBUG_ENABLED
}
+#endif
return retvalue;
}
@@ -1765,20 +1784,9 @@ GDScriptFunction::~GDScriptFunction() {
Variant GDScriptFunctionState::_signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
- if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) {
-#ifdef DEBUG_ENABLED
- ERR_EXPLAIN("Resumed after yield, but class instance is gone");
- ERR_FAIL_V(Variant());
-#else
- return Variant();
-#endif
- }
-
Variant arg;
r_error.error = Variant::CallError::CALL_OK;
- ERR_FAIL_COND_V(!function, Variant());
-
if (p_argcount == 0) {
r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
r_error.argument = 1;
@@ -1804,33 +1812,7 @@ Variant GDScriptFunctionState::_signal_callback(const Variant **p_args, int p_ar
return Variant();
}
- state.result = arg;
- Variant ret = function->call(NULL, NULL, 0, r_error, &state);
-
- bool completed = true;
-
- // If the return value is a GDScriptFunctionState reference,
- // then the function did yield again after resuming.
- if (ret.is_ref()) {
- GDScriptFunctionState *gdfs = Object::cast_to<GDScriptFunctionState>(ret);
- if (gdfs && gdfs->function == function) {
- completed = false;
- gdfs->first_state = first_state.is_valid() ? first_state : Ref<GDScriptFunctionState>(this);
- }
- }
-
- function = NULL; //cleaned up;
- state.result = Variant();
-
- if (completed) {
- if (first_state.is_valid()) {
- first_state->emit_signal("completed", ret);
- } else {
- emit_signal("completed", ret);
- }
- }
-
- return ret;
+ return resume(arg);
}
bool GDScriptFunctionState::is_valid(bool p_extended_check) const {
@@ -1852,7 +1834,7 @@ Variant GDScriptFunctionState::resume(const Variant &p_arg) {
ERR_FAIL_COND_V(!function, Variant());
if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) {
#ifdef DEBUG_ENABLED
- ERR_EXPLAIN("Resumed after yield, but class instance is gone");
+ ERR_EXPLAIN("Resumed function '" + String(function->get_name()) + "()' after yield, but class instance is gone. At script: " + state.script->get_path() + ":" + itos(state.line));
ERR_FAIL_V(Variant());
#else
return Variant();
@@ -1884,6 +1866,17 @@ Variant GDScriptFunctionState::resume(const Variant &p_arg) {
} else {
emit_signal("completed", ret);
}
+
+#ifdef DEBUG_ENABLED
+ if (ScriptDebugger::get_singleton())
+ GDScriptLanguage::get_singleton()->exit_function();
+ if (state.stack_size) {
+ //free stack
+ Variant *stack = (Variant *)state.stack.ptr();
+ for (int i = 0; i < state.stack_size; i++)
+ stack[i].~Variant();
+ }
+#endif
}
return ret;
diff --git a/modules/gdscript/gdscript_functions.cpp b/modules/gdscript/gdscript_functions.cpp
index 5ebcddfd7c..8c33d6613c 100644
--- a/modules/gdscript/gdscript_functions.cpp
+++ b/modules/gdscript/gdscript_functions.cpp
@@ -58,6 +58,7 @@ const char *GDScriptFunctions::get_func_name(Function p_func) {
"sqrt",
"fmod",
"fposmod",
+ "posmod",
"floor",
"ceil",
"round",
@@ -78,6 +79,7 @@ const char *GDScriptFunctions::get_func_name(Function p_func) {
"inverse_lerp",
"range_lerp",
"smoothstep",
+ "move_toward",
"dectime",
"randomize",
"randi",
@@ -242,6 +244,12 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_
VALIDATE_ARG_NUM(1);
r_ret = Math::fposmod((double)*p_args[0], (double)*p_args[1]);
} break;
+ case MATH_POSMOD: {
+ VALIDATE_ARG_COUNT(2);
+ VALIDATE_ARG_NUM(0);
+ VALIDATE_ARG_NUM(1);
+ r_ret = Math::posmod((int)*p_args[0], (int)*p_args[1]);
+ } break;
case MATH_FLOOR: {
VALIDATE_ARG_COUNT(1);
VALIDATE_ARG_NUM(0);
@@ -341,7 +349,7 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_
VALIDATE_ARG_NUM(0);
r_ret = Math::step_decimals((double)*p_args[0]);
ERR_EXPLAIN("GDScript method 'decimals' is deprecated and has been renamed to 'step_decimals', please update your code accordingly.");
- WARN_DEPRECATED
+ WARN_DEPRECATED;
} break;
case MATH_STEP_DECIMALS: {
VALIDATE_ARG_COUNT(1);
@@ -398,6 +406,13 @@ void GDScriptFunctions::call(Function p_func, const Variant **p_args, int p_arg_
VALIDATE_ARG_NUM(2);
r_ret = Math::smoothstep((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]);
} break;
+ case MATH_MOVE_TOWARD: {
+ VALIDATE_ARG_COUNT(3);
+ VALIDATE_ARG_NUM(0);
+ VALIDATE_ARG_NUM(1);
+ VALIDATE_ARG_NUM(2);
+ r_ret = Math::move_toward((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]);
+ } break;
case MATH_DECTIME: {
VALIDATE_ARG_COUNT(3);
VALIDATE_ARG_NUM(0);
@@ -1448,6 +1463,7 @@ bool GDScriptFunctions::is_deterministic(Function p_func) {
case MATH_SQRT:
case MATH_FMOD:
case MATH_FPOSMOD:
+ case MATH_POSMOD:
case MATH_FLOOR:
case MATH_CEIL:
case MATH_ROUND:
@@ -1466,6 +1482,7 @@ bool GDScriptFunctions::is_deterministic(Function p_func) {
case MATH_INVERSE_LERP:
case MATH_RANGE_LERP:
case MATH_SMOOTHSTEP:
+ case MATH_MOVE_TOWARD:
case MATH_DECTIME:
case MATH_DEG2RAD:
case MATH_RAD2DEG:
@@ -1559,15 +1576,20 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) {
return mi;
} break;
case MATH_FMOD: {
- MethodInfo mi("fmod", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y"));
+ MethodInfo mi("fmod", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b"));
mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_FPOSMOD: {
- MethodInfo mi("fposmod", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y"));
+ MethodInfo mi("fposmod", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b"));
mi.return_val.type = Variant::REAL;
return mi;
} break;
+ case MATH_POSMOD: {
+ MethodInfo mi("posmod", PropertyInfo(Variant::INT, "a"), PropertyInfo(Variant::INT, "b"));
+ mi.return_val.type = Variant::INT;
+ return mi;
+ } break;
case MATH_FLOOR: {
MethodInfo mi("floor", PropertyInfo(Variant::REAL, "s"));
mi.return_val.type = Variant::REAL;
@@ -1594,7 +1616,7 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) {
return mi;
} break;
case MATH_POW: {
- MethodInfo mi("pow", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y"));
+ MethodInfo mi("pow", PropertyInfo(Variant::REAL, "base"), PropertyInfo(Variant::REAL, "exp"));
mi.return_val.type = Variant::REAL;
return mi;
} break;
@@ -1669,6 +1691,11 @@ MethodInfo GDScriptFunctions::get_info(Function p_func) {
mi.return_val.type = Variant::REAL;
return mi;
} break;
+ case MATH_MOVE_TOWARD: {
+ MethodInfo mi("move_toward", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to"), PropertyInfo(Variant::REAL, "delta"));
+ mi.return_val.type = Variant::REAL;
+ return mi;
+ } break;
case MATH_DECTIME: {
MethodInfo mi("dectime", PropertyInfo(Variant::REAL, "value"), PropertyInfo(Variant::REAL, "amount"), PropertyInfo(Variant::REAL, "step"));
mi.return_val.type = Variant::REAL;
diff --git a/modules/gdscript/gdscript_functions.h b/modules/gdscript/gdscript_functions.h
index c594480ff8..d52b9118d3 100644
--- a/modules/gdscript/gdscript_functions.h
+++ b/modules/gdscript/gdscript_functions.h
@@ -49,6 +49,7 @@ public:
MATH_SQRT,
MATH_FMOD,
MATH_FPOSMOD,
+ MATH_POSMOD,
MATH_FLOOR,
MATH_CEIL,
MATH_ROUND,
@@ -69,6 +70,7 @@ public:
MATH_INVERSE_LERP,
MATH_RANGE_LERP,
MATH_SMOOTHSTEP,
+ MATH_MOVE_TOWARD,
MATH_DECTIME,
MATH_RANDOMIZE,
MATH_RAND,
diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp
index 1c22c4af3c..fa430b5364 100644
--- a/modules/gdscript/gdscript_parser.cpp
+++ b/modules/gdscript/gdscript_parser.cpp
@@ -125,7 +125,7 @@ bool GDScriptParser::_enter_indent_block(BlockNode *p_block) {
}
}
-bool GDScriptParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete) {
+bool GDScriptParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete, bool p_parsing_constant) {
if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
tokenizer->advance();
@@ -149,7 +149,7 @@ bool GDScriptParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bo
return false;
}
- Node *arg = _parse_expression(p_parent, p_static);
+ Node *arg = _parse_expression(p_parent, p_static, false, p_parsing_constant);
if (!arg) {
return false;
}
@@ -463,7 +463,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
}
if (!path.is_abs_path() && base_path != "")
- path = base_path + "/" + path;
+ path = base_path.plus_file(path);
path = path.replace("///", "//").simplify_path();
if (path == self_path) {
@@ -639,7 +639,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
id->name = identifier;
op->arguments.push_back(id);
- if (!_parse_arguments(op, op->arguments, p_static, true))
+ if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant))
return NULL;
expr = op;
@@ -731,7 +731,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
completion_node = op;
}
if (!replaced) {
- if (!_parse_arguments(op, op->arguments, p_static, true))
+ if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant))
return NULL;
expr = op;
}
@@ -826,11 +826,12 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
}
// Check parents for the constant
- if (!bfn && cln->extends_file != StringName()) {
- Ref<GDScript> parent = ResourceLoader::load(cln->extends_file);
- if (parent.is_valid() && parent->is_valid()) {
+ if (!bfn) {
+ // Using current_class instead of cln here, since cln is const*
+ _determine_inheritance(current_class, false);
+ if (cln->base_type.has_type && cln->base_type.kind == DataType::GDSCRIPT && cln->base_type.script_type->is_valid()) {
Map<StringName, Variant> parent_constants;
- parent->get_constants(&parent_constants);
+ current_class->base_type.script_type->get_constants(&parent_constants);
if (parent_constants.has(identifier)) {
ConstantNode *constant = alloc_node<ConstantNode>();
constant->value = parent_constants[identifier];
@@ -847,24 +848,11 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
if (current_function) {
int arg_idx = current_function->arguments.find(identifier);
if (arg_idx != -1) {
- switch (tokenizer->get_token()) {
- case GDScriptTokenizer::TK_OP_ASSIGN_ADD:
- case GDScriptTokenizer::TK_OP_ASSIGN_BIT_AND:
- case GDScriptTokenizer::TK_OP_ASSIGN_BIT_OR:
- case GDScriptTokenizer::TK_OP_ASSIGN_BIT_XOR:
- case GDScriptTokenizer::TK_OP_ASSIGN_DIV:
- case GDScriptTokenizer::TK_OP_ASSIGN_MOD:
- case GDScriptTokenizer::TK_OP_ASSIGN_MUL:
- case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_LEFT:
- case GDScriptTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT:
- case GDScriptTokenizer::TK_OP_ASSIGN_SUB:
- case GDScriptTokenizer::TK_OP_ASSIGN: {
- // Assignment is not really usage
- current_function->arguments_usage.write[arg_idx] = current_function->arguments_usage[arg_idx] - 1;
- } break;
- default: {
- current_function->arguments_usage.write[arg_idx] = current_function->arguments_usage[arg_idx] + 1;
- }
+ if (tokenizer->get_token() == GDScriptTokenizer::TK_OP_ASSIGN) {
+ // Assignment is not really usage
+ current_function->arguments_usage.write[arg_idx] = current_function->arguments_usage[arg_idx] - 1;
+ } else {
+ current_function->arguments_usage.write[arg_idx] = current_function->arguments_usage[arg_idx] + 1;
}
}
}
@@ -1125,7 +1113,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
}
} else {
tokenizer->advance();
- if (!_parse_arguments(op, op->arguments, p_static)) {
+ if (!_parse_arguments(op, op->arguments, p_static, false, p_parsing_constant)) {
return NULL;
}
}
@@ -1150,7 +1138,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
if (!expr) {
ERR_EXPLAIN("GDScriptParser bug, couldn't figure out what expression is...");
- ERR_FAIL_COND_V(!expr, NULL);
+ ERR_FAIL_V(NULL);
}
/******************/
@@ -1177,22 +1165,14 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
tokenizer->advance();
IdentifierNode *id = alloc_node<IdentifierNode>();
- if (tokenizer->get_token() == GDScriptTokenizer::TK_BUILT_IN_FUNC) {
- //small hack so built in funcs don't obfuscate methods
-
- id->name = GDScriptFunctions::get_func_name(tokenizer->get_token_built_in_func());
- tokenizer->advance();
-
- } else {
- StringName identifier;
- if (_get_completable_identifier(COMPLETION_METHOD, identifier)) {
- completion_node = op;
- //indexing stuff
- }
-
- id->name = identifier;
+ StringName identifier;
+ if (_get_completable_identifier(COMPLETION_METHOD, identifier)) {
+ completion_node = op;
+ //indexing stuff
}
+ id->name = identifier;
+
op->arguments.push_back(expr); // call what
op->arguments.push_back(id); // call func
//get arguments
@@ -1201,7 +1181,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
_make_completable_call(0);
completion_node = op;
}
- if (!_parse_arguments(op, op->arguments, p_static, true))
+ if (!_parse_arguments(op, op->arguments, p_static, true, p_parsing_constant))
return NULL;
expr = op;
@@ -1493,7 +1473,7 @@ GDScriptParser::Node *GDScriptParser::_parse_expression(Node *p_parent, bool p_s
if (next_op == -1) {
_set_error("Yet another parser bug....");
- ERR_FAIL_COND_V(next_op == -1, NULL);
+ ERR_FAIL_V(NULL);
}
// OK! create operator..
@@ -1995,7 +1975,6 @@ GDScriptParser::Node *GDScriptParser::_reduce_expression(Node *p_node, bool p_to
}
}
- ERR_FAIL_V(op);
} break;
default: {
return p_node;
@@ -2232,6 +2211,8 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran
p_block->has_return = true;
+ bool catch_all_appeared = false;
+
while (true) {
while (tokenizer->get_token() == GDScriptTokenizer::TK_NEWLINE && _parse_newline())
@@ -2242,7 +2223,7 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran
return;
if (indent_level > tab_level.back()->get()) {
- return; // go back a level
+ break; // go back a level
}
if (pending_newline != -1) {
@@ -2257,12 +2238,20 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran
branch->patterns.push_back(_parse_pattern(p_static));
if (!branch->patterns[0]) {
- return;
+ break;
}
bool has_binding = branch->patterns[0]->pt_type == PatternNode::PT_BIND;
bool catch_all = has_binding || branch->patterns[0]->pt_type == PatternNode::PT_WILDCARD;
+#ifdef DEBUG_ENABLED
+ // Branches after a wildcard or binding are unreachable
+ if (catch_all_appeared && !current_function->has_unreachable_code) {
+ _add_warning(GDScriptWarning::UNREACHABLE_CODE, -1, current_function->name.operator String());
+ current_function->has_unreachable_code = true;
+ }
+#endif
+
while (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
tokenizer->advance();
branch->patterns.push_back(_parse_pattern(p_static));
@@ -2280,6 +2269,8 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran
catch_all = catch_all || pt == PatternNode::PT_WILDCARD;
}
+ catch_all_appeared = catch_all_appeared || catch_all;
+
if (!_enter_indent_block()) {
_set_error("Expected block in pattern branch");
return;
@@ -2295,6 +2286,11 @@ void GDScriptParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBran
p_branches.push_back(branch);
}
+
+ // Even if all branches return, there is possibility of default fallthrough
+ if (!catch_all_appeared) {
+ p_block->has_return = false;
+ }
}
void GDScriptParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node *> &p_bindings) {
@@ -3369,7 +3365,7 @@ void GDScriptParser::_parse_extends(ClassNode *p_class) {
return;
}
- if (!p_class->constant_expressions.empty() || !p_class->subclasses.empty() || !p_class->functions.empty() || !p_class->variables.empty()) {
+ if (!p_class->constant_expressions.empty() || !p_class->subclasses.empty() || !p_class->functions.empty() || !p_class->variables.empty() || p_class->classname_used) {
_set_error("'extends' must be used before anything else.");
return;
@@ -3497,7 +3493,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
_set_error("'class_name' is only valid for the main class namespace.");
return;
}
- if (self_path.empty()) {
+ if (self_path.begins_with("res://") && self_path.find("::") != -1) {
_set_error("'class_name' not allowed in built-in scripts.");
return;
}
@@ -3506,6 +3502,12 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
_set_error("'class_name' syntax: 'class_name <UniqueName>'");
return;
}
+ if (p_class->classname_used) {
+ _set_error("'class_name' already used for this class.");
+ return;
+ }
+
+ p_class->classname_used = true;
p_class->name = tokenizer->get_token_identifier(1);
@@ -4019,7 +4021,7 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() == GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
ERR_EXPLAIN("Exporting bit flags hint requires string constants.");
- WARN_DEPRECATED
+ WARN_DEPRECATED;
break;
}
if (tokenizer->get_token() != GDScriptTokenizer::TK_COMMA) {
@@ -4062,6 +4064,50 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
break;
}
+ if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_2D_RENDER") {
+
+ tokenizer->advance();
+ if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
+ _set_error("Expected ')' in layers 2D render hint.");
+ return;
+ }
+ current_export.hint = PROPERTY_HINT_LAYERS_2D_RENDER;
+ break;
+ }
+
+ if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_2D_PHYSICS") {
+
+ tokenizer->advance();
+ if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
+ _set_error("Expected ')' in layers 2D physics hint.");
+ return;
+ }
+ current_export.hint = PROPERTY_HINT_LAYERS_2D_PHYSICS;
+ break;
+ }
+
+ if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_3D_RENDER") {
+
+ tokenizer->advance();
+ if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
+ _set_error("Expected ')' in layers 3D render hint.");
+ return;
+ }
+ current_export.hint = PROPERTY_HINT_LAYERS_3D_RENDER;
+ break;
+ }
+
+ if (tokenizer->get_token() == GDScriptTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "LAYERS_3D_PHYSICS") {
+
+ tokenizer->advance();
+ if (tokenizer->get_token() != GDScriptTokenizer::TK_PARENTHESIS_CLOSE) {
+ _set_error("Expected ')' in layers 3D physics hint.");
+ return;
+ }
+ current_export.hint = PROPERTY_HINT_LAYERS_3D_PHYSICS;
+ break;
+ }
+
if (tokenizer->get_token() == GDScriptTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) {
//enumeration
current_export.hint = PROPERTY_HINT_ENUM;
@@ -5048,6 +5094,9 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
if (tokenizer->get_token() == GDScriptTokenizer::TK_COMMA) {
tokenizer->advance();
+ } else if (tokenizer->is_token_literal(0, true)) {
+ _set_error("Unexpected identifier");
+ return;
}
if (enum_name != "") {
@@ -5122,9 +5171,11 @@ void GDScriptParser::_parse_class(ClassNode *p_class) {
}
}
-void GDScriptParser::_determine_inheritance(ClassNode *p_class) {
+void GDScriptParser::_determine_inheritance(ClassNode *p_class, bool p_recursive) {
- if (p_class->extends_used) {
+ if (p_class->base_type.has_type) {
+ // Already determined
+ } else if (p_class->extends_used) {
//do inheritance
String path = p_class->extends_file;
@@ -5319,9 +5370,11 @@ void GDScriptParser::_determine_inheritance(ClassNode *p_class) {
p_class->base_type.native_type = "Reference";
}
- // Recursively determine subclasses
- for (int i = 0; i < p_class->subclasses.size(); i++) {
- _determine_inheritance(p_class->subclasses[i]);
+ if (p_recursive) {
+ // Recursively determine subclasses
+ for (int i = 0; i < p_class->subclasses.size(); i++) {
+ _determine_inheritance(p_class->subclasses[i], p_recursive);
+ }
}
}
@@ -5895,11 +5948,8 @@ bool GDScriptParser::_is_type_compatible(const DataType &p_container, const Data
if (p_container.kind == DataType::BUILTIN && p_container.builtin_type == Variant::OBJECT) {
// Object built-in is a special case, it's compatible with any object and with null
- if (p_expression.kind == DataType::BUILTIN && p_expression.builtin_type == Variant::NIL) {
- return true;
- }
if (p_expression.kind == DataType::BUILTIN) {
- return false;
+ return p_expression.builtin_type == Variant::NIL;
}
// If it's not a built-in, must be an object
return true;
@@ -6015,7 +6065,11 @@ bool GDScriptParser::_is_type_compatible(const DataType &p_container, const Data
}
GDScriptParser::DataType GDScriptParser::_reduce_node_type(Node *p_node) {
+#ifdef DEBUG_ENABLED
+ if (p_node->get_datatype().has_type && p_node->type != Node::TYPE_ARRAY && p_node->type != Node::TYPE_DICTIONARY) {
+#else
if (p_node->get_datatype().has_type) {
+#endif
return p_node->get_datatype();
}
diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h
index 809bff8f20..62d7bdb393 100644
--- a/modules/gdscript/gdscript_parser.h
+++ b/modules/gdscript/gdscript_parser.h
@@ -149,6 +149,7 @@ public:
bool tool;
StringName name;
bool extends_used;
+ bool classname_used;
StringName extends_file;
Vector<StringName> extends_class;
DataType base_type;
@@ -198,6 +199,7 @@ public:
tool = false;
type = TYPE_CLASS;
extends_used = false;
+ classname_used = false;
end_line = -1;
owner = NULL;
}
@@ -580,7 +582,7 @@ private:
#endif // DEBUG_ENABLED
bool _recover_from_completion();
- bool _parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete = false);
+ bool _parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete = false, bool p_parsing_constant = false);
bool _enter_indent_block(BlockNode *p_block = NULL);
bool _parse_newline();
Node *_parse_expression(Node *p_parent, bool p_static, bool p_allow_assign = false, bool p_parsing_constant = false);
@@ -597,7 +599,7 @@ private:
void _parse_class(ClassNode *p_class);
bool _end_statement();
- void _determine_inheritance(ClassNode *p_class);
+ void _determine_inheritance(ClassNode *p_class, bool p_recursive = true);
bool _parse_type(DataType &r_type, bool p_can_be_void = false);
DataType _resolve_type(const DataType &p_source, int p_line);
DataType _type_from_variant(const Variant &p_value) const;
diff --git a/modules/gdscript/gdscript_tokenizer.cpp b/modules/gdscript/gdscript_tokenizer.cpp
index b8048fb5dd..95715ab648 100644
--- a/modules/gdscript/gdscript_tokenizer.cpp
+++ b/modules/gdscript/gdscript_tokenizer.cpp
@@ -376,6 +376,11 @@ static bool _is_hex(CharType c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
+static bool _is_bin(CharType c) {
+
+ return (c == '0' || c == '1');
+}
+
void GDScriptTokenizerText::_make_token(Token p_type) {
TokenData &tk = tk_rb[tk_rb_pos];
@@ -877,6 +882,7 @@ void GDScriptTokenizerText::_advance() {
bool period_found = false;
bool exponent_found = false;
bool hexa_found = false;
+ bool bin_found = false;
bool sign_found = false;
String str;
@@ -887,16 +893,28 @@ void GDScriptTokenizerText::_advance() {
if (period_found || exponent_found) {
_make_error("Invalid numeric constant at '.'");
return;
+ } else if (bin_found) {
+ _make_error("Invalid binary constant at '.'");
+ return;
+ } else if (hexa_found) {
+ _make_error("Invalid hexadecimal constant at '.'");
+ return;
}
period_found = true;
} else if (GETCHAR(i) == 'x') {
- if (hexa_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) {
+ if (hexa_found || bin_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) {
_make_error("Invalid numeric constant at 'x'");
return;
}
hexa_found = true;
+ } else if (GETCHAR(i) == 'b') {
+ if (hexa_found || bin_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) {
+ _make_error("Invalid numeric constant at 'b'");
+ return;
+ }
+ bin_found = true;
} else if (!hexa_found && GETCHAR(i) == 'e') {
- if (exponent_found) {
+ if (exponent_found || bin_found) {
_make_error("Invalid numeric constant at 'e'");
return;
}
@@ -905,6 +923,8 @@ void GDScriptTokenizerText::_advance() {
//all ok
} else if (hexa_found && _is_hex(GETCHAR(i))) {
+ } else if (bin_found && _is_bin(GETCHAR(i))) {
+
} else if ((GETCHAR(i) == '-' || GETCHAR(i) == '+') && exponent_found) {
if (sign_found) {
_make_error("Invalid numeric constant at '-'");
@@ -930,6 +950,9 @@ void GDScriptTokenizerText::_advance() {
if (hexa_found) {
int64_t val = str.hex_to_int64();
_make_constant(val);
+ } else if (bin_found) {
+ int64_t val = str.bin_to_int64();
+ _make_constant(val);
} else if (period_found || exponent_found) {
double val = str.to_double();
_make_constant(val);
@@ -1166,7 +1189,7 @@ Error GDScriptTokenizerBuffer::set_code_buffer(const Vector<uint8_t> &p_buffer)
int version = decode_uint32(&buf[4]);
if (version > BYTECODE_VERSION) {
ERR_EXPLAIN("Bytecode is too New! Please use a newer engine version.");
- ERR_FAIL_COND_V(version > BYTECODE_VERSION, ERR_INVALID_DATA);
+ ERR_FAIL_V(ERR_INVALID_DATA);
}
int identifier_count = decode_uint32(&buf[8]);
int constant_count = decode_uint32(&buf[12]);
@@ -1280,7 +1303,7 @@ Vector<uint8_t> GDScriptTokenizerBuffer::parse_code_string(const String &p_code)
} break;
case TK_CONSTANT: {
- Variant c = tt.get_token_constant();
+ const Variant &c = tt.get_token_constant();
if (!constant_map.has(c)) {
int idx = constant_map.size();
constant_map[c] = idx;
diff --git a/modules/gdscript/icons/icon_g_d_script.svg b/modules/gdscript/icons/icon_g_d_script.svg
new file mode 100644
index 0000000000..953bb9ae9e
--- /dev/null
+++ b/modules/gdscript/icons/icon_g_d_script.svg
@@ -0,0 +1,5 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g transform="translate(0 -1036.4)">
+<path transform="translate(0 1036.4)" d="m7 1l-0.56445 2.2578a5 5 0 0 0 -0.68945 0.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -0.28516 0.68555l-2.2539 0.5625v2l2.2578 0.56445a5 5 0 0 0 0.2793 0.6875l-1.1934 1.9902 1.4141 1.4141 1.9941-1.1953a5 5 0 0 0 0.68555 0.28516l0.5625 2.2539h2l0.56445-2.2578a5 5 0 0 0 0.6875 -0.2793l1.9902 1.1934 1.4141-1.4141-1.1953-1.9941a5 5 0 0 0 0.28516 -0.68555l2.2539-0.5625v-2l-2.2578-0.56445a5 5 0 0 0 -0.2793 -0.6875l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -0.68555 -0.28516l-0.5625-2.2539h-2zm1 5a2 2 0 0 1 2 2 2 2 0 0 1 -2 2 2 2 0 0 1 -2 -2 2 2 0 0 1 2 -2z" fill="#e0e0e0"/>
+</g>
+</svg>
diff --git a/modules/gridmap/doc_classes/GridMap.xml b/modules/gridmap/doc_classes/GridMap.xml
index f8f9fc1af9..1bd3d72066 100644
--- a/modules/gridmap/doc_classes/GridMap.xml
+++ b/modules/gridmap/doc_classes/GridMap.xml
@@ -86,14 +86,14 @@
<return type="Array">
</return>
<description>
- Array of [Transform] and [Mesh] references corresponding to the non empty cells in the grid. The transforms are specified in world space.
+ Array of [Transform] and [Mesh] references corresponding to the non-empty cells in the grid. The transforms are specified in world space.
</description>
</method>
<method name="get_used_cells" qualifiers="const">
<return type="Array">
</return>
<description>
- Array of [Vector3] with the non empty cell coordinates in the grid map.
+ Array of [Vector3] with the non-empty cell coordinates in the grid map.
</description>
</method>
<method name="make_baked_meshes">
@@ -189,26 +189,26 @@
</method>
</methods>
<members>
- <member name="cell_center_x" type="bool" setter="set_center_x" getter="get_center_x">
+ <member name="cell_center_x" type="bool" setter="set_center_x" getter="get_center_x" default="true">
If [code]true[/code], grid items are centered on the X axis.
</member>
- <member name="cell_center_y" type="bool" setter="set_center_y" getter="get_center_y">
+ <member name="cell_center_y" type="bool" setter="set_center_y" getter="get_center_y" default="true">
If [code]true[/code], grid items are centered on the Y axis.
</member>
- <member name="cell_center_z" type="bool" setter="set_center_z" getter="get_center_z">
+ <member name="cell_center_z" type="bool" setter="set_center_z" getter="get_center_z" default="true">
If [code]true[/code], grid items are centered on the Z axis.
</member>
- <member name="cell_octant_size" type="int" setter="set_octant_size" getter="get_octant_size">
+ <member name="cell_octant_size" type="int" setter="set_octant_size" getter="get_octant_size" default="8">
The size of each octant measured in number of cells. This applies to all three axis.
</member>
- <member name="cell_scale" type="float" setter="set_cell_scale" getter="get_cell_scale">
+ <member name="cell_scale" type="float" setter="set_cell_scale" getter="get_cell_scale" default="1.0">
</member>
- <member name="cell_size" type="Vector3" setter="set_cell_size" getter="get_cell_size">
+ <member name="cell_size" type="Vector3" setter="set_cell_size" getter="get_cell_size" default="Vector3( 2, 2, 2 )">
The dimensions of the grid's cells.
</member>
- <member name="collision_layer" type="int" setter="set_collision_layer" getter="get_collision_layer">
+ <member name="collision_layer" type="int" setter="set_collision_layer" getter="get_collision_layer" default="1">
</member>
- <member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask">
+ <member name="collision_mask" type="int" setter="set_collision_mask" getter="get_collision_mask" default="1">
</member>
<member name="mesh_library" type="MeshLibrary" setter="set_mesh_library" getter="get_mesh_library">
The assigned [MeshLibrary].
diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index 32a014e76d..994a84fbc4 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -197,7 +197,7 @@ bool GridMap::get_collision_layer_bit(int p_bit) const {
void GridMap::set_theme(const Ref<MeshLibrary> &p_theme) {
ERR_EXPLAIN("GridMap.theme/set_theme() is deprecated and will be removed in a future version. Use GridMap.mesh_library/set_mesh_library() instead.");
- WARN_DEPRECATED
+ WARN_DEPRECATED;
set_mesh_library(p_theme);
}
@@ -205,7 +205,7 @@ void GridMap::set_theme(const Ref<MeshLibrary> &p_theme) {
Ref<MeshLibrary> GridMap::get_theme() const {
ERR_EXPLAIN("GridMap.theme/get_theme() is deprecated and will be removed in a future version. Use GridMap.mesh_library/get_mesh_library() instead.");
- WARN_DEPRECATED
+ WARN_DEPRECATED;
return get_mesh_library();
}
@@ -241,6 +241,7 @@ Vector3 GridMap::get_cell_size() const {
void GridMap::set_octant_size(int p_size) {
+ ERR_FAIL_COND(p_size == 0);
octant_size = p_size;
_recreate_octant_data();
}
diff --git a/modules/gridmap/grid_map_editor_plugin.cpp b/modules/gridmap/grid_map_editor_plugin.cpp
index 657aa1f9ce..5a21833ffa 100644
--- a/modules/gridmap/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/grid_map_editor_plugin.cpp
@@ -235,7 +235,7 @@ void GridMapEditor::_menu_option(int p_option) {
options->get_popup()->set_item_checked(idx, !options->get_popup()->is_item_checked(idx));
} break;
- case MENU_OPTION_SELECTION_DUPLICATE: // fallthrough
+ case MENU_OPTION_SELECTION_DUPLICATE:
case MENU_OPTION_SELECTION_CUT: {
if (!(selection.active && input_action == INPUT_NONE))
break;
@@ -279,7 +279,7 @@ void GridMapEditor::_update_cursor_transform() {
cursor_transform = Transform();
cursor_transform.origin = cursor_origin;
cursor_transform.basis.set_orthogonal_index(cursor_rot);
- cursor_transform = node->get_transform() * cursor_transform;
+ cursor_transform = node->get_global_transform() * cursor_transform;
if (cursor_instance.is_valid()) {
VisualServer::get_singleton()->instance_set_transform(cursor_instance, cursor_transform);
@@ -345,7 +345,7 @@ void GridMapEditor::_validate_selection() {
_update_selection_transform();
}
-void GridMapEditor::_set_selection(bool p_active, const Vector3 p_begin, const Vector3 p_end) {
+void GridMapEditor::_set_selection(bool p_active, const Vector3 &p_begin, const Vector3 &p_end) {
selection.active = p_active;
selection.begin = p_begin;
@@ -420,7 +420,7 @@ bool GridMapEditor::do_input_action(Camera *p_camera, const Point2 &p_point, boo
}
last_mouseover = Vector3(cell[0], cell[1], cell[2]);
- VS::get_singleton()->instance_set_transform(grid_instance[edit_axis], Transform(Basis(), grid_ofs));
+ VS::get_singleton()->instance_set_transform(grid_instance[edit_axis], node->get_global_transform() * edit_grid_xform);
if (cursor_instance.is_valid()) {
@@ -578,7 +578,7 @@ void GridMapEditor::_update_paste_indicator() {
return;
}
- Vector3 center = 0.5 * Vector3(node->get_center_x(), node->get_center_y(), node->get_center_z());
+ Vector3 center = 0.5 * Vector3(float(node->get_center_x()), float(node->get_center_y()), float(node->get_center_z()));
Vector3 scale = (Vector3(1, 1, 1) + (paste_indicator.end - paste_indicator.begin)) * node->get_cell_size();
Transform xf;
xf.scale(scale);
@@ -664,8 +664,10 @@ bool GridMapEditor::forward_spatial_input_event(Camera *p_camera, const Ref<Inpu
}
if (mb->is_pressed()) {
-
- if (mb->get_button_index() == BUTTON_LEFT) {
+ SpatialEditorViewport::NavigationScheme nav_scheme = (SpatialEditorViewport::NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
+ if ((nav_scheme == SpatialEditorViewport::NAVIGATION_MAYA || nav_scheme == SpatialEditorViewport::NAVIGATION_MODO) && mb->get_alt()) {
+ input_action = INPUT_NONE;
+ } else if (mb->get_button_index() == BUTTON_LEFT) {
if (input_action == INPUT_PASTE) {
_do_paste();
@@ -1179,6 +1181,10 @@ void GridMapEditor::_floor_changed(float p_value) {
_update_selection_transform();
}
+void GridMapEditor::_floor_mouse_exited() {
+ floor->get_line_edit()->release_focus();
+}
+
void GridMapEditor::_bind_methods() {
ClassDB::bind_method("_text_changed", &GridMapEditor::_text_changed);
@@ -1188,6 +1194,7 @@ void GridMapEditor::_bind_methods() {
ClassDB::bind_method("_configure", &GridMapEditor::_configure);
ClassDB::bind_method("_item_selected_cbk", &GridMapEditor::_item_selected_cbk);
ClassDB::bind_method("_floor_changed", &GridMapEditor::_floor_changed);
+ ClassDB::bind_method("_floor_mouse_exited", &GridMapEditor::_floor_mouse_exited);
ClassDB::bind_method("_set_selection", &GridMapEditor::_set_selection);
ClassDB::bind_method(D_METHOD("_set_display_mode", "mode"), &GridMapEditor::_set_display_mode);
@@ -1221,6 +1228,8 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
spatial_editor_hb->add_child(floor);
floor->connect("value_changed", this, "_floor_changed");
+ floor->connect("mouse_exited", this, "_floor_mouse_exited");
+ floor->get_line_edit()->connect("mouse_exited", this, "_floor_mouse_exited");
spatial_editor_hb->add_child(memnew(VSeparator));
diff --git a/modules/gridmap/grid_map_editor_plugin.h b/modules/gridmap/grid_map_editor_plugin.h
index 8e1948ea7d..b9be925ff7 100644
--- a/modules/gridmap/grid_map_editor_plugin.h
+++ b/modules/gridmap/grid_map_editor_plugin.h
@@ -222,9 +222,10 @@ class GridMapEditor : public VBoxContainer {
void _do_paste();
void _update_selection_transform();
void _validate_selection();
- void _set_selection(bool p_active, const Vector3 p_begin = Vector3(), const Vector3 p_end = Vector3());
+ void _set_selection(bool p_active, const Vector3 &p_begin = Vector3(), const Vector3 &p_end = Vector3());
void _floor_changed(float p_value);
+ void _floor_mouse_exited();
void _delete_selection();
void _fill_selection();
diff --git a/modules/gridmap/icons/icon_grid_map.svg b/modules/gridmap/icons/icon_grid_map.svg
new file mode 100644
index 0000000000..eafe1211f2
--- /dev/null
+++ b/modules/gridmap/icons/icon_grid_map.svg
@@ -0,0 +1,5 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g transform="translate(0 -1036.4)">
+<path transform="translate(0 1036.4)" d="m8 1-6 3v8l6 3 6-3v-2l-2-1-4 2-2-1v-4l2-1v-2l2-1zm4 2-2 1v2l2 1 2-1v-2z" fill="#fc9c9c" fill-opacity=".99608"/>
+</g>
+</svg>
diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp
index 5493223cb0..dcd8b8aebd 100644
--- a/modules/jpg/image_loader_jpegd.cpp
+++ b/modules/jpg/image_loader_jpegd.cpp
@@ -96,7 +96,7 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p
else
fmt = Image::FORMAT_RGB8;
- dw = PoolVector<uint8_t>::Write();
+ dw.release();
p_image->create(image_width, image_height, 0, fmt, data);
return OK;
@@ -117,8 +117,6 @@ Error ImageLoaderJPG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force
Error err = jpeg_load_image_from_buffer(p_image.ptr(), w.ptr(), src_image_len);
- w = PoolVector<uint8_t>::Write();
-
return err;
}
diff --git a/modules/mbedtls/stream_peer_mbed_tls.cpp b/modules/mbedtls/stream_peer_mbed_tls.cpp
index 45d3b86919..4bb7557150 100755
--- a/modules/mbedtls/stream_peer_mbed_tls.cpp
+++ b/modules/mbedtls/stream_peer_mbed_tls.cpp
@@ -33,8 +33,6 @@
#include "core/io/stream_peer_tcp.h"
#include "core/os/file_access.h"
-#include <mbedtls/platform_util.h>
-
static void my_debug(void *ctx, int level,
const char *file, int line,
const char *str) {
@@ -122,6 +120,8 @@ Error StreamPeerMbedTLS::_do_handshake() {
Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname) {
+ ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER);
+
base = p_base;
int ret = 0;
int authmode = p_validate_certs ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE;
diff --git a/modules/mbedtls/stream_peer_mbed_tls.h b/modules/mbedtls/stream_peer_mbed_tls.h
index 3ddbea3ce4..ab87b779c1 100755
--- a/modules/mbedtls/stream_peer_mbed_tls.h
+++ b/modules/mbedtls/stream_peer_mbed_tls.h
@@ -37,7 +37,6 @@
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/debug.h>
#include <mbedtls/entropy.h>
-#include <mbedtls/net.h>
#include <mbedtls/ssl.h>
#include <stdio.h>
diff --git a/modules/mobile_vr/doc_classes/MobileVRInterface.xml b/modules/mobile_vr/doc_classes/MobileVRInterface.xml
index 8876bcbe9d..a132333a87 100644
--- a/modules/mobile_vr/doc_classes/MobileVRInterface.xml
+++ b/modules/mobile_vr/doc_classes/MobileVRInterface.xml
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="MobileVRInterface" inherits="ARVRInterface" category="Core" version="3.2">
<brief_description>
- Generic mobile VR implementation
+ Generic mobile VR implementation.
</brief_description>
<description>
- This is a generic mobile VR implementation where you need to provide details about the phone and HMD used. It does not rely on any existing framework. This is the most basic interface we have. For the best effect you do need a mobile phone with a gyroscope and accelerometer.
- Note that even though there is no positional tracking the camera will assume the headset is at a height of 1.85 meters, you can change this by setting [member eye_height].
+ This is a generic mobile VR implementation where you need to provide details about the phone and HMD used. It does not rely on any existing framework. This is the most basic interface we have. For the best effect, you need a mobile phone with a gyroscope and accelerometer.
+ Note that even though there is no positional tracking, the camera will assume the headset is at a height of 1.85 meters. You can change this by setting [member eye_height].
You can initialise this interface as follows:
[codeblock]
var interface = ARVRServer.find_interface("Native mobile")
@@ -18,25 +18,25 @@
<methods>
</methods>
<members>
- <member name="display_to_lens" type="float" setter="set_display_to_lens" getter="get_display_to_lens">
+ <member name="display_to_lens" type="float" setter="set_display_to_lens" getter="get_display_to_lens" default="4.0">
The distance between the display and the lenses inside of the device in centimeters.
</member>
- <member name="display_width" type="float" setter="set_display_width" getter="get_display_width">
+ <member name="display_width" type="float" setter="set_display_width" getter="get_display_width" default="14.5">
The width of the display in centimeters.
</member>
- <member name="eye_height" type="float" setter="set_eye_height" getter="get_eye_height">
+ <member name="eye_height" type="float" setter="set_eye_height" getter="get_eye_height" default="1.85">
The height at which the camera is placed in relation to the ground (i.e. [ARVROrigin] node).
</member>
- <member name="iod" type="float" setter="set_iod" getter="get_iod">
+ <member name="iod" type="float" setter="set_iod" getter="get_iod" default="6.0">
The interocular distance, also known as the interpupillary distance. The distance between the pupils of the left and right eye.
</member>
- <member name="k1" type="float" setter="set_k1" getter="get_k1">
+ <member name="k1" type="float" setter="set_k1" getter="get_k1" default="0.215">
The k1 lens factor is one of the two constants that define the strength of the lens used and directly influences the lens distortion effect.
</member>
- <member name="k2" type="float" setter="set_k2" getter="get_k2">
+ <member name="k2" type="float" setter="set_k2" getter="get_k2" default="0.215">
The k2 lens factor, see k1.
</member>
- <member name="oversample" type="float" setter="set_oversample" getter="get_oversample">
+ <member name="oversample" type="float" setter="set_oversample" getter="get_oversample" default="1.5">
The oversample setting. Because of the lens distortion we have to render our buffers at a higher resolution then the screen can natively handle. A value between 1.5 and 2.0 often provides good results but at the cost of performance.
</member>
</members>
diff --git a/modules/mono/SCsub b/modules/mono/SCsub
index 341d57f3e4..cc60e64a11 100644
--- a/modules/mono/SCsub
+++ b/modules/mono/SCsub
@@ -1,5 +1,8 @@
#!/usr/bin/env python
+import build_scripts.tls_configure as tls_configure
+import build_scripts.mono_configure as mono_configure
+
Import('env')
Import('env_modules')
@@ -20,38 +23,42 @@ if env['tools']:
'glue/cs_glue_version.gen.h'
)
-vars = Variables()
-vars.Add(BoolVariable('mono_glue', 'Build with the mono glue sources', True))
-vars.Add(BoolVariable('xbuild_fallback', 'If MSBuild is not found, fallback to xbuild', False))
-vars.Update(env_mono)
-
# Glue sources
if env_mono['mono_glue']:
env_mono.Append(CPPDEFINES=['MONO_GLUE_ENABLED'])
import os.path
if not os.path.isfile('glue/mono_glue.gen.cpp'):
- raise RuntimeError('Missing mono glue sources. Did you forget to generate them?')
+ raise RuntimeError("Mono glue sources not found. Did you forget to run '--generate-mono-glue'?")
if env_mono['tools'] or env_mono['target'] != 'release':
env_mono.Append(CPPDEFINES=['GD_MONO_HOT_RELOAD'])
# Configure Thread Local Storage
-import build_scripts.tls_configure as tls_configure
-
conf = Configure(env_mono)
tls_configure.configure(conf)
env_mono = conf.Finish()
# Configure Mono
-import build_scripts.mono_configure as mono_configure
-
mono_configure.configure(env, env_mono)
-# Build GodotSharpTools
+# Build Godot API solution
+
+if env_mono['tools'] and env_mono['mono_glue']:
+ import build_scripts.api_solution_build as api_solution_build
+ api_solution_build.build(env_mono)
-import build_scripts.godotsharptools_build as godotsharptools_build
+# Build GodotTools
-godotsharptools_build.build(env_mono)
+if env_mono['tools']:
+ import build_scripts.godot_tools_build as godot_tools_build
+ if env_mono['mono_glue']:
+ godot_tools_build.build(env_mono)
+ else:
+ # Building without the glue sources so the Godot API solution may be missing.
+ # GodotTools depends on the Godot API solution. As such, we will only build
+ # GodotTools.ProjectEditor which doesn't depend on the Godot API solution and
+ # is required by the bindings generator in order to be able to generated it.
+ godot_tools_build.build_project_editor_only(env_mono)
diff --git a/modules/mono/__init__.py b/modules/mono/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/modules/mono/__init__.py
diff --git a/modules/mono/build_scripts/api_solution_build.py b/modules/mono/build_scripts/api_solution_build.py
new file mode 100644
index 0000000000..1fe00a3028
--- /dev/null
+++ b/modules/mono/build_scripts/api_solution_build.py
@@ -0,0 +1,66 @@
+# Build the Godot API solution
+
+import os
+
+from SCons.Script import Dir
+
+
+def build_api_solution(source, target, env):
+ # source and target elements are of type SCons.Node.FS.File, hence why we convert them to str
+
+ module_dir = env['module_dir']
+
+ solution_path = os.path.join(module_dir, 'glue/Managed/Generated/GodotSharp.sln')
+
+ if not os.path.isfile(solution_path):
+ raise RuntimeError("Godot API solution not found. Did you forget to run '--generate-mono-glue'?")
+
+ build_config = env['solution_build_config']
+
+ extra_msbuild_args = ['/p:NoWarn=1591'] # Ignore missing documentation warnings
+
+ from .solution_builder import build_solution
+ build_solution(env, solution_path, build_config, extra_msbuild_args=extra_msbuild_args)
+
+ # Copy targets
+
+ core_src_dir = os.path.abspath(os.path.join(solution_path, os.pardir, 'GodotSharp', 'bin', build_config))
+ editor_src_dir = os.path.abspath(os.path.join(solution_path, os.pardir, 'GodotSharpEditor', 'bin', build_config))
+
+ dst_dir = os.path.abspath(os.path.join(str(target[0]), os.pardir))
+
+ if not os.path.isdir(dst_dir):
+ assert not os.path.isfile(dst_dir)
+ os.makedirs(dst_dir)
+
+ def copy_target(target_path):
+ from shutil import copy
+ filename = os.path.basename(target_path)
+
+ src_path = os.path.join(core_src_dir, filename)
+ if not os.path.isfile(src_path):
+ src_path = os.path.join(editor_src_dir, filename)
+
+ copy(src_path, target_path)
+
+ for scons_target in target:
+ copy_target(str(scons_target))
+
+
+def build(env_mono):
+ assert env_mono['tools']
+
+ target_filenames = [
+ 'GodotSharp.dll', 'GodotSharp.pdb', 'GodotSharp.xml',
+ 'GodotSharpEditor.dll', 'GodotSharpEditor.pdb', 'GodotSharpEditor.xml'
+ ]
+
+ for build_config in ['Debug', 'Release']:
+ output_dir = Dir('#bin').abspath
+ editor_api_dir = os.path.join(output_dir, 'GodotSharp', 'Api', build_config)
+
+ targets = [os.path.join(editor_api_dir, filename) for filename in target_filenames]
+
+ cmd = env_mono.CommandNoCache(targets, [], build_api_solution,
+ module_dir=os.getcwd(), solution_build_config=build_config)
+ env_mono.AlwaysBuild(cmd)
diff --git a/modules/mono/build_scripts/godot_tools_build.py b/modules/mono/build_scripts/godot_tools_build.py
new file mode 100644
index 0000000000..c47cfc8a38
--- /dev/null
+++ b/modules/mono/build_scripts/godot_tools_build.py
@@ -0,0 +1,112 @@
+# Build GodotTools solution
+
+import os
+
+from SCons.Script import Dir
+
+
+def build_godot_tools(source, target, env):
+ # source and target elements are of type SCons.Node.FS.File, hence why we convert them to str
+
+ module_dir = env['module_dir']
+
+ solution_path = os.path.join(module_dir, 'editor/GodotTools/GodotTools.sln')
+ build_config = 'Debug' if env['target'] == 'debug' else 'Release'
+
+ from . solution_builder import build_solution, nuget_restore
+ nuget_restore(env, solution_path)
+ build_solution(env, solution_path, build_config)
+
+ # Copy targets
+
+ solution_dir = os.path.abspath(os.path.join(solution_path, os.pardir))
+
+ src_dir = os.path.join(solution_dir, 'GodotTools', 'bin', build_config)
+ dst_dir = os.path.abspath(os.path.join(str(target[0]), os.pardir))
+
+ if not os.path.isdir(dst_dir):
+ assert not os.path.isfile(dst_dir)
+ os.makedirs(dst_dir)
+
+ def copy_target(target_path):
+ from shutil import copy
+ filename = os.path.basename(target_path)
+ copy(os.path.join(src_dir, filename), target_path)
+
+ for scons_target in target:
+ copy_target(str(scons_target))
+
+
+def build_godot_tools_project_editor(source, target, env):
+ # source and target elements are of type SCons.Node.FS.File, hence why we convert them to str
+
+ module_dir = env['module_dir']
+
+ project_name = 'GodotTools.ProjectEditor'
+
+ csproj_dir = os.path.join(module_dir, 'editor/GodotTools', project_name)
+ csproj_path = os.path.join(csproj_dir, project_name + '.csproj')
+ build_config = 'Debug' if env['target'] == 'debug' else 'Release'
+
+ from . solution_builder import build_solution, nuget_restore
+
+ # Make sure to restore NuGet packages in the project directory for the project to find it
+ nuget_restore(env, os.path.join(csproj_dir, 'packages.config'), '-PackagesDirectory',
+ os.path.join(csproj_dir, 'packages'))
+
+ build_solution(env, csproj_path, build_config)
+
+ # Copy targets
+
+ src_dir = os.path.join(csproj_dir, 'bin', build_config)
+ dst_dir = os.path.abspath(os.path.join(str(target[0]), os.pardir))
+
+ if not os.path.isdir(dst_dir):
+ assert not os.path.isfile(dst_dir)
+ os.makedirs(dst_dir)
+
+ def copy_target(target_path):
+ from shutil import copy
+ filename = os.path.basename(target_path)
+ copy(os.path.join(src_dir, filename), target_path)
+
+ for scons_target in target:
+ copy_target(str(scons_target))
+
+
+def build(env_mono):
+ assert env_mono['tools']
+
+ output_dir = Dir('#bin').abspath
+ editor_tools_dir = os.path.join(output_dir, 'GodotSharp', 'Tools')
+ editor_api_dir = os.path.join(output_dir, 'GodotSharp', 'Api', 'Debug')
+
+ source_filenames = ['GodotSharp.dll', 'GodotSharpEditor.dll']
+ sources = [os.path.join(editor_api_dir, filename) for filename in source_filenames]
+
+ target_filenames = ['GodotTools.dll', 'GodotTools.BuildLogger.dll', 'GodotTools.ProjectEditor.dll', 'DotNet.Glob.dll', 'GodotTools.Core.dll']
+
+ if env_mono['target'] == 'debug':
+ target_filenames += ['GodotTools.pdb', 'GodotTools.BuildLogger.pdb', 'GodotTools.ProjectEditor.pdb', 'GodotTools.Core.pdb']
+
+ targets = [os.path.join(editor_tools_dir, filename) for filename in target_filenames]
+
+ cmd = env_mono.CommandNoCache(targets, sources, build_godot_tools, module_dir=os.getcwd())
+ env_mono.AlwaysBuild(cmd)
+
+
+def build_project_editor_only(env_mono):
+ assert env_mono['tools']
+
+ output_dir = Dir('#bin').abspath
+ editor_tools_dir = os.path.join(output_dir, 'GodotSharp', 'Tools')
+
+ target_filenames = ['GodotTools.ProjectEditor.dll', 'DotNet.Glob.dll', 'GodotTools.Core.dll']
+
+ if env_mono['target'] == 'debug':
+ target_filenames += ['GodotTools.ProjectEditor.pdb', 'GodotTools.Core.pdb']
+
+ targets = [os.path.join(editor_tools_dir, filename) for filename in target_filenames]
+
+ cmd = env_mono.CommandNoCache(targets, [], build_godot_tools_project_editor, module_dir=os.getcwd())
+ env_mono.AlwaysBuild(cmd)
diff --git a/modules/mono/build_scripts/make_android_mono_config.py b/modules/mono/build_scripts/make_android_mono_config.py
new file mode 100644
index 0000000000..cd9210897d
--- /dev/null
+++ b/modules/mono/build_scripts/make_android_mono_config.py
@@ -0,0 +1,69 @@
+
+def generate_compressed_config(config_src, output_dir):
+ import os.path
+ from compat import byte_to_str
+
+ # Header file
+ with open(os.path.join(output_dir, 'android_mono_config.gen.h'), 'w') as header:
+ header.write('''/* THIS FILE IS GENERATED DO NOT EDIT */
+#ifndef ANDROID_MONO_CONFIG_GEN_H
+#define ANDROID_MONO_CONFIG_GEN_H
+
+#ifdef ANDROID_ENABLED
+
+#include "core/ustring.h"
+
+String get_godot_android_mono_config();
+
+#endif // ANDROID_ENABLED
+
+#endif // ANDROID_MONO_CONFIG_GEN_H
+''')
+
+ # Source file
+ with open(os.path.join(output_dir, 'android_mono_config.gen.cpp'), 'w') as cpp:
+ with open(config_src, 'rb') as f:
+ buf = f.read()
+ decompr_size = len(buf)
+ import zlib
+ buf = zlib.compress(buf)
+ compr_size = len(buf)
+
+ bytes_seq_str = ''
+ for i, buf_idx in enumerate(range(compr_size)):
+ if i > 0:
+ bytes_seq_str += ', '
+ bytes_seq_str += byte_to_str(buf[buf_idx])
+
+ cpp.write('''/* THIS FILE IS GENERATED DO NOT EDIT */
+#include "android_mono_config.gen.h"
+
+#ifdef ANDROID_ENABLED
+
+#include "core/io/compression.h"
+#include "core/pool_vector.h"
+
+namespace {
+
+// config
+static const int config_compressed_size = %d;
+static const int config_uncompressed_size = %d;
+static const unsigned char config_compressed_data[] = { %s };
+
+} // namespace
+
+String get_godot_android_mono_config() {
+ PoolVector<uint8_t> data;
+ data.resize(config_uncompressed_size);
+ PoolVector<uint8_t>::Write w = data.write();
+ Compression::decompress(w.ptr(), config_uncompressed_size, config_compressed_data,
+ config_compressed_size, Compression::MODE_DEFLATE);
+ String s;
+ if (s.parse_utf8((const char *)w.ptr(), data.size())) {
+ ERR_FAIL_V(String());
+ }
+ return s;
+}
+
+#endif // ANDROID_ENABLED
+''' % (compr_size, decompr_size, bytes_seq_str))
diff --git a/modules/mono/build_scripts/make_cs_compressed_header.py b/modules/mono/build_scripts/make_cs_compressed_header.py
index 1f9177cef8..ed49db5bb2 100644
--- a/modules/mono/build_scripts/make_cs_compressed_header.py
+++ b/modules/mono/build_scripts/make_cs_compressed_header.py
@@ -23,30 +23,31 @@ def generate_header(src, dst, version_dst):
latest_mtime = mtime if mtime > latest_mtime else latest_mtime
with open(filepath, 'rb') as f:
buf = f.read()
- decomp_size = len(buf)
+ decompr_size = len(buf)
import zlib
buf = zlib.compress(buf)
+ compr_size = len(buf)
name = str(cs_file_count)
header.write('\n')
header.write('// ' + filepath_src_rel + '\n')
- header.write('static const int _cs_' + name + '_compressed_size = ' + str(len(buf)) + ';\n')
- header.write('static const int _cs_' + name + '_uncompressed_size = ' + str(decomp_size) + ';\n')
+ header.write('static const int _cs_' + name + '_compressed_size = ' + str(compr_size) + ';\n')
+ header.write('static const int _cs_' + name + '_uncompressed_size = ' + str(decompr_size) + ';\n')
header.write('static const unsigned char _cs_' + name + '_compressed[] = { ')
- for i, buf_idx in enumerate(range(len(buf))):
+ for i, buf_idx in enumerate(range(compr_size)):
if i > 0:
header.write(', ')
header.write(byte_to_str(buf[buf_idx]))
+ header.write(' };\n')
inserted_files += '\tr_files.insert("' + filepath_src_rel.replace('\\', '\\\\') + '", ' \
- 'CompressedFile(_cs_' + name + '_compressed_size, ' \
+ 'GodotCsCompressedFile(_cs_' + name + '_compressed_size, ' \
'_cs_' + name + '_uncompressed_size, ' \
'_cs_' + name + '_compressed));\n'
- header.write(' };\n')
- header.write('\nstruct CompressedFile\n' '{\n'
+ header.write('\nstruct GodotCsCompressedFile\n' '{\n'
'\tint compressed_size;\n' '\tint uncompressed_size;\n' '\tconst unsigned char* data;\n'
- '\n\tCompressedFile(int p_comp_size, int p_uncomp_size, const unsigned char* p_data)\n'
+ '\n\tGodotCsCompressedFile(int p_comp_size, int p_uncomp_size, const unsigned char* p_data)\n'
'\t{\n' '\t\tcompressed_size = p_comp_size;\n' '\t\tuncompressed_size = p_uncomp_size;\n'
- '\t\tdata = p_data;\n' '\t}\n' '\n\tCompressedFile() {}\n' '};\n'
- '\nvoid get_compressed_files(Map<String, CompressedFile>& r_files)\n' '{\n' + inserted_files + '}\n'
+ '\t\tdata = p_data;\n' '\t}\n' '\n\tGodotCsCompressedFile() {}\n' '};\n'
+ '\nvoid get_compressed_files(Map<String, GodotCsCompressedFile>& r_files)\n' '{\n' + inserted_files + '}\n'
)
header.write('\n#endif // TOOLS_ENABLED\n')
header.write('\n#endif // CS_COMPRESSED_H\n')
diff --git a/modules/mono/build_scripts/mono_configure.py b/modules/mono/build_scripts/mono_configure.py
index 4cfa2a5b93..9f0eb58896 100644
--- a/modules/mono/build_scripts/mono_configure.py
+++ b/modules/mono/build_scripts/mono_configure.py
@@ -1,15 +1,28 @@
-import imp
import os
+import os.path
import sys
import subprocess
-from distutils.version import LooseVersion
-from SCons.Script import BoolVariable, Dir, Environment, Variables
+from SCons.Script import Dir, Environment
if os.name == 'nt':
from . import mono_reg_utils as monoreg
+android_arch_dirs = {
+ 'armv7': 'armeabi-v7a',
+ 'arm64v8': 'arm64-v8a',
+ 'x86': 'x86',
+ 'x86_64': 'x86_64'
+}
+
+
+def get_android_out_dir(env):
+ return os.path.join(Dir('#platform/android/java/libs').abspath,
+ 'release' if env['target'] == 'release' else 'debug',
+ android_arch_dirs[env['android_arch']])
+
+
def find_file_in_dir(directory, files, prefix='', extension=''):
if not extension.startswith('.'):
extension = '.' + extension
@@ -20,53 +33,60 @@ def find_file_in_dir(directory, files, prefix='', extension=''):
def copy_file(src_dir, dst_dir, name):
- from shutil import copyfile
+ from shutil import copy
- src_path = os.path.join(src_dir, name)
- dst_path = os.path.join(dst_dir, name)
+ src_path = os.path.join(Dir(src_dir).abspath, name)
+ dst_dir = Dir(dst_dir).abspath
if not os.path.isdir(dst_dir):
- os.mkdir(dst_dir)
+ os.makedirs(dst_dir)
- copyfile(src_path, dst_path)
+ copy(src_path, dst_dir)
def configure(env, env_mono):
- envvars = Variables()
- envvars.Add(BoolVariable('mono_static', 'Statically link mono', False))
- envvars.Add(BoolVariable('copy_mono_root', 'Make a copy of the mono installation directory to bundle with the editor', False))
- envvars.Update(env)
-
bits = env['bits']
+ is_android = env['platform'] == 'android'
tools_enabled = env['tools']
mono_static = env['mono_static']
copy_mono_root = env['copy_mono_root']
+ mono_prefix = env['mono_prefix']
+
mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0']
+ is_travis = os.environ.get('TRAVIS') == 'true'
+
+ if is_travis:
+ # Travis CI may have a Mono version lower than 5.12
+ env_mono.Append(CPPDEFINES=['NO_PENDING_EXCEPTIONS'])
+
+ if is_android and not env['android_arch'] in android_arch_dirs:
+ raise RuntimeError('This module does not support for the specified \'android_arch\': ' + env['android_arch'])
+
+ if is_android and tools_enabled:
+ # TODO: Implement this. We have to add the data directory to the apk, concretely the Api and Tools folders.
+ raise RuntimeError('This module does not currently support building for android with tools enabled')
+
+ if is_android and mono_static:
+ # When static linking and doing something that requires libmono-native, we get a dlopen error as libmono-native seems to depend on libmonosgen-2.0
+ raise RuntimeError('Linking Mono statically is not currently supported on Android')
+
+ if (os.getenv('MONO32_PREFIX') or os.getenv('MONO64_PREFIX')) and not mono_prefix:
+ print("WARNING: The environment variables 'MONO32_PREFIX' and 'MONO64_PREFIX' are deprecated; use the 'mono_prefix' SCons parameter instead")
+
if env['platform'] == 'windows':
- mono_root = ''
+ mono_root = mono_prefix
- if bits == '32':
- if os.getenv('MONO32_PREFIX'):
- mono_root = os.getenv('MONO32_PREFIX')
- elif os.name == 'nt':
- mono_root = monoreg.find_mono_root_dir(bits)
- else:
- if os.getenv('MONO64_PREFIX'):
- mono_root = os.getenv('MONO64_PREFIX')
- elif os.name == 'nt':
- mono_root = monoreg.find_mono_root_dir(bits)
+ if not mono_root and os.name == 'nt':
+ mono_root = monoreg.find_mono_root_dir(bits)
if not mono_root:
- raise RuntimeError('Mono installation directory not found')
+ raise RuntimeError("Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter")
print('Found Mono root directory: ' + mono_root)
- mono_version = mono_root_try_find_mono_version(mono_root)
- configure_for_mono_version(env_mono, mono_version)
-
mono_lib_path = os.path.join(mono_root, 'lib')
env.Append(LIBPATH=mono_lib_path)
@@ -113,21 +133,18 @@ def configure(env, env_mono):
if not mono_dll_name:
raise RuntimeError('Could not find mono shared library in: ' + mono_bin_path)
- copy_file(mono_bin_path, 'bin', mono_dll_name + '.dll')
+ copy_file(mono_bin_path, '#bin', mono_dll_name + '.dll')
else:
is_apple = (sys.platform == 'darwin' or "osxcross" in env)
sharedlib_ext = '.dylib' if is_apple else '.so'
- mono_root = ''
+ mono_root = mono_prefix
mono_lib_path = ''
+ mono_so_name = ''
- if bits == '32':
- if os.getenv('MONO32_PREFIX'):
- mono_root = os.getenv('MONO32_PREFIX')
- else:
- if os.getenv('MONO64_PREFIX'):
- mono_root = os.getenv('MONO64_PREFIX')
+ if not mono_root and is_android:
+ raise RuntimeError("Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter")
if not mono_root and is_apple:
# Try with some known directories under OSX
@@ -142,14 +159,12 @@ def configure(env, env_mono):
if not mono_root and mono_static:
mono_root = pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext)
if not mono_root:
- raise RuntimeError('Building with mono_static=yes, but failed to find the mono prefix with pkg-config. Specify one manually')
+ raise RuntimeError("Building with mono_static=yes, but failed to find the mono prefix with pkg-config; " + \
+ "specify one manually with the 'mono_prefix' SCons parameter")
if mono_root:
print('Found Mono root directory: ' + mono_root)
- mono_version = mono_root_try_find_mono_version(mono_root)
- configure_for_mono_version(env_mono, mono_version)
-
mono_lib_path = os.path.join(mono_root, 'lib')
env.Append(LIBPATH=mono_lib_path)
@@ -160,7 +175,7 @@ def configure(env, env_mono):
if not mono_lib:
raise RuntimeError('Could not find mono library in: ' + mono_lib_path)
- env_mono.Append(CPPFLAGS=['-D_REENTRANT'])
+ env_mono.Append(CPPDEFINES=['_REENTRANT'])
if mono_static:
mono_lib_file = os.path.join(mono_lib_path, 'lib' + mono_lib + '.a')
@@ -174,6 +189,8 @@ def configure(env, env_mono):
if is_apple:
env.Append(LIBS=['iconv', 'pthread'])
+ elif is_android:
+ pass # Nothing
else:
env.Append(LIBS=['m', 'rt', 'dl', 'pthread'])
@@ -183,22 +200,16 @@ def configure(env, env_mono):
if not mono_so_name:
raise RuntimeError('Could not find mono shared library in: ' + mono_lib_path)
- copy_file(mono_lib_path, 'bin', 'lib' + mono_so_name + sharedlib_ext)
+ copy_file(mono_lib_path, '#bin', 'lib' + mono_so_name + sharedlib_ext)
else:
assert not mono_static
# TODO: Add option to force using pkg-config
print('Mono root directory not found. Using pkg-config instead')
- mono_version = pkgconfig_try_find_mono_version()
- configure_for_mono_version(env_mono, mono_version)
-
env.ParseConfig('pkg-config monosgen-2 --libs')
env_mono.ParseConfig('pkg-config monosgen-2 --cflags')
- mono_lib_path = ''
- mono_so_name = ''
-
tmpenv = Environment()
tmpenv.AppendENVPath('PKG_CONFIG_PATH', os.getenv('PKG_CONFIG_PATH'))
tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L')
@@ -213,15 +224,25 @@ def configure(env, env_mono):
if not mono_so_name:
raise RuntimeError('Could not find mono shared library in: ' + str(tmpenv['LIBPATH']))
- copy_file(mono_lib_path, 'bin', 'lib' + mono_so_name + sharedlib_ext)
+ if not mono_static:
+ libs_output_dir = get_android_out_dir(env) if is_android else '#bin'
+ copy_file(mono_lib_path, libs_output_dir, 'lib' + mono_so_name + sharedlib_ext)
env.Append(LINKFLAGS='-rdynamic')
- if not tools_enabled:
+ if not tools_enabled and not is_android:
if not mono_root:
mono_root = subprocess.check_output(['pkg-config', 'mono-2', '--variable=prefix']).decode('utf8').strip()
make_template_dir(env, mono_root)
+ elif not tools_enabled and is_android:
+ # Compress Android Mono Config
+ from . import make_android_mono_config
+ config_file_path = os.path.join(mono_root, 'etc', 'mono', 'config')
+ make_android_mono_config.generate_compressed_config(config_file_path, 'mono_gd/')
+
+ # Copy the required shared libraries
+ copy_mono_shared_libs(env, mono_root, None)
if copy_mono_root:
if not mono_root:
@@ -241,7 +262,7 @@ def make_template_dir(env, mono_root):
template_dir_name = ''
- if platform in ['windows', 'osx', 'x11']:
+ if platform in ['windows', 'osx', 'x11', 'android']:
template_dir_name = 'data.mono.%s.%s.%s' % (platform, env['bits'], target)
else:
assert False
@@ -261,7 +282,7 @@ def make_template_dir(env, mono_root):
# Copy the required shared libraries
- copy_mono_shared_libs(mono_root, template_mono_root_dir, env['platform'])
+ copy_mono_shared_libs(env, mono_root, template_mono_root_dir)
def copy_mono_root_files(env, mono_root):
@@ -285,7 +306,7 @@ def copy_mono_root_files(env, mono_root):
# Copy the required shared libraries
- copy_mono_shared_libs(mono_root, editor_mono_root_dir, env['platform'])
+ copy_mono_shared_libs(env, mono_root, editor_mono_root_dir)
# Copy framework assemblies
@@ -332,42 +353,47 @@ def copy_mono_etc_dir(mono_root, target_mono_config_dir, platform):
copy_tree(os.path.join(mono_etc_dir, '2.0'), os.path.join(target_mono_config_dir, '2.0'))
copy_tree(os.path.join(mono_etc_dir, '4.0'), os.path.join(target_mono_config_dir, '4.0'))
copy_tree(os.path.join(mono_etc_dir, '4.5'), os.path.join(target_mono_config_dir, '4.5'))
- copy_tree(os.path.join(mono_etc_dir, 'mconfig'), os.path.join(target_mono_config_dir, 'mconfig'))
+ if os.path.isdir(os.path.join(mono_etc_dir, 'mconfig')):
+ copy_tree(os.path.join(mono_etc_dir, 'mconfig'), os.path.join(target_mono_config_dir, 'mconfig'))
for file in glob(os.path.join(mono_etc_dir, '*')):
if os.path.isfile(file):
copy(file, target_mono_config_dir)
-def copy_mono_shared_libs(mono_root, target_mono_root_dir, platform):
+def copy_mono_shared_libs(env, mono_root, target_mono_root_dir):
from shutil import copy
+ def copy_if_exists(src, dst):
+ if os.path.isfile(src):
+ copy(src, dst)
+
+ platform = env['platform']
+
if platform == 'windows':
target_mono_bin_dir = os.path.join(target_mono_root_dir, 'bin')
if not os.path.isdir(target_mono_bin_dir):
os.makedirs(target_mono_bin_dir)
- copy(os.path.join(mono_root, 'bin', 'MonoPosixHelper.dll'), os.path.join(target_mono_bin_dir, 'MonoPosixHelper.dll'))
+ copy(os.path.join(mono_root, 'bin', 'MonoPosixHelper.dll'), target_mono_bin_dir)
else:
- target_mono_lib_dir = os.path.join(target_mono_root_dir, 'lib')
+ target_mono_lib_dir = get_android_out_dir(env) if platform == 'android' else os.path.join(target_mono_root_dir, 'lib')
if not os.path.isdir(target_mono_lib_dir):
os.makedirs(target_mono_lib_dir)
if platform == 'osx':
- copy(os.path.join(mono_root, 'lib', 'libMonoPosixHelper.dylib'), os.path.join(target_mono_lib_dir, 'libMonoPosixHelper.dylib'))
- elif platform == 'x11':
- copy(os.path.join(mono_root, 'lib', 'libmono-btls-shared.so'), os.path.join(target_mono_lib_dir, 'libmono-btls-shared.so'))
- copy(os.path.join(mono_root, 'lib', 'libMonoPosixHelper.so'), os.path.join(target_mono_lib_dir, 'libMonoPosixHelper.so'))
-
+ # TODO: Make sure nothing is missing
+ copy(os.path.join(mono_root, 'lib', 'libMonoPosixHelper.dylib'), target_mono_lib_dir)
+ elif platform == 'x11' or platform == 'android':
+ lib_file_names = [lib_name + '.so' for lib_name in [
+ 'libmono-btls-shared', 'libmono-ee-interp', 'libmono-native', 'libMonoPosixHelper',
+ 'libmono-profiler-aot', 'libmono-profiler-coverage', 'libmono-profiler-log', 'libMonoSupportW'
+ ]]
-def configure_for_mono_version(env, mono_version):
- if mono_version is None:
- raise RuntimeError('Mono JIT compiler version not found')
- print('Found Mono JIT compiler version: ' + str(mono_version))
- if mono_version >= LooseVersion('5.12.0'):
- env.Append(CPPFLAGS=['-DHAS_PENDING_EXCEPTIONS'])
+ for lib_file_name in lib_file_names:
+ copy_if_exists(os.path.join(mono_root, 'lib', lib_file_name), target_mono_lib_dir)
def pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext):
@@ -379,36 +405,3 @@ def pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext):
if name_found and os.path.isdir(os.path.join(hint_dir, '..', 'include', 'mono-2.0')):
return os.path.join(hint_dir, '..')
return ''
-
-
-def pkgconfig_try_find_mono_version():
- from compat import decode_utf8
-
- lines = subprocess.check_output(['pkg-config', 'monosgen-2', '--modversion']).splitlines()
- greater_version = None
- for line in lines:
- try:
- version = LooseVersion(decode_utf8(line))
- if greater_version is None or version > greater_version:
- greater_version = version
- except ValueError:
- pass
- return greater_version
-
-
-def mono_root_try_find_mono_version(mono_root):
- from compat import decode_utf8
-
- mono_bin = os.path.join(mono_root, 'bin')
- if os.path.isfile(os.path.join(mono_bin, 'mono')):
- mono_binary = os.path.join(mono_bin, 'mono')
- elif os.path.isfile(os.path.join(mono_bin, 'mono.exe')):
- mono_binary = os.path.join(mono_bin, 'mono.exe')
- else:
- return None
- output = subprocess.check_output([mono_binary, '--version'])
- first_line = decode_utf8(output.splitlines()[0])
- try:
- return LooseVersion(first_line.split()[len('Mono JIT compiler version'.split())])
- except (ValueError, IndexError):
- return None
diff --git a/modules/mono/build_scripts/mono_reg_utils.py b/modules/mono/build_scripts/mono_reg_utils.py
index 583708bf07..b2c48f0a61 100644
--- a/modules/mono/build_scripts/mono_reg_utils.py
+++ b/modules/mono/build_scripts/mono_reg_utils.py
@@ -116,5 +116,3 @@ def find_msbuild_tools_path_reg():
return value
except (WindowsError, OSError):
return ''
-
- return ''
diff --git a/modules/mono/build_scripts/patches/fix-mono-android-tkill.diff b/modules/mono/build_scripts/patches/fix-mono-android-tkill.diff
new file mode 100644
index 0000000000..05f8dcadcc
--- /dev/null
+++ b/modules/mono/build_scripts/patches/fix-mono-android-tkill.diff
@@ -0,0 +1,70 @@
+diff --git a/libgc/include/private/gcconfig.h b/libgc/include/private/gcconfig.h
+index e2bdf13ac3e..f962200ba4e 100644
+--- a/libgc/include/private/gcconfig.h
++++ b/libgc/include/private/gcconfig.h
+@@ -2255,6 +2255,14 @@
+ # define GETPAGESIZE() getpagesize()
+ # endif
+
++#if defined(HOST_ANDROID) && !(__ANDROID_API__ >= 23) \
++ && ((defined(MIPS) && (CPP_WORDSZ == 32)) \
++ || defined(ARM32) || defined(I386) /* but not x32 */)
++ /* tkill() exists only on arm32/mips(32)/x86. */
++ /* NDK r11+ deprecates tkill() but keeps it for Mono clients. */
++# define USE_TKILL_ON_ANDROID
++#endif
++
+ # if defined(SUNOS5) || defined(DRSNX) || defined(UTS4)
+ /* OS has SVR4 generic features. Probably others also qualify. */
+ # define SVR4
+diff --git a/libgc/pthread_stop_world.c b/libgc/pthread_stop_world.c
+index f93ce26b562..4a49a6d578c 100644
+--- a/libgc/pthread_stop_world.c
++++ b/libgc/pthread_stop_world.c
+@@ -336,7 +336,7 @@ void GC_push_all_stacks()
+ pthread_t GC_stopping_thread;
+ int GC_stopping_pid;
+
+-#ifdef HOST_ANDROID
++#ifdef USE_TKILL_ON_ANDROID
+ static
+ int android_thread_kill(pid_t tid, int sig)
+ {
+diff --git a/mono/metadata/threads.c b/mono/metadata/threads.c
+index ad9b8823f8f..3542b32b540 100644
+--- a/mono/metadata/threads.c
++++ b/mono/metadata/threads.c
+@@ -77,8 +77,12 @@ mono_native_thread_join_handle (HANDLE thread_handle, gboolean close_handle);
+ #include <zircon/syscalls.h>
+ #endif
+
+-#if defined(HOST_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
+-#define USE_TKILL_ON_ANDROID 1
++#if defined(HOST_ANDROID) && !(__ANDROID_API__ >= 23) \
++ && ((defined(MIPS) && (CPP_WORDSZ == 32)) \
++ || defined(ARM32) || defined(I386) /* but not x32 */)
++ /* tkill() exists only on arm32/mips(32)/x86. */
++ /* NDK r11+ deprecates tkill() but keeps it for Mono clients. */
++# define USE_TKILL_ON_ANDROID
+ #endif
+
+ #ifdef HOST_ANDROID
+diff --git a/mono/utils/mono-threads-posix.c b/mono/utils/mono-threads-posix.c
+index 3e4bf93de5f..79c9f731fe7 100644
+--- a/mono/utils/mono-threads-posix.c
++++ b/mono/utils/mono-threads-posix.c
+@@ -31,8 +31,12 @@
+
+ #include <errno.h>
+
+-#if defined(HOST_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
+-#define USE_TKILL_ON_ANDROID 1
++#if defined(HOST_ANDROID) && !(__ANDROID_API__ >= 23) \
++ && ((defined(MIPS) && (CPP_WORDSZ == 32)) \
++ || defined(ARM32) || defined(I386) /* but not x32 */)
++ /* tkill() exists only on arm32/mips(32)/x86. */
++ /* NDK r11+ deprecates tkill() but keeps it for Mono clients. */
++# define USE_TKILL_ON_ANDROID
+ #endif
+
+ #ifdef USE_TKILL_ON_ANDROID
diff --git a/modules/mono/build_scripts/godotsharptools_build.py b/modules/mono/build_scripts/solution_builder.py
index af3a5cb5c6..d1529a64d2 100644
--- a/modules/mono/build_scripts/godotsharptools_build.py
+++ b/modules/mono/build_scripts/solution_builder.py
@@ -1,9 +1,8 @@
-# Build GodotSharpTools solution
-
import os
-from SCons.Script import Builder, Dir
+
+verbose = False
def find_nuget_unix():
@@ -53,21 +52,9 @@ def find_nuget_windows(env):
if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK):
return hint_path
- from . import mono_reg_utils as monoreg
+ from . mono_reg_utils import find_mono_root_dir
- mono_root = ''
- bits = env['bits']
-
- if bits == '32':
- if os.getenv('MONO32_PREFIX'):
- mono_root = os.getenv('MONO32_PREFIX')
- else:
- mono_root = monoreg.find_mono_root_dir(bits)
- else:
- if os.getenv('MONO64_PREFIX'):
- mono_root = os.getenv('MONO64_PREFIX')
- else:
- mono_root = monoreg.find_mono_root_dir(bits)
+ mono_root = env['mono_prefix'] or find_mono_root_dir(env['bits'])
if mono_root:
mono_bin_dir = os.path.join(mono_root, 'bin')
@@ -114,29 +101,21 @@ def find_msbuild_unix(filename):
def find_msbuild_windows(env):
- from . import mono_reg_utils as monoreg
-
- mono_root = ''
- bits = env['bits']
+ from . mono_reg_utils import find_mono_root_dir, find_msbuild_tools_path_reg
- if bits == '32':
- if os.getenv('MONO32_PREFIX'):
- mono_root = os.getenv('MONO32_PREFIX')
- else:
- mono_root = monoreg.find_mono_root_dir(bits)
- else:
- if os.getenv('MONO64_PREFIX'):
- mono_root = os.getenv('MONO64_PREFIX')
- else:
- mono_root = monoreg.find_mono_root_dir(bits)
+ mono_root = env['mono_prefix'] or find_mono_root_dir(env['bits'])
if not mono_root:
raise RuntimeError('Cannot find mono root directory')
- framework_path = os.path.join(mono_root, 'lib', 'mono', '4.5')
mono_bin_dir = os.path.join(mono_root, 'bin')
msbuild_mono = os.path.join(mono_bin_dir, 'msbuild.bat')
+ msbuild_tools_path = find_msbuild_tools_path_reg()
+
+ if msbuild_tools_path:
+ return (os.path.join(msbuild_tools_path, 'MSBuild.exe'), {})
+
if os.path.isfile(msbuild_mono):
# The (Csc/Vbc/Fsc)ToolExe environment variables are required when
# building with Mono's MSBuild. They must point to the batch files
@@ -146,24 +125,52 @@ def find_msbuild_windows(env):
'VbcToolExe': os.path.join(mono_bin_dir, 'vbc.bat'),
'FscToolExe': os.path.join(mono_bin_dir, 'fsharpc.bat')
}
- return (msbuild_mono, framework_path, mono_msbuild_env)
+ return (msbuild_mono, mono_msbuild_env)
- msbuild_tools_path = monoreg.find_msbuild_tools_path_reg()
+ return None
- if msbuild_tools_path:
- return (os.path.join(msbuild_tools_path, 'MSBuild.exe'), framework_path, {})
- return None
+def run_command(command, args, env_override=None, name=None):
+ def cmd_args_to_str(cmd_args):
+ return ' '.join([arg if not ' ' in arg else '"%s"' % arg for arg in cmd_args])
+
+ args = [command] + args
+
+ if name is None:
+ name = os.path.basename(command)
+ if verbose:
+ print("Running '%s': %s" % (name, cmd_args_to_str(args)))
-def mono_build_solution(source, target, env):
import subprocess
- from shutil import copyfile
+ try:
+ if env_override is None:
+ subprocess.check_call(args)
+ else:
+ subprocess.check_call(args, env=env_override)
+ except subprocess.CalledProcessError as e:
+ raise RuntimeError("'%s' exited with error code: %s" % (name, e.returncode))
+
+
+def nuget_restore(env, *args):
+ global verbose
+ verbose = env['verbose']
+
+ # Find NuGet
+ nuget_path = find_nuget_windows(env) if os.name == 'nt' else find_nuget_unix()
+ if nuget_path is None:
+ raise RuntimeError('Cannot find NuGet executable')
+
+ print('NuGet path: ' + nuget_path)
+
+ # Do NuGet restore
+ run_command(nuget_path, ['restore'] + list(args), name='nuget restore')
- sln_path = os.path.abspath(str(source[0]))
- target_path = os.path.abspath(str(target[0]))
- framework_path = ''
+def build_solution(env, solution_path, build_config, extra_msbuild_args=[]):
+ global verbose
+ verbose = env['verbose']
+
msbuild_env = os.environ.copy()
# Needed when running from Developer Command Prompt for VS
@@ -176,8 +183,7 @@ def mono_build_solution(source, target, env):
if msbuild_info is None:
raise RuntimeError('Cannot find MSBuild executable')
msbuild_path = msbuild_info[0]
- framework_path = msbuild_info[1]
- msbuild_env.update(msbuild_info[2])
+ msbuild_env.update(msbuild_info[1])
else:
msbuild_path = find_msbuild_unix('msbuild')
if msbuild_path is None:
@@ -200,64 +206,9 @@ def mono_build_solution(source, target, env):
print('MSBuild path: ' + msbuild_path)
- # Find NuGet
- nuget_path = find_nuget_windows(env) if os.name == 'nt' else find_nuget_unix()
- if nuget_path is None:
- raise RuntimeError('Cannot find NuGet executable')
-
- print('NuGet path: ' + nuget_path)
-
- # Do NuGet restore
-
- try:
- subprocess.check_call([nuget_path, 'restore', sln_path])
- except subprocess.CalledProcessError:
- raise RuntimeError('GodotSharpTools: NuGet restore failed')
-
# Build solution
- build_config = 'Release'
-
- msbuild_args = [
- msbuild_path,
- sln_path,
- '/p:Configuration=' + build_config,
- ]
-
- if framework_path:
- msbuild_args += ['/p:FrameworkPathOverride=' + framework_path]
-
- try:
- subprocess.check_call(msbuild_args, env=msbuild_env)
- except subprocess.CalledProcessError:
- raise RuntimeError('GodotSharpTools: Build failed')
-
- # Copy files
-
- src_dir = os.path.abspath(os.path.join(sln_path, os.pardir, 'bin', build_config))
- dst_dir = os.path.abspath(os.path.join(target_path, os.pardir))
- asm_file = 'GodotSharpTools.dll'
-
- if not os.path.isdir(dst_dir):
- if os.path.exists(dst_dir):
- raise RuntimeError('Target directory is a file')
- os.makedirs(dst_dir)
-
- copyfile(os.path.join(src_dir, asm_file), os.path.join(dst_dir, asm_file))
-
- # Dependencies
- copyfile(os.path.join(src_dir, "DotNet.Glob.dll"), os.path.join(dst_dir, "DotNet.Glob.dll"))
-
-def build(env_mono):
- if not env_mono['tools']:
- return
-
- output_dir = Dir('#bin').abspath
- editor_tools_dir = os.path.join(output_dir, 'GodotSharp', 'Tools')
+ msbuild_args = [solution_path, '/p:Configuration=' + build_config]
+ msbuild_args += extra_msbuild_args
- mono_sln_builder = Builder(action=mono_build_solution)
- env_mono.Append(BUILDERS={'MonoBuildSolution': mono_sln_builder})
- env_mono.MonoBuildSolution(
- os.path.join(editor_tools_dir, 'GodotSharpTools.dll'),
- 'editor/GodotSharpTools/GodotSharpTools.sln'
- )
+ run_command(msbuild_path, msbuild_args, env_override=msbuild_env, name='msbuild')
diff --git a/modules/mono/class_db_api_json.cpp b/modules/mono/class_db_api_json.cpp
new file mode 100644
index 0000000000..71ccdb7aab
--- /dev/null
+++ b/modules/mono/class_db_api_json.cpp
@@ -0,0 +1,242 @@
+/*************************************************************************/
+/* class_db_api_json.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "class_db_api_json.h"
+
+#include "core/io/json.h"
+#include "core/os/file_access.h"
+#include "core/project_settings.h"
+#include "core/version.h"
+
+void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) {
+ Dictionary classes_dict;
+
+ List<StringName> names;
+
+ const StringName *k = NULL;
+
+ while ((k = ClassDB::classes.next(k))) {
+
+ names.push_back(*k);
+ }
+ //must be alphabetically sorted for hash to compute
+ names.sort_custom<StringName::AlphCompare>();
+
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+
+ ClassDB::ClassInfo *t = ClassDB::classes.getptr(E->get());
+ ERR_FAIL_COND(!t);
+ if (t->api != p_api || !t->exposed)
+ continue;
+
+ Dictionary class_dict;
+ classes_dict[t->name] = class_dict;
+
+ class_dict["inherits"] = t->inherits;
+
+ { //methods
+
+ List<StringName> snames;
+
+ k = NULL;
+
+ while ((k = t->method_map.next(k))) {
+
+ snames.push_back(*k);
+ }
+
+ snames.sort_custom<StringName::AlphCompare>();
+
+ Array methods;
+
+ for (List<StringName>::Element *F = snames.front(); F; F = F->next()) {
+ Dictionary method_dict;
+ methods.push_back(method_dict);
+
+ MethodBind *mb = t->method_map[F->get()];
+ method_dict["name"] = mb->get_name();
+ method_dict["argument_count"] = mb->get_argument_count();
+ method_dict["return_type"] = mb->get_argument_type(-1);
+
+ Array arguments;
+ method_dict["arguments"] = arguments;
+
+ for (int i = 0; i < mb->get_argument_count(); i++) {
+ Dictionary argument_dict;
+ arguments.push_back(argument_dict);
+ const PropertyInfo info = mb->get_argument_info(i);
+ argument_dict["type"] = info.type;
+ argument_dict["name"] = info.name;
+ argument_dict["hint"] = info.hint;
+ argument_dict["hint_string"] = info.hint_string;
+ }
+
+ method_dict["default_argument_count"] = mb->get_default_argument_count();
+
+ Array default_arguments;
+ method_dict["default_arguments"] = default_arguments;
+
+ for (int i = 0; i < mb->get_default_argument_count(); i++) {
+ Dictionary default_argument_dict;
+ default_arguments.push_back(default_argument_dict);
+ //hash should not change, i hope for tis
+ Variant da = mb->get_default_argument(i);
+ default_argument_dict["value"] = da;
+ }
+
+ method_dict["hint_flags"] = mb->get_hint_flags();
+ }
+
+ if (!methods.empty()) {
+ class_dict["methods"] = methods;
+ }
+ }
+
+ { //constants
+
+ List<StringName> snames;
+
+ k = NULL;
+
+ while ((k = t->constant_map.next(k))) {
+
+ snames.push_back(*k);
+ }
+
+ snames.sort_custom<StringName::AlphCompare>();
+
+ Array constants;
+
+ for (List<StringName>::Element *F = snames.front(); F; F = F->next()) {
+ Dictionary constant_dict;
+ constants.push_back(constant_dict);
+
+ constant_dict["name"] = F->get();
+ constant_dict["value"] = t->constant_map[F->get()];
+ }
+
+ if (!constants.empty()) {
+ class_dict["constants"] = constants;
+ }
+ }
+
+ { //signals
+
+ List<StringName> snames;
+
+ k = NULL;
+
+ while ((k = t->signal_map.next(k))) {
+
+ snames.push_back(*k);
+ }
+
+ snames.sort_custom<StringName::AlphCompare>();
+
+ Array signals;
+
+ for (List<StringName>::Element *F = snames.front(); F; F = F->next()) {
+ Dictionary signal_dict;
+ signals.push_back(signal_dict);
+
+ MethodInfo &mi = t->signal_map[F->get()];
+ signal_dict["name"] = F->get();
+
+ Array arguments;
+ signal_dict["arguments"] = arguments;
+ for (int i = 0; i < mi.arguments.size(); i++) {
+ Dictionary argument_dict;
+ arguments.push_back(argument_dict);
+ argument_dict["type"] = mi.arguments[i].type;
+ }
+ }
+
+ if (!signals.empty()) {
+ class_dict["signals"] = signals;
+ }
+ }
+
+ { //properties
+
+ List<StringName> snames;
+
+ k = NULL;
+
+ while ((k = t->property_setget.next(k))) {
+
+ snames.push_back(*k);
+ }
+
+ snames.sort_custom<StringName::AlphCompare>();
+
+ Array properties;
+
+ for (List<StringName>::Element *F = snames.front(); F; F = F->next()) {
+ Dictionary property_dict;
+ properties.push_back(property_dict);
+
+ ClassDB::PropertySetGet *psg = t->property_setget.getptr(F->get());
+
+ property_dict["name"] = F->get();
+ property_dict["setter"] = psg->setter;
+ property_dict["getter"] = psg->getter;
+ }
+
+ if (!properties.empty()) {
+ class_dict["property_setget"] = properties;
+ }
+ }
+
+ Array property_list;
+
+ //property list
+ for (List<PropertyInfo>::Element *F = t->property_list.front(); F; F = F->next()) {
+ Dictionary property_dict;
+ property_list.push_back(property_dict);
+
+ property_dict["name"] = F->get().name;
+ property_dict["type"] = F->get().type;
+ property_dict["hint"] = F->get().hint;
+ property_dict["hint_string"] = F->get().hint_string;
+ property_dict["usage"] = F->get().usage;
+ }
+
+ if (!property_list.empty()) {
+ class_dict["property_list"] = property_list;
+ }
+ }
+
+ FileAccessRef f = FileAccess::open(p_output_file, FileAccess::WRITE);
+ ERR_FAIL_COND(!f);
+ f->store_string(JSON::print(classes_dict, /*indent: */ "\t"));
+ f->close();
+
+ print_line(String() + "ClassDB API JSON written to: " + ProjectSettings::get_singleton()->globalize_path(p_output_file));
+}
diff --git a/modules/mono/class_db_api_json.h b/modules/mono/class_db_api_json.h
new file mode 100644
index 0000000000..0aa9c20930
--- /dev/null
+++ b/modules/mono/class_db_api_json.h
@@ -0,0 +1,39 @@
+/*************************************************************************/
+/* class_db_api_json.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef CLASS_DB_API_JSON_H
+#define CLASS_DB_API_JSON_H
+
+#include "core/class_db.h"
+#include "core/ustring.h"
+
+void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api);
+
+#endif // CLASS_DB_API_JSON_H
diff --git a/modules/mono/config.py b/modules/mono/config.py
index 3b2e96765e..9adf4ee6e5 100644
--- a/modules/mono/config.py
+++ b/modules/mono/config.py
@@ -8,6 +8,16 @@ def configure(env):
env.use_ptrcall = True
env.add_module_version_string('mono')
+ from SCons.Script import BoolVariable, PathVariable, Variables
+
+ envvars = Variables()
+ envvars.Add(PathVariable('mono_prefix', 'Path to the mono installation directory for the target platform and architecture', '', PathVariable.PathAccept))
+ envvars.Add(BoolVariable('mono_static', 'Statically link mono', False))
+ envvars.Add(BoolVariable('mono_glue', 'Build with the mono glue sources', True))
+ envvars.Add(BoolVariable('copy_mono_root', 'Make a copy of the mono installation directory to bundle with the editor', False))
+ envvars.Add(BoolVariable('xbuild_fallback', 'If MSBuild is not found, fallback to xbuild', False))
+ envvars.Update(env)
+
def get_doc_classes():
return [
diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp
index 72199281ff..078a490b22 100644
--- a/modules/mono/csharp_script.cpp
+++ b/modules/mono/csharp_script.cpp
@@ -42,9 +42,13 @@
#include "editor/bindings_generator.h"
#include "editor/csharp_project.h"
#include "editor/editor_node.h"
-#include "editor/godotsharp_editor.h"
#endif
+#ifdef DEBUG_METHODS_ENABLED
+#include "class_db_api_json.h"
+#endif
+
+#include "editor/editor_internal_calls.h"
#include "godotsharp_dirs.h"
#include "mono_gd/gd_mono_class.h"
#include "mono_gd/gd_mono_marshal.h"
@@ -65,8 +69,8 @@ static bool _create_project_solution_if_needed() {
if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) {
// A solution does not yet exist, create a new one
- CRASH_COND(GodotSharpEditor::get_singleton() == NULL);
- return GodotSharpEditor::get_singleton()->call("_create_project_solution");
+ CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == NULL);
+ return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolution");
}
return true;
@@ -96,32 +100,36 @@ Error CSharpLanguage::execute_file(const String &p_path) {
return OK;
}
-#ifdef TOOLS_ENABLED
-void gdsharp_editor_init_callback() {
+void CSharpLanguage::init() {
- EditorNode *editor = EditorNode::get_singleton();
- editor->add_child(memnew(GodotSharpEditor(editor)));
-}
+#ifdef DEBUG_METHODS_ENABLED
+ if (OS::get_singleton()->get_cmdline_args().find("--class_db_to_json")) {
+ class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE);
+#ifdef TOOLS_ENABLED
+ class_db_api_to_json("user://class_db_api_editor.json", ClassDB::API_EDITOR);
+#endif
+ }
#endif
-
-void CSharpLanguage::init() {
gdmono = memnew(GDMono);
gdmono->initialize();
-#ifndef MONO_GLUE_ENABLED
- WARN_PRINT("This binary is built with `mono_glue=no` and cannot be used for scripting");
+#if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
+ // Generate bindings here, before loading assemblies. `initialize_load_assemblies` aborts
+ // the applications if the api assemblies or the main tools assembly is missing, but this
+ // is not a problem for BindingsGenerator as it only needs the tools project editor assembly.
+ List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
+ BindingsGenerator::handle_cmdline_args(cmdline_args);
#endif
-#if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
- if (gdmono->get_editor_tools_assembly() != NULL) {
- List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
- BindingsGenerator::handle_cmdline_args(cmdline_args);
- }
+#ifndef MONO_GLUE_ENABLED
+ print_line("Run this binary with `--generate-mono-glue path/to/modules/mono/glue`");
#endif
+ gdmono->initialize_load_assemblies();
+
#ifdef TOOLS_ENABLED
- EditorNode::add_init_callback(&gdsharp_editor_init_callback);
+ EditorNode::add_init_callback(&_editor_init_callback);
GLOBAL_DEF("mono/export/include_scripts_content", false);
#endif
@@ -664,7 +672,7 @@ void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft
CRASH_COND(!Engine::get_singleton()->is_editor_hint());
#ifdef TOOLS_ENABLED
- MonoReloadNode::get_singleton()->restart_reload_timer();
+ get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer");
#endif
#ifdef GD_MONO_HOT_RELOAD
@@ -682,19 +690,20 @@ bool CSharpLanguage::is_assembly_reloading_needed() {
GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
- String name = ProjectSettings::get_singleton()->get("application/config/name");
- if (name.empty()) {
- name = "UnnamedProject";
+ String appname = ProjectSettings::get_singleton()->get("application/config/name");
+ String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
+ if (appname_safe.empty()) {
+ appname_safe = "UnnamedProject";
}
- name += ".dll";
+ appname_safe += ".dll";
if (proj_assembly) {
String proj_asm_path = proj_assembly->get_path();
if (!FileAccess::exists(proj_assembly->get_path())) {
// Maybe it wasn't loaded from the default path, so check this as well
- proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name);
+ proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe);
if (!FileAccess::exists(proj_asm_path))
return false; // No assembly to load
}
@@ -702,18 +711,10 @@ bool CSharpLanguage::is_assembly_reloading_needed() {
if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time())
return false; // Already up to date
} else {
- if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name)))
+ if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe)))
return false; // No assembly to load
}
-#ifdef TOOLS_ENABLED
- if (!gdmono->get_core_api_assembly() && gdmono->metadata_is_api_assembly_invalidated(APIAssembly::API_CORE))
- return false; // The core API assembly to load is invalidated
-
- if (!gdmono->get_editor_api_assembly() && gdmono->metadata_is_api_assembly_invalidated(APIAssembly::API_EDITOR))
- return false; // The editor API assembly to load is invalidated
-#endif
-
return true;
}
@@ -730,58 +731,93 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
SCOPED_MUTEX_LOCK(script_instances_mutex);
for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
- if (elem->self()->get_path().is_resource_file()) {
- // Cast to CSharpScript to avoid being erased by accident
- scripts.push_back(Ref<CSharpScript>(elem->self()));
- }
+ // Cast to CSharpScript to avoid being erased by accident
+ scripts.push_back(Ref<CSharpScript>(elem->self()));
}
}
List<Ref<CSharpScript> > to_reload;
+ // We need to keep reference instances alive during reloading
+ List<Ref<Reference> > ref_instances;
+
+ for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
+ CSharpScriptBinding &script_binding = E->value();
+ Reference *ref = Object::cast_to<Reference>(script_binding.owner);
+ if (ref) {
+ ref_instances.push_back(Ref<Reference>(ref));
+ }
+ }
+
// As scripts are going to be reloaded, must proceed without locking here
scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order
for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
-
Ref<CSharpScript> &script = E->get();
to_reload.push_back(script);
+ if (script->get_path().empty()) {
+ script->tied_class_name_for_reload = script->script_class->get_name();
+ script->tied_class_namespace_for_reload = script->script_class->get_namespace();
+ }
+
// Script::instances are deleted during managed object disposal, which happens on domain finalize.
// Only placeholders are kept. Therefore we need to keep a copy before that happens.
for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) {
- script->pending_reload_instances.insert(F->get()->get_instance_id());
+ Object *obj = F->get();
+ script->pending_reload_instances.insert(obj->get_instance_id());
+
+ Reference *ref = Object::cast_to<Reference>(obj);
+ if (ref) {
+ ref_instances.push_back(Ref<Reference>(ref));
+ }
}
#ifdef TOOLS_ENABLED
for (Set<PlaceHolderScriptInstance *>::Element *F = script->placeholders.front(); F; F = F->next()) {
- script->pending_reload_instances.insert(F->get()->get_owner()->get_instance_id());
+ Object *obj = F->get()->get_owner();
+ script->pending_reload_instances.insert(obj->get_instance_id());
+
+ Reference *ref = Object::cast_to<Reference>(obj);
+ if (ref) {
+ ref_instances.push_back(Ref<Reference>(ref));
+ }
}
#endif
- // FIXME: What about references? Need to keep them alive if only managed code references them.
-
// Save state and remove script from instances
Map<ObjectID, CSharpScript::StateBackup> &owners_map = script->pending_reload_state;
- while (script->instances.front()) {
- Object *obj = script->instances.front()->get();
- // Save instance info
- CSharpScript::StateBackup state;
+ for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) {
+ Object *obj = F->get();
ERR_CONTINUE(!obj->get_script_instance());
- // TODO: Proper state backup (Not only variants, serialize managed state of scripts)
- obj->get_script_instance()->get_property_state(state.properties);
+ CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
+
+ // Call OnBeforeSerialize
+ if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
+ obj->get_script_instance()->call_multilevel(string_names.on_before_serialize);
- Ref<MonoGCHandle> gchandle = CAST_CSHARP_INSTANCE(obj->get_script_instance())->gchandle;
- if (gchandle.is_valid())
- gchandle->release();
+ // Save instance info
+ CSharpScript::StateBackup state;
+
+ // TODO: Proper state backup (Not only variants, serialize managed state of scripts)
+ csi->get_properties_state_for_reloading(state.properties);
owners_map[obj->get_instance_id()] = state;
+ }
+ }
+
+ // After the state of all instances is saved, clear scripts and script instances
+ for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
+ Ref<CSharpScript> &script = E->get();
+
+ while (script->instances.front()) {
+ Object *obj = script->instances.front()->get();
obj->set_script(RefPtr()); // Remove script and existing script instances (placeholder are not removed before domain reload)
}
@@ -824,26 +860,80 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
scr->pending_reload_state.erase(obj_id);
}
}
+
return;
}
+ List<Ref<CSharpScript> > to_reload_state;
+
for (List<Ref<CSharpScript> >::Element *E = to_reload.front(); E; E = E->next()) {
+ Ref<CSharpScript> script = E->get();
+
+ if (!script->get_path().empty()) {
+#ifdef TOOLS_ENABLED
+ script->exports_invalidated = true;
+#endif
+ script->signals_invalidated = true;
+
+ script->reload(p_soft_reload);
+ script->update_exports();
+
+ if (!script->valid) {
+ script->pending_reload_instances.clear();
+ continue;
+ }
+ } else {
+ const StringName &class_namespace = script->tied_class_namespace_for_reload;
+ const StringName &class_name = script->tied_class_name_for_reload;
+ GDMonoAssembly *project_assembly = gdmono->get_project_assembly();
+
+ // Search in project and tools assemblies first as those are the most likely to have the class
+ GDMonoClass *script_class = (project_assembly ? project_assembly->get_class(class_namespace, class_name) : NULL);
- Ref<CSharpScript> scr = E->get();
#ifdef TOOLS_ENABLED
- scr->exports_invalidated = true;
+ if (!script_class) {
+ GDMonoAssembly *tools_assembly = gdmono->get_tools_assembly();
+ script_class = (tools_assembly ? tools_assembly->get_class(class_namespace, class_name) : NULL);
+ }
#endif
- scr->signals_invalidated = true;
- scr->reload(p_soft_reload);
- scr->update_exports();
+
+ if (!script_class) {
+ script_class = gdmono->get_class(class_namespace, class_name);
+ }
+
+ if (!script_class) {
+ // The class was removed, can't reload
+ script->pending_reload_instances.clear();
+ continue;
+ }
+
+ bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(script_class);
+ if (!obj_type) {
+ // The class no longer inherits Godot.Object, can't reload
+ script->pending_reload_instances.clear();
+ continue;
+ }
+
+ GDMonoClass *native = GDMonoUtils::get_class_native_base(script_class);
+
+ CSharpScript::initialize_for_managed_type(script, script_class, native);
+ }
+
+ String native_name = NATIVE_GDMONOCLASS_NAME(script->native);
{
- for (Set<ObjectID>::Element *F = scr->pending_reload_instances.front(); F; F = F->next()) {
+ for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) {
ObjectID obj_id = F->get();
Object *obj = ObjectDB::get_instance(obj_id);
if (!obj) {
- scr->pending_reload_state.erase(obj_id);
+ script->pending_reload_state.erase(obj_id);
+ continue;
+ }
+
+ if (!ClassDB::is_parent_class(obj->get_class_name(), native_name)) {
+ // No longer inherits the same compatible type, can't reload
+ script->pending_reload_state.erase(obj_id);
continue;
}
@@ -855,28 +945,20 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
// Non-placeholder script instances are removed in godot_icall_Object_Disposed.
CRASH_COND(!si->is_placeholder());
- if (scr->is_tool() || ScriptServer::is_scripting_enabled()) {
+ if (script->is_tool() || ScriptServer::is_scripting_enabled()) {
// Replace placeholder with a script instance
- CSharpScript::StateBackup &state_backup = scr->pending_reload_state[obj_id];
+ CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
// Backup placeholder script instance state before replacing it with a script instance
si->get_property_state(state_backup.properties);
- ScriptInstance *script_instance = scr->instance_create(obj);
+ ScriptInstance *script_instance = script->instance_create(obj);
if (script_instance) {
- scr->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
+ script->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
obj->set_script_instance(script_instance);
}
-
- // TODO: Restore serialized state
-
- for (List<Pair<StringName, Variant> >::Element *G = state_backup.properties.front(); G; G = G->next()) {
- script_instance->set(G->get().first, G->get().second);
- }
-
- scr->pending_reload_state.erase(obj_id);
}
continue;
@@ -885,20 +967,42 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
CRASH_COND(si != NULL);
#endif
// Re-create script instance
+ obj->set_script(script.get_ref_ptr()); // will create the script instance as well
+ }
+ }
- obj->set_script(scr.get_ref_ptr()); // will create the script instance as well
+ to_reload_state.push_back(script);
+ }
- // TODO: Restore serialized state
+ for (List<Ref<CSharpScript> >::Element *E = to_reload_state.front(); E; E = E->next()) {
+ Ref<CSharpScript> script = E->get();
- for (List<Pair<StringName, Variant> >::Element *G = scr->pending_reload_state[obj_id].properties.front(); G; G = G->next()) {
- obj->get_script_instance()->set(G->get().first, G->get().second);
- }
+ for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) {
+ ObjectID obj_id = F->get();
+ Object *obj = ObjectDB::get_instance(obj_id);
- scr->pending_reload_state.erase(obj_id);
+ if (!obj) {
+ script->pending_reload_state.erase(obj_id);
+ continue;
+ }
+
+ ERR_CONTINUE(!obj->get_script_instance());
+
+ // TODO: Restore serialized state
+
+ CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
+
+ for (List<Pair<StringName, Variant> >::Element *G = state_backup.properties.front(); G; G = G->next()) {
+ obj->get_script_instance()->set(G->get().first, G->get().second);
}
- scr->pending_reload_instances.clear();
+ // Call OnAfterDeserialization
+ CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance());
+ if (csi && csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
+ obj->get_script_instance()->call_multilevel(string_names.on_after_deserialize);
}
+
+ script->pending_reload_instances.clear();
}
#ifdef TOOLS_ENABLED
@@ -963,12 +1067,12 @@ void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const
#ifdef TOOLS_ENABLED
Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
- return GodotSharpEditor::get_singleton()->open_in_external_editor(p_script, p_line, p_col);
+ return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col);
}
bool CSharpLanguage::overrides_external_editor() {
- return GodotSharpEditor::get_singleton()->overrides_external_editor();
+ return get_godotsharp_editor()->call("OverridesExternalEditor");
}
#endif
@@ -1026,6 +1130,34 @@ void CSharpLanguage::_on_scripts_domain_unloaded() {
scripts_metadata_invalidated = true;
}
+#ifdef TOOLS_ENABLED
+void CSharpLanguage::_editor_init_callback() {
+
+ register_editor_internal_calls();
+
+ // Initialize GodotSharpEditor
+
+ GDMonoClass *editor_klass = GDMono::get_singleton()->get_tools_assembly()->get_class("GodotTools", "GodotSharpEditor");
+ CRASH_COND(editor_klass == NULL);
+
+ MonoObject *mono_object = mono_object_new(mono_domain_get(), editor_klass->get_mono_ptr());
+ CRASH_COND(mono_object == NULL);
+
+ MonoException *exc = NULL;
+ GDMonoUtils::runtime_object_init(mono_object, editor_klass, &exc);
+ UNHANDLED_EXCEPTION(exc);
+
+ EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(GDMonoMarshal::mono_object_to_variant(mono_object));
+ CRASH_COND(godotsharp_editor == NULL);
+
+ // Enable it as a plugin
+ EditorNode::add_editor_plugin(godotsharp_editor);
+ godotsharp_editor->enable_plugin();
+
+ get_singleton()->godotsharp_editor = godotsharp_editor;
+}
+#endif
+
void CSharpLanguage::set_language_index(int p_idx) {
ERR_FAIL_COND(lang_idx != -1);
@@ -1083,6 +1215,10 @@ CSharpLanguage::CSharpLanguage() {
lang_idx = -1;
scripts_metadata_invalidated = true;
+
+#ifdef TOOLS_ENABLED
+ godotsharp_editor = NULL;
+#endif
}
CSharpLanguage::~CSharpLanguage() {
@@ -1138,6 +1274,7 @@ bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_b
r_script_binding.type_name = type_name;
r_script_binding.wrapper_class = type_class; // cache
r_script_binding.gchandle = MonoGCHandle::create_strong(mono_object);
+ r_script_binding.owner = p_object;
// Tie managed to unmanaged
Reference *ref = Object::cast_to<Reference>(p_object);
@@ -1222,6 +1359,9 @@ void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
+ if (!script_binding.inited)
+ return;
+
if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
// The reference count was increased after the managed side was the only one referencing our owner.
// This means the owner is being referenced again by the unmanaged side,
@@ -1246,14 +1386,17 @@ bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
CRASH_COND(!ref_owner);
#endif
- int refcount = ref_owner->reference_get_count();
-
void *data = p_object->get_script_instance_binding(get_language_index());
CRASH_COND(!data);
CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
+ int refcount = ref_owner->reference_get_count();
+
+ if (!script_binding.inited)
+ return refcount == 0;
+
if (refcount == 1 && gchandle.is_valid() && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
// If owner owner is no longer referenced by the unmanaged side,
// the managed instance takes responsibility of deleting the owner when GCed.
@@ -1416,6 +1559,31 @@ bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
return false;
}
+void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Variant> > &r_state) {
+
+ List<PropertyInfo> pinfo;
+ get_property_list(&pinfo);
+
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ Pair<StringName, Variant> state_pair;
+ state_pair.first = E->get().name;
+
+ ManagedType managedType;
+
+ GDMonoField *field = script->script_class->get_field(state_pair.first);
+ if (!field)
+ continue; // Properties ignored. We get the property baking fields instead.
+
+ managedType = field->get_type();
+
+ if (GDMonoMarshal::managed_to_variant_type(managedType) != Variant::NIL) { // If we can marshal it
+ if (get(state_pair.first, state_pair.second)) {
+ r_state.push_back(state_pair);
+ }
+ }
+ }
+}
+
void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
@@ -1613,17 +1781,18 @@ MonoObject *CSharpInstance::_internal_new_managed() {
ERR_FAIL_NULL_V(owner, NULL);
ERR_FAIL_COND_V(script.is_null(), NULL);
- MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, script->script_class->get_mono_ptr());
+ MonoObject *mono_object = mono_object_new(mono_domain_get(), script->script_class->get_mono_ptr());
if (!mono_object) {
// Important to clear this before destroying the script instance here
script = Ref<CSharpScript>();
- owner = NULL;
bool die = _unreference_owner_unsafe();
// Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
CRASH_COND(die == true);
+ owner = NULL;
+
ERR_EXPLAIN("Failed to allocate memory for the object");
ERR_FAIL_V(NULL);
}
@@ -1939,7 +2108,16 @@ CSharpInstance::~CSharpInstance() {
CRASH_COND(data == NULL);
CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
- CRASH_COND(!script_binding.inited);
+
+ if (!script_binding.inited) {
+ SCOPED_MUTEX_LOCK(CSharpLanguage::get_singleton()->get_language_bind_mutex());
+
+ if (!script_binding.inited) { // Other thread may have set it up
+ // Already had a binding that needs to be setup
+ CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, owner);
+ CRASH_COND(!script_binding.inited);
+ }
+ }
bool die = _unreference_owner_unsafe();
CRASH_COND(die == true); // The "instance binding" should be holding a reference
@@ -1981,6 +2159,52 @@ void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List
propnames.push_back(E->get());
}
}
+
+void CSharpScript::_update_member_info_no_exports() {
+
+ if (exports_invalidated) {
+ exports_invalidated = false;
+
+ member_info.clear();
+
+ GDMonoClass *top = script_class;
+
+ while (top && top != native) {
+ PropertyInfo prop_info;
+ bool exported;
+
+ const Vector<GDMonoField *> &fields = top->get_all_fields();
+
+ for (int i = fields.size() - 1; i >= 0; i--) {
+ GDMonoField *field = fields[i];
+
+ if (_get_member_export(field, /* inspect export: */ false, prop_info, exported)) {
+ StringName member_name = field->get_name();
+
+ member_info[member_name] = prop_info;
+ exported_members_cache.push_front(prop_info);
+ exported_members_defval_cache[member_name] = Variant();
+ }
+ }
+
+ const Vector<GDMonoProperty *> &properties = top->get_all_properties();
+
+ for (int i = properties.size() - 1; i >= 0; i--) {
+ GDMonoProperty *property = properties[i];
+
+ if (_get_member_export(property, /* inspect export: */ false, prop_info, exported)) {
+ StringName member_name = property->get_name();
+
+ member_info[member_name] = prop_info;
+ exported_members_cache.push_front(prop_info);
+ exported_members_defval_cache[member_name] = Variant();
+ }
+ }
+
+ top = top->get_parent_class();
+ }
+ }
+}
#endif
bool CSharpScript::_update_exports() {
@@ -2007,7 +2231,7 @@ bool CSharpScript::_update_exports() {
// Here we create a temporary managed instance of the class to get the initial values
- MonoObject *tmp_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr());
+ MonoObject *tmp_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
if (!tmp_object) {
ERR_PRINT("Failed to allocate temporary MonoObject");
@@ -2048,18 +2272,18 @@ bool CSharpScript::_update_exports() {
for (int i = fields.size() - 1; i >= 0; i--) {
GDMonoField *field = fields[i];
- if (_get_member_export(field, prop_info, exported)) {
- StringName name = field->get_name();
+ if (_get_member_export(field, /* inspect export: */ true, prop_info, exported)) {
+ StringName member_name = field->get_name();
if (exported) {
- member_info[name] = prop_info;
+ member_info[member_name] = prop_info;
exported_members_cache.push_front(prop_info);
if (tmp_object) {
- exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
+ exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
}
} else {
- member_info[name] = prop_info;
+ member_info[member_name] = prop_info;
}
}
}
@@ -2069,25 +2293,25 @@ bool CSharpScript::_update_exports() {
for (int i = properties.size() - 1; i >= 0; i--) {
GDMonoProperty *property = properties[i];
- if (_get_member_export(property, prop_info, exported)) {
- StringName name = property->get_name();
+ if (_get_member_export(property, /* inspect export: */ true, prop_info, exported)) {
+ StringName member_name = property->get_name();
if (exported) {
- member_info[name] = prop_info;
+ member_info[member_name] = prop_info;
exported_members_cache.push_front(prop_info);
if (tmp_object) {
MonoException *exc = NULL;
MonoObject *ret = property->get_value(tmp_object, &exc);
if (exc) {
- exported_members_defval_cache[name] = Variant();
+ exported_members_defval_cache[member_name] = Variant();
GDMonoUtils::debug_print_unhandled_exception(exc);
} else {
- exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(ret);
+ exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret);
}
}
} else {
- member_info[name] = prop_info;
+ member_info[member_name] = prop_info;
}
}
}
@@ -2196,7 +2420,7 @@ bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoClass *p_delegate, Ve
* Returns false if there was an error, otherwise true.
* If there was an error, r_prop_info and r_exported are not assigned any value.
*/
-bool CSharpScript::_get_member_export(IMonoClassMember *p_member, PropertyInfo &r_prop_info, bool &r_exported) {
+bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported) {
// Goddammit, C++. All I wanted was some nested functions.
#define MEMBER_FULL_QUALIFIED_NAME(m_member) \
@@ -2221,26 +2445,30 @@ bool CSharpScript::_get_member_export(IMonoClassMember *p_member, PropertyInfo &
CRASH_NOW();
}
- Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type);
-
- if (!p_member->has_attribute(CACHED_CLASS(ExportAttribute))) {
- r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
- r_exported = false;
- return true;
- }
+ bool exported = p_member->has_attribute(CACHED_CLASS(ExportAttribute));
if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
if (!property->has_getter()) {
- ERR_PRINTS("Read-only property cannot be exported: " + MEMBER_FULL_QUALIFIED_NAME(p_member));
+ if (exported)
+ ERR_PRINTS("Read-only property cannot be exported: " + MEMBER_FULL_QUALIFIED_NAME(p_member));
return false;
}
if (!property->has_setter()) {
- ERR_PRINTS("Set-only property (without getter) cannot be exported: " + MEMBER_FULL_QUALIFIED_NAME(p_member));
+ if (exported)
+ ERR_PRINTS("Write-only property (without getter) cannot be exported: " + MEMBER_FULL_QUALIFIED_NAME(p_member));
return false;
}
}
+ Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type);
+
+ if (!p_inspect_export || !exported) {
+ r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
+ r_exported = false;
+ return true;
+ }
+
MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
PropertyHint hint = PROPERTY_HINT_NONE;
@@ -2460,33 +2688,58 @@ void CSharpScript::_bind_methods() {
Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native) {
- // This method should not fail
+ // This method should not fail, only assertions allowed
- CRASH_COND(!p_class);
+ CRASH_COND(p_class == NULL);
- // TODO: Cache the 'CSharpScript' associated with this 'p_class' instead of allocating a new one every time
+ // TODO OPTIMIZE: Cache the 'CSharpScript' associated with this 'p_class' instead of allocating a new one every time
Ref<CSharpScript> script = memnew(CSharpScript);
- script->name = p_class->get_name();
- script->script_class = p_class;
- script->native = p_native;
+ initialize_for_managed_type(script, p_class, p_native);
+
+ return script;
+}
+
+void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMonoClass *p_class, GDMonoClass *p_native) {
+
+ // This method should not fail, only assertions allowed
+
+ CRASH_COND(p_class == NULL);
+
+ p_script->name = p_class->get_name();
+ p_script->script_class = p_class;
+ p_script->native = p_native;
+
+ CRASH_COND(p_script->native == NULL);
- CRASH_COND(script->native == NULL);
+ GDMonoClass *base = p_script->script_class->get_parent_class();
- GDMonoClass *base = script->script_class->get_parent_class();
+ if (base != p_script->native)
+ p_script->base = base;
- if (base != script->native)
- script->base = base;
+ p_script->valid = true;
+ p_script->tool = p_script->script_class->has_attribute(CACHED_CLASS(ToolAttribute));
+
+ if (!p_script->tool) {
+ GDMonoClass *nesting_class = p_script->script_class->get_nesting_class();
+ p_script->tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
+ }
+
+#if TOOLS_ENABLED
+ if (!p_script->tool) {
+ p_script->tool = p_script->script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
+ }
+#endif
#ifdef DEBUG_ENABLED
// For debug builds, we must fetch from all native base methods as well.
// Native base methods must be fetched before the current class.
// Not needed if the script class itself is a native class.
- if (script->script_class != script->native) {
- GDMonoClass *native_top = script->native;
+ if (p_script->script_class != p_script->native) {
+ GDMonoClass *native_top = p_script->native;
while (native_top) {
- native_top->fetch_methods_with_godot_api_checks(script->native);
+ native_top->fetch_methods_with_godot_api_checks(p_script->native);
if (native_top == CACHED_CLASS(GodotObject))
break;
@@ -2496,18 +2749,19 @@ Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GD
}
#endif
- script->script_class->fetch_methods_with_godot_api_checks(script->native);
+ p_script->script_class->fetch_methods_with_godot_api_checks(p_script->native);
// Need to fetch method from base classes as well
- GDMonoClass *top = script->script_class;
- while (top && top != script->native) {
- top->fetch_methods_with_godot_api_checks(script->native);
+ GDMonoClass *top = p_script->script_class;
+ while (top && top != p_script->native) {
+ top->fetch_methods_with_godot_api_checks(p_script->native);
top = top->get_parent_class();
}
- script->load_script_signals(script->script_class, script->native);
-
- return script;
+ p_script->load_script_signals(p_script->script_class, p_script->native);
+#ifdef TOOLS_ENABLED
+ p_script->_update_member_info_no_exports();
+#endif
}
bool CSharpScript::can_instance() const {
@@ -2515,7 +2769,8 @@ bool CSharpScript::can_instance() const {
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
- if (get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted...
+ // Hack to lower the risk of attached scripts not being added to the C# project
+ if (!get_path().empty() && get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted...
if (_create_project_solution_if_needed()) {
CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
"Compile",
@@ -2567,7 +2822,9 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg
GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount);
if (ctor == NULL) {
if (p_argcount == 0) {
- ERR_PRINTS("Cannot create script instance because the class does not define a parameterless constructor: " + get_path());
+ String path = get_path();
+ ERR_PRINTS("Cannot create script instance. The class '" + script_class->get_full_name() +
+ "' does not define a parameterless constructor." + (path.empty() ? String() : ". Path: " + path));
}
ERR_EXPLAIN("Constructor not found");
@@ -2609,7 +2866,7 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg
/* STEP 2, INITIALIZE AND CONSTRUCT */
- MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr());
+ MonoObject *mono_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
if (!mono_object) {
// Important to clear this before destroying the script instance here
@@ -2690,7 +2947,7 @@ ScriptInstance *CSharpScript::instance_create(Object *p_this) {
#endif
if (native) {
- String native_name = native->get_name();
+ String native_name = NATIVE_GDMONOCLASS_NAME(native);
if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
if (ScriptDebugger::get_singleton()) {
CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
@@ -2701,7 +2958,7 @@ ScriptInstance *CSharpScript::instance_create(Object *p_this) {
}
Variant::CallError unchecked_error;
- return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this), unchecked_error);
+ return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this) != NULL, unchecked_error);
}
PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
@@ -2816,11 +3073,22 @@ Error CSharpScript::reload(bool p_keep_state) {
if (script_class) {
#ifdef DEBUG_ENABLED
- print_verbose("Found class " + script_class->get_namespace() + "." + script_class->get_name() + " for script " + get_path());
+ print_verbose("Found class " + script_class->get_full_name() + " for script " + get_path());
#endif
tool = script_class->has_attribute(CACHED_CLASS(ToolAttribute));
+ if (!tool) {
+ GDMonoClass *nesting_class = script_class->get_nesting_class();
+ tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
+ }
+
+#if TOOLS_ENABLED
+ if (!tool) {
+ tool = script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
+ }
+#endif
+
native = GDMonoUtils::get_class_native_base(script_class);
CRASH_COND(native == NULL);
@@ -2898,10 +3166,7 @@ void CSharpScript::update_exports() {
}
bool CSharpScript::has_script_signal(const StringName &p_signal) const {
- if (_signals.has(p_signal))
- return true;
-
- return false;
+ return _signals.has(p_signal);
}
void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
@@ -3021,7 +3286,8 @@ RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p
#endif
#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint() && mono_domain_get() == NULL) {
+ MonoDomain *domain = mono_domain_get();
+ if (Engine::get_singleton()->is_editor_hint() && domain == NULL) {
CRASH_COND(Thread::get_caller_id() == Thread::get_main_id());
@@ -3029,8 +3295,8 @@ RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p
// because this may be called by one of the editor's worker threads.
// Attach this thread temporarily to reload the script.
- if (SCRIPTS_DOMAIN) {
- MonoThread *mono_thread = mono_thread_attach(SCRIPTS_DOMAIN);
+ if (domain) {
+ MonoThread *mono_thread = mono_thread_attach(domain);
CRASH_COND(mono_thread == NULL);
script->reload();
mono_thread_detach(mono_thread);
@@ -3130,5 +3396,7 @@ CSharpLanguage::StringNameCache::StringNameCache() {
_get_property_list = StaticCString::create("_get_property_list");
_notification = StaticCString::create("_notification");
_script_source = StaticCString::create("script/source");
+ on_before_serialize = StaticCString::create("OnBeforeSerialize");
+ on_after_deserialize = StaticCString::create("OnAfterDeserialize");
dotctor = StaticCString::create(".ctor");
}
diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h
index e735e0f741..eb168f344d 100644
--- a/modules/mono/csharp_script.h
+++ b/modules/mono/csharp_script.h
@@ -41,6 +41,10 @@
#include "mono_gd/gd_mono_header.h"
#include "mono_gd/gd_mono_internals.h"
+#ifdef TOOLS_ENABLED
+#include "editor/editor_plugin.h"
+#endif
+
class CSharpScript;
class CSharpInstance;
class CSharpLanguage;
@@ -63,7 +67,7 @@ TScriptInstance *cast_script_instance(ScriptInstance *p_inst) {
class CSharpScript : public Script {
- GDCLASS(CSharpScript, Script)
+ GDCLASS(CSharpScript, Script);
friend class CSharpInstance;
friend class CSharpLanguage;
@@ -92,6 +96,8 @@ class CSharpScript : public Script {
Set<ObjectID> pending_reload_instances;
Map<ObjectID, StateBackup> pending_reload_state;
+ StringName tied_class_name_for_reload;
+ StringName tied_class_namespace_for_reload;
#endif
String source;
@@ -115,6 +121,7 @@ class CSharpScript : public Script {
bool placeholder_fallback_enabled;
bool exports_invalidated;
void _update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames);
+ void _update_member_info_no_exports();
virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder);
#endif
@@ -127,7 +134,7 @@ class CSharpScript : public Script {
bool _update_exports();
#ifdef TOOLS_ENABLED
- bool _get_member_export(IMonoClassMember *p_member, PropertyInfo &r_prop_info, bool &r_exported);
+ bool _get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported);
static int _try_get_member_export_hint(IMonoClassMember *p_member, ManagedType p_type, Variant::Type p_variant_type, bool p_allow_generics, PropertyHint &r_hint, String &r_hint_string);
#endif
@@ -137,6 +144,7 @@ class CSharpScript : public Script {
// Do not use unless you know what you are doing
friend void GDMonoInternals::tie_managed_to_unmanaged(MonoObject *, Object *);
static Ref<CSharpScript> create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native);
+ static void initialize_for_managed_type(Ref<CSharpScript> p_script, GDMonoClass *p_class, GDMonoClass *p_native);
protected:
static void _bind_methods();
@@ -226,6 +234,8 @@ class CSharpInstance : public ScriptInstance {
MultiplayerAPI::RPCMode _member_get_rpc_mode(IMonoClassMember *p_member) const;
+ void get_properties_state_for_reloading(List<Pair<StringName, Variant> > &r_state);
+
public:
MonoObject *get_mono_object() const;
@@ -276,6 +286,7 @@ struct CSharpScriptBinding {
StringName type_name;
GDMonoClass *wrapper_class;
Ref<MonoGCHandle> gchandle;
+ Object *owner;
};
class CSharpLanguage : public ScriptLanguage {
@@ -305,6 +316,8 @@ class CSharpLanguage : public ScriptLanguage {
StringName _notification;
StringName _script_source;
StringName dotctor; // .ctor
+ StringName on_before_serialize; // OnBeforeSerialize
+ StringName on_after_deserialize; // OnAfterDeserialize
StringNameCache();
};
@@ -324,6 +337,12 @@ class CSharpLanguage : public ScriptLanguage {
friend class GDMono;
void _on_scripts_domain_unloaded();
+#ifdef TOOLS_ENABLED
+ EditorPlugin *godotsharp_editor;
+
+ static void _editor_init_callback();
+#endif
+
public:
StringNameCache string_names;
@@ -336,8 +355,12 @@ public:
_FORCE_INLINE_ static CSharpLanguage *get_singleton() { return singleton; }
+#ifdef TOOLS_ENABLED
+ _FORCE_INLINE_ EditorPlugin *get_godotsharp_editor() const { return godotsharp_editor; }
+#endif
+
static void release_script_gchandle(Ref<MonoGCHandle> &p_gchandle);
- static void release_script_gchandle(MonoObject *p_pinned_expected_obj, Ref<MonoGCHandle> &p_gchandle);
+ static void release_script_gchandle(MonoObject *p_expected_obj, Ref<MonoGCHandle> &p_gchandle);
bool debug_break(const String &p_error, bool p_allow_continue = true);
bool debug_break_parse(const String &p_file, int p_line, const String &p_error);
@@ -380,7 +403,6 @@ public:
virtual bool supports_builtin_mode() const;
/* TODO? */ virtual int find_function(const String &p_function, const String &p_code) const { return -1; }
virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const;
- /* TODO? */ Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) { return ERR_UNAVAILABLE; }
virtual String _get_indentation() const;
/* TODO? */ virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const {}
/* TODO */ virtual void add_global_constant(const StringName &p_variable, const Variant &p_value) {}
@@ -441,7 +463,6 @@ public:
};
class ResourceFormatLoaderCSharpScript : public ResourceFormatLoader {
- GDCLASS(ResourceFormatLoaderCSharpScript, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
@@ -450,7 +471,6 @@ public:
};
class ResourceFormatSaverCSharpScript : public ResourceFormatSaver {
- GDCLASS(ResourceFormatSaverCSharpScript, ResourceFormatSaver)
public:
virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0);
virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const;
diff --git a/modules/mono/editor/GodotSharpTools/.gitignore b/modules/mono/editor/GodotSharpTools/.gitignore
deleted file mode 100644
index 296ad48834..0000000000
--- a/modules/mono/editor/GodotSharpTools/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# nuget packages
-packages \ No newline at end of file
diff --git a/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs b/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs
deleted file mode 100644
index e5044feb75..0000000000
--- a/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs
+++ /dev/null
@@ -1,425 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.Diagnostics;
-using System.IO;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Security;
-using Microsoft.Build.Framework;
-
-namespace GodotSharpTools.Build
-{
- public class BuildInstance : IDisposable
- {
- [MethodImpl(MethodImplOptions.InternalCall)]
- private extern static void godot_icall_BuildInstance_ExitCallback(string solution, string config, int exitCode);
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- private extern static string godot_icall_BuildInstance_get_MSBuildPath();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private extern static string godot_icall_BuildInstance_get_MonoWindowsBinDir();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private extern static bool godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows();
- [MethodImpl(MethodImplOptions.InternalCall)]
- private extern static bool godot_icall_BuildInstance_get_PrintBuildOutput();
-
- private static string GetMSBuildPath()
- {
- string msbuildPath = godot_icall_BuildInstance_get_MSBuildPath();
-
- if (msbuildPath == null)
- throw new FileNotFoundException("Cannot find the MSBuild executable.");
-
- return msbuildPath;
- }
-
- private static string MonoWindowsBinDir
- {
- get
- {
- string monoWinBinDir = godot_icall_BuildInstance_get_MonoWindowsBinDir();
-
- if (monoWinBinDir == null)
- throw new FileNotFoundException("Cannot find the Windows Mono binaries directory.");
-
- return monoWinBinDir;
- }
- }
-
- private static bool UsingMonoMSBuildOnWindows
- {
- get
- {
- return godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows();
- }
- }
-
- private static bool PrintBuildOutput
- {
- get
- {
- return godot_icall_BuildInstance_get_PrintBuildOutput();
- }
- }
-
- private string solution;
- private string config;
-
- private Process process;
-
- private int exitCode;
- public int ExitCode { get { return exitCode; } }
-
- public bool IsRunning { get { return process != null && !process.HasExited; } }
-
- public BuildInstance(string solution, string config)
- {
- this.solution = solution;
- this.config = config;
- }
-
- public bool Build(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null)
- {
- List<string> customPropertiesList = new List<string>();
-
- if (customProperties != null)
- customPropertiesList.AddRange(customProperties);
-
- string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customPropertiesList);
-
- ProcessStartInfo startInfo = new ProcessStartInfo(GetMSBuildPath(), compilerArgs);
-
- bool redirectOutput = !IsDebugMSBuildRequested() && !PrintBuildOutput;
-
- if (!redirectOutput) // TODO: or if stdout verbose
- Console.WriteLine($"Running: \"{startInfo.FileName}\" {startInfo.Arguments}");
-
- startInfo.RedirectStandardOutput = redirectOutput;
- startInfo.RedirectStandardError = redirectOutput;
- startInfo.UseShellExecute = false;
-
- if (UsingMonoMSBuildOnWindows)
- {
- // These environment variables are required for Mono's MSBuild to find the compilers.
- // We use the batch files in Mono's bin directory to make sure the compilers are executed with mono.
- string monoWinBinDir = MonoWindowsBinDir;
- startInfo.EnvironmentVariables.Add("CscToolExe", Path.Combine(monoWinBinDir, "csc.bat"));
- startInfo.EnvironmentVariables.Add("VbcToolExe", Path.Combine(monoWinBinDir, "vbc.bat"));
- startInfo.EnvironmentVariables.Add("FscToolExe", Path.Combine(monoWinBinDir, "fsharpc.bat"));
- }
-
- // Needed when running from Developer Command Prompt for VS
- RemovePlatformVariable(startInfo.EnvironmentVariables);
-
- using (Process process = new Process())
- {
- process.StartInfo = startInfo;
-
- process.Start();
-
- if (redirectOutput)
- {
- process.BeginOutputReadLine();
- process.BeginErrorReadLine();
- }
-
- process.WaitForExit();
-
- exitCode = process.ExitCode;
- }
-
- return true;
- }
-
- public bool BuildAsync(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null)
- {
- if (process != null)
- throw new InvalidOperationException("Already in use");
-
- List<string> customPropertiesList = new List<string>();
-
- if (customProperties != null)
- customPropertiesList.AddRange(customProperties);
-
- string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customPropertiesList);
-
- ProcessStartInfo startInfo = new ProcessStartInfo(GetMSBuildPath(), compilerArgs);
-
- bool redirectOutput = !IsDebugMSBuildRequested() && !PrintBuildOutput;
-
- if (!redirectOutput) // TODO: or if stdout verbose
- Console.WriteLine($"Running: \"{startInfo.FileName}\" {startInfo.Arguments}");
-
- startInfo.RedirectStandardOutput = redirectOutput;
- startInfo.RedirectStandardError = redirectOutput;
- startInfo.UseShellExecute = false;
-
- if (UsingMonoMSBuildOnWindows)
- {
- // These environment variables are required for Mono's MSBuild to find the compilers.
- // We use the batch files in Mono's bin directory to make sure the compilers are executed with mono.
- string monoWinBinDir = MonoWindowsBinDir;
- startInfo.EnvironmentVariables.Add("CscToolExe", Path.Combine(monoWinBinDir, "csc.bat"));
- startInfo.EnvironmentVariables.Add("VbcToolExe", Path.Combine(monoWinBinDir, "vbc.bat"));
- startInfo.EnvironmentVariables.Add("FscToolExe", Path.Combine(monoWinBinDir, "fsharpc.bat"));
- }
-
- // Needed when running from Developer Command Prompt for VS
- RemovePlatformVariable(startInfo.EnvironmentVariables);
-
- process = new Process();
- process.StartInfo = startInfo;
- process.EnableRaisingEvents = true;
- process.Exited += new EventHandler(BuildProcess_Exited);
-
- process.Start();
-
- if (redirectOutput)
- {
- process.BeginOutputReadLine();
- process.BeginErrorReadLine();
- }
-
- return true;
- }
-
- private string BuildArguments(string loggerAssemblyPath, string loggerOutputDir, List<string> customProperties)
- {
- string arguments = string.Format(@"""{0}"" /v:normal /t:Rebuild ""/p:{1}"" ""/l:{2},{3};{4}""",
- solution,
- "Configuration=" + config,
- typeof(GodotBuildLogger).FullName,
- loggerAssemblyPath,
- loggerOutputDir
- );
-
- foreach (string customProperty in customProperties)
- {
- arguments += " /p:" + customProperty;
- }
-
- return arguments;
- }
-
- private void RemovePlatformVariable(StringDictionary environmentVariables)
- {
- // EnvironmentVariables is case sensitive? Seriously?
-
- List<string> platformEnvironmentVariables = new List<string>();
-
- foreach (string env in environmentVariables.Keys)
- {
- if (env.ToUpper() == "PLATFORM")
- platformEnvironmentVariables.Add(env);
- }
-
- foreach (string env in platformEnvironmentVariables)
- environmentVariables.Remove(env);
- }
-
- private void BuildProcess_Exited(object sender, System.EventArgs e)
- {
- exitCode = process.ExitCode;
-
- godot_icall_BuildInstance_ExitCallback(solution, config, exitCode);
-
- Dispose();
- }
-
- private static bool IsDebugMSBuildRequested()
- {
- return Environment.GetEnvironmentVariable("GODOT_DEBUG_MSBUILD")?.Trim() == "1";
- }
-
- public void Dispose()
- {
- if (process != null)
- {
- process.Dispose();
- process = null;
- }
- }
- }
-
- public class GodotBuildLogger : ILogger
- {
- public string Parameters { get; set; }
- public LoggerVerbosity Verbosity { get; set; }
-
- public void Initialize(IEventSource eventSource)
- {
- if (null == Parameters)
- throw new LoggerException("Log directory was not set.");
-
- string[] parameters = Parameters.Split(new[] { ';' });
-
- string logDir = parameters[0];
-
- if (String.IsNullOrEmpty(logDir))
- throw new LoggerException("Log directory was not set.");
-
- if (parameters.Length > 1)
- throw new LoggerException("Too many parameters passed.");
-
- string logFile = Path.Combine(logDir, "msbuild_log.txt");
- string issuesFile = Path.Combine(logDir, "msbuild_issues.csv");
-
- try
- {
- if (!Directory.Exists(logDir))
- Directory.CreateDirectory(logDir);
-
- this.logStreamWriter = new StreamWriter(logFile);
- this.issuesStreamWriter = new StreamWriter(issuesFile);
- }
- catch (Exception ex)
- {
- if
- (
- ex is UnauthorizedAccessException
- || ex is ArgumentNullException
- || ex is PathTooLongException
- || ex is DirectoryNotFoundException
- || ex is NotSupportedException
- || ex is ArgumentException
- || ex is SecurityException
- || ex is IOException
- )
- {
- throw new LoggerException("Failed to create log file: " + ex.Message);
- }
- else
- {
- // Unexpected failure
- throw;
- }
- }
-
- eventSource.ProjectStarted += new ProjectStartedEventHandler(eventSource_ProjectStarted);
- eventSource.TaskStarted += new TaskStartedEventHandler(eventSource_TaskStarted);
- eventSource.MessageRaised += new BuildMessageEventHandler(eventSource_MessageRaised);
- eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
- eventSource.ErrorRaised += new BuildErrorEventHandler(eventSource_ErrorRaised);
- eventSource.ProjectFinished += new ProjectFinishedEventHandler(eventSource_ProjectFinished);
- }
-
- void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e)
- {
- string line = String.Format("{0}({1},{2}): error {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message);
-
- if (e.ProjectFile.Length > 0)
- line += string.Format(" [{0}]", e.ProjectFile);
-
- WriteLine(line);
-
- string errorLine = String.Format(@"error,{0},{1},{2},{3},{4},{5}",
- e.File.CsvEscape(), e.LineNumber, e.ColumnNumber,
- e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile.CsvEscape());
- issuesStreamWriter.WriteLine(errorLine);
- }
-
- void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
- {
- string line = String.Format("{0}({1},{2}): warning {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message, e.ProjectFile);
-
- if (e.ProjectFile != null && e.ProjectFile.Length > 0)
- line += string.Format(" [{0}]", e.ProjectFile);
-
- WriteLine(line);
-
- string warningLine = String.Format(@"warning,{0},{1},{2},{3},{4},{5}",
- e.File.CsvEscape(), e.LineNumber, e.ColumnNumber,
- e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile != null ? e.ProjectFile.CsvEscape() : string.Empty);
- issuesStreamWriter.WriteLine(warningLine);
- }
-
- void eventSource_MessageRaised(object sender, BuildMessageEventArgs e)
- {
- // BuildMessageEventArgs adds Importance to BuildEventArgs
- // Let's take account of the verbosity setting we've been passed in deciding whether to log the message
- if ((e.Importance == MessageImportance.High && IsVerbosityAtLeast(LoggerVerbosity.Minimal))
- || (e.Importance == MessageImportance.Normal && IsVerbosityAtLeast(LoggerVerbosity.Normal))
- || (e.Importance == MessageImportance.Low && IsVerbosityAtLeast(LoggerVerbosity.Detailed))
- )
- {
- WriteLineWithSenderAndMessage(String.Empty, e);
- }
- }
-
- void eventSource_TaskStarted(object sender, TaskStartedEventArgs e)
- {
- // TaskStartedEventArgs adds ProjectFile, TaskFile, TaskName
- // To keep this log clean, this logger will ignore these events.
- }
-
- void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e)
- {
- WriteLine(e.Message);
- indent++;
- }
-
- void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e)
- {
- indent--;
- WriteLine(e.Message);
- }
-
- /// <summary>
- /// Write a line to the log, adding the SenderName
- /// </summary>
- private void WriteLineWithSender(string line, BuildEventArgs e)
- {
- if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/))
- {
- // Well, if the sender name is MSBuild, let's leave it out for prettiness
- WriteLine(line);
- }
- else
- {
- WriteLine(e.SenderName + ": " + line);
- }
- }
-
- /// <summary>
- /// Write a line to the log, adding the SenderName and Message
- /// (these parameters are on all MSBuild event argument objects)
- /// </summary>
- private void WriteLineWithSenderAndMessage(string line, BuildEventArgs e)
- {
- if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/))
- {
- // Well, if the sender name is MSBuild, let's leave it out for prettiness
- WriteLine(line + e.Message);
- }
- else
- {
- WriteLine(e.SenderName + ": " + line + e.Message);
- }
- }
-
- private void WriteLine(string line)
- {
- for (int i = indent; i > 0; i--)
- {
- logStreamWriter.Write("\t");
- }
- logStreamWriter.WriteLine(line);
- }
-
- public void Shutdown()
- {
- logStreamWriter.Close();
- issuesStreamWriter.Close();
- }
-
- public bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity)
- {
- return this.Verbosity >= checkVerbosity;
- }
-
- private StreamWriter logStreamWriter;
- private StreamWriter issuesStreamWriter;
- private int indent;
- }
-}
diff --git a/modules/mono/editor/GodotSharpTools/Editor/GodotSharpExport.cs b/modules/mono/editor/GodotSharpTools/Editor/GodotSharpExport.cs
deleted file mode 100644
index e45dd2025b..0000000000
--- a/modules/mono/editor/GodotSharpTools/Editor/GodotSharpExport.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Runtime.CompilerServices;
-
-namespace GodotSharpTools.Editor
-{
- public static class GodotSharpExport
- {
- public static void _ExportBegin(string[] features, bool debug, string path, int flags)
- {
- var featureSet = new HashSet<string>(features);
-
- if (PlatformHasTemplateDir(featureSet))
- {
- string templateDirName = "data.mono";
-
- if (featureSet.Contains("Windows"))
- {
- templateDirName += ".windows";
- templateDirName += featureSet.Contains("64") ? ".64" : ".32";
- }
- else if (featureSet.Contains("X11"))
- {
- templateDirName += ".x11";
- templateDirName += featureSet.Contains("64") ? ".64" : ".32";
- }
- else
- {
- throw new NotSupportedException("Target platform not supported");
- }
-
- templateDirName += debug ? ".release_debug" : ".release";
-
- string templateDirPath = Path.Combine(GetTemplatesDir(), templateDirName);
-
- if (!Directory.Exists(templateDirPath))
- throw new FileNotFoundException("Data template directory not found");
-
- string outputDir = new FileInfo(path).Directory.FullName;
-
- string outputDataDir = Path.Combine(outputDir, GetDataDirName());
-
- if (Directory.Exists(outputDataDir))
- Directory.Delete(outputDataDir, recursive: true); // Clean first
-
- Directory.CreateDirectory(outputDataDir);
-
- foreach (string dir in Directory.GetDirectories(templateDirPath, "*", SearchOption.AllDirectories))
- {
- Directory.CreateDirectory(Path.Combine(outputDataDir, dir.Substring(templateDirPath.Length + 1)));
- }
-
- foreach (string file in Directory.GetFiles(templateDirPath, "*", SearchOption.AllDirectories))
- {
- File.Copy(file, Path.Combine(outputDataDir, file.Substring(templateDirPath.Length + 1)));
- }
- }
- }
-
- public static bool PlatformHasTemplateDir(HashSet<string> featureSet)
- {
- // OSX export templates are contained in a zip, so we place
- // our custom template inside it and let Godot do the rest.
- return !featureSet.Contains("OSX");
- }
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- extern static string GetTemplatesDir();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- extern static string GetDataDirName();
- }
-}
diff --git a/modules/mono/editor/GodotSharpTools/GodotSharpTools.sln b/modules/mono/editor/GodotSharpTools/GodotSharpTools.sln
deleted file mode 100644
index 5f7d0e8a39..0000000000
--- a/modules/mono/editor/GodotSharpTools/GodotSharpTools.sln
+++ /dev/null
@@ -1,17 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 2012
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotSharpTools", "GodotSharpTools.csproj", "{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Release|Any CPU.Build.0 = Release|Any CPU
- EndGlobalSection
-EndGlobal
diff --git a/modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs b/modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs
deleted file mode 100644
index a13f4fd6ef..0000000000
--- a/modules/mono/editor/GodotSharpTools/Project/ProjectUtils.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-using System.Collections.Generic;
-using System.IO;
-using DotNet.Globbing;
-using Microsoft.Build.Construction;
-
-namespace GodotSharpTools.Project
-{
- public static class ProjectUtils
- {
- public static void AddItemToProjectChecked(string projectPath, string itemType, string include)
- {
- var dir = Directory.GetParent(projectPath).FullName;
- var root = ProjectRootElement.Open(projectPath);
- var normalizedInclude = include.RelativeToPath(dir).Replace("/", "\\");
-
- if (root.AddItemChecked(itemType, normalizedInclude))
- root.Save();
- }
-
- private static string[] GetAllFilesRecursive(string rootDirectory, string mask)
- {
- string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories);
-
- // We want relative paths
- for (int i = 0; i < files.Length; i++) {
- files[i] = files[i].RelativeToPath(rootDirectory);
- }
-
- return files;
- }
-
- public static string[] GetIncludeFiles(string projectPath, string itemType)
- {
- var result = new List<string>();
- var existingFiles = GetAllFilesRecursive(Path.GetDirectoryName(projectPath), "*.cs");
-
- GlobOptions globOptions = new GlobOptions();
- globOptions.Evaluation.CaseInsensitive = false;
-
- var root = ProjectRootElement.Open(projectPath);
-
- foreach (var itemGroup in root.ItemGroups)
- {
- if (itemGroup.Condition.Length != 0)
- continue;
-
- foreach (var item in itemGroup.Items)
- {
- if (item.ItemType != itemType)
- continue;
-
- string normalizedInclude = item.Include.NormalizePath();
-
- var glob = Glob.Parse(normalizedInclude, globOptions);
-
- // TODO Check somehow if path has no blog to avoid the following loop...
-
- foreach (var existingFile in existingFiles)
- {
- if (glob.IsMatch(existingFile))
- {
- result.Add(existingFile);
- }
- }
- }
- }
-
- return result.ToArray();
- }
- }
-}
diff --git a/modules/mono/editor/GodotSharpTools/Utils/OS.cs b/modules/mono/editor/GodotSharpTools/Utils/OS.cs
deleted file mode 100644
index 148e954e77..0000000000
--- a/modules/mono/editor/GodotSharpTools/Utils/OS.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-using System;
-using System.Linq;
-using System.Runtime.CompilerServices;
-
-namespace GodotSharpTools.Utils
-{
- public static class OS
- {
- [MethodImpl(MethodImplOptions.InternalCall)]
- extern static string GetPlatformName();
-
- const string HaikuName = "Haiku";
- const string OSXName = "OSX";
- const string ServerName = "Server";
- const string UWPName = "UWP";
- const string WindowsName = "Windows";
- const string X11Name = "X11";
-
- public static bool IsHaiku()
- {
- return HaikuName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
- }
-
- public static bool IsOSX()
- {
- return OSXName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
- }
-
- public static bool IsServer()
- {
- return ServerName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
- }
-
- public static bool IsUWP()
- {
- return UWPName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
- }
-
- public static bool IsWindows()
- {
- return WindowsName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
- }
-
- public static bool IsX11()
- {
- return X11Name.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
- }
-
- static bool? IsUnixCache = null;
- static readonly string[] UnixPlatforms = new string[] { HaikuName, OSXName, ServerName, X11Name };
-
- public static bool IsUnix()
- {
- if (IsUnixCache.HasValue)
- return IsUnixCache.Value;
-
- string osName = GetPlatformName();
- IsUnixCache = UnixPlatforms.Any(p => p.Equals(osName, StringComparison.OrdinalIgnoreCase));
- return IsUnixCache.Value;
- }
- }
-}
diff --git a/modules/mono/editor/GodotTools/.gitignore b/modules/mono/editor/GodotTools/.gitignore
new file mode 100644
index 0000000000..48e2f914d8
--- /dev/null
+++ b/modules/mono/editor/GodotTools/.gitignore
@@ -0,0 +1,356 @@
+# Rider
+.idea/
+
+# Visual Studio Code
+.vscode/
+
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Ll]og/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# JustCode is a .NET coding add-in
+.JustCode
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs
new file mode 100644
index 0000000000..a0f6f1ff32
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotBuildLogger.cs
@@ -0,0 +1,186 @@
+using System;
+using System.IO;
+using System.Security;
+using Microsoft.Build.Framework;
+using GodotTools.Core;
+
+namespace GodotTools.BuildLogger
+{
+ public class GodotBuildLogger : ILogger
+ {
+ public static readonly string AssemblyPath = Path.GetFullPath(typeof(GodotBuildLogger).Assembly.Location);
+
+ public string Parameters { get; set; }
+ public LoggerVerbosity Verbosity { get; set; }
+
+ public void Initialize(IEventSource eventSource)
+ {
+ if (null == Parameters)
+ throw new LoggerException("Log directory was not set.");
+
+ var parameters = Parameters.Split(new[] {';'});
+
+ string logDir = parameters[0];
+
+ if (string.IsNullOrEmpty(logDir))
+ throw new LoggerException("Log directory was not set.");
+
+ if (parameters.Length > 1)
+ throw new LoggerException("Too many parameters passed.");
+
+ string logFile = Path.Combine(logDir, "msbuild_log.txt");
+ string issuesFile = Path.Combine(logDir, "msbuild_issues.csv");
+
+ try
+ {
+ if (!Directory.Exists(logDir))
+ Directory.CreateDirectory(logDir);
+
+ logStreamWriter = new StreamWriter(logFile);
+ issuesStreamWriter = new StreamWriter(issuesFile);
+ }
+ catch (Exception ex)
+ {
+ if (ex is UnauthorizedAccessException
+ || ex is ArgumentNullException
+ || ex is PathTooLongException
+ || ex is DirectoryNotFoundException
+ || ex is NotSupportedException
+ || ex is ArgumentException
+ || ex is SecurityException
+ || ex is IOException)
+ {
+ throw new LoggerException("Failed to create log file: " + ex.Message);
+ }
+ else
+ {
+ // Unexpected failure
+ throw;
+ }
+ }
+
+ eventSource.ProjectStarted += eventSource_ProjectStarted;
+ eventSource.TaskStarted += eventSource_TaskStarted;
+ eventSource.MessageRaised += eventSource_MessageRaised;
+ eventSource.WarningRaised += eventSource_WarningRaised;
+ eventSource.ErrorRaised += eventSource_ErrorRaised;
+ eventSource.ProjectFinished += eventSource_ProjectFinished;
+ }
+
+ void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e)
+ {
+ string line = $"{e.File}({e.LineNumber},{e.ColumnNumber}): error {e.Code}: {e.Message}";
+
+ if (e.ProjectFile.Length > 0)
+ line += $" [{e.ProjectFile}]";
+
+ WriteLine(line);
+
+ string errorLine = $@"error,{e.File.CsvEscape()},{e.LineNumber},{e.ColumnNumber}," +
+ $@"{e.Code.CsvEscape()},{e.Message.CsvEscape()},{e.ProjectFile.CsvEscape()}";
+ issuesStreamWriter.WriteLine(errorLine);
+ }
+
+ void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
+ {
+ string line = $"{e.File}({e.LineNumber},{e.ColumnNumber}): warning {e.Code}: {e.Message}";
+
+ if (!string.IsNullOrEmpty(e.ProjectFile))
+ line += $" [{e.ProjectFile}]";
+
+ WriteLine(line);
+
+ string warningLine = $@"warning,{e.File.CsvEscape()},{e.LineNumber},{e.ColumnNumber},{e.Code.CsvEscape()}," +
+ $@"{e.Message.CsvEscape()},{(e.ProjectFile != null ? e.ProjectFile.CsvEscape() : string.Empty)}";
+ issuesStreamWriter.WriteLine(warningLine);
+ }
+
+ private void eventSource_MessageRaised(object sender, BuildMessageEventArgs e)
+ {
+ // BuildMessageEventArgs adds Importance to BuildEventArgs
+ // Let's take account of the verbosity setting we've been passed in deciding whether to log the message
+ if (e.Importance == MessageImportance.High && IsVerbosityAtLeast(LoggerVerbosity.Minimal)
+ || e.Importance == MessageImportance.Normal && IsVerbosityAtLeast(LoggerVerbosity.Normal)
+ || e.Importance == MessageImportance.Low && IsVerbosityAtLeast(LoggerVerbosity.Detailed))
+ {
+ WriteLineWithSenderAndMessage(string.Empty, e);
+ }
+ }
+
+ private void eventSource_TaskStarted(object sender, TaskStartedEventArgs e)
+ {
+ // TaskStartedEventArgs adds ProjectFile, TaskFile, TaskName
+ // To keep this log clean, this logger will ignore these events.
+ }
+
+ private void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e)
+ {
+ WriteLine(e.Message);
+ indent++;
+ }
+
+ private void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e)
+ {
+ indent--;
+ WriteLine(e.Message);
+ }
+
+ /// <summary>
+ /// Write a line to the log, adding the SenderName
+ /// </summary>
+ private void WriteLineWithSender(string line, BuildEventArgs e)
+ {
+ if (0 == string.Compare(e.SenderName, "MSBuild", StringComparison.OrdinalIgnoreCase))
+ {
+ // Well, if the sender name is MSBuild, let's leave it out for prettiness
+ WriteLine(line);
+ }
+ else
+ {
+ WriteLine(e.SenderName + ": " + line);
+ }
+ }
+
+ /// <summary>
+ /// Write a line to the log, adding the SenderName and Message
+ /// (these parameters are on all MSBuild event argument objects)
+ /// </summary>
+ private void WriteLineWithSenderAndMessage(string line, BuildEventArgs e)
+ {
+ if (0 == string.Compare(e.SenderName, "MSBuild", StringComparison.OrdinalIgnoreCase))
+ {
+ // Well, if the sender name is MSBuild, let's leave it out for prettiness
+ WriteLine(line + e.Message);
+ }
+ else
+ {
+ WriteLine(e.SenderName + ": " + line + e.Message);
+ }
+ }
+
+ private void WriteLine(string line)
+ {
+ for (int i = indent; i > 0; i--)
+ {
+ logStreamWriter.Write("\t");
+ }
+
+ logStreamWriter.WriteLine(line);
+ }
+
+ public void Shutdown()
+ {
+ logStreamWriter.Close();
+ issuesStreamWriter.Close();
+ }
+
+ private bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity)
+ {
+ return Verbosity >= checkVerbosity;
+ }
+
+ private StreamWriter logStreamWriter;
+ private StreamWriter issuesStreamWriter;
+ private int indent;
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
new file mode 100644
index 0000000000..f3ac353c0f
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/GodotTools.BuildLogger.csproj
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProjectGuid>{6CE9A984-37B1-4F8A-8FE9-609F05F071B3}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>GodotTools.BuildLogger</RootNamespace>
+ <AssemblyName>GodotTools.BuildLogger</AssemblyName>
+ <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <PlatformTarget>AnyCPU</PlatformTarget>
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>portable</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <PlatformTarget>AnyCPU</PlatformTarget>
+ <DebugType>portable</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="Microsoft.Build.Framework" />
+ <Reference Include="System" />
+ <Reference Include="System.Core" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="GodotBuildLogger.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\GodotTools.Core\GodotTools.Core.csproj">
+ <Project>{639e48bd-44e5-4091-8edd-22d36dc0768d}</Project>
+ <Name>GodotTools.Core</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project> \ No newline at end of file
diff --git a/modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000000..8717c4901e
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.BuildLogger/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("GodotTools.BuildLogger")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("")]
+[assembly: AssemblyCopyright("Godot Engine contributors")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("6CE9A984-37B1-4F8A-8FE9-609F05F071B3")]
+
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj b/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
new file mode 100644
index 0000000000..f36b40f87c
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.Core/GodotTools.Core.csproj
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProjectGuid>{639E48BD-44E5-4091-8EDD-22D36DC0768D}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <RootNamespace>GodotTools.Core</RootNamespace>
+ <AssemblyName>GodotTools.Core</AssemblyName>
+ <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug</OutputPath>
+ <DefineConstants>DEBUG;</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <ConsolePause>false</ConsolePause>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release</OutputPath>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <ConsolePause>false</ConsolePause>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="ProcessExtensions.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="StringExtensions.cs" />
+ </ItemGroup>
+ <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+</Project> \ No newline at end of file
diff --git a/modules/mono/editor/GodotTools/GodotTools.Core/ProcessExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.Core/ProcessExtensions.cs
new file mode 100644
index 0000000000..43d40f2ad9
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.Core/ProcessExtensions.cs
@@ -0,0 +1,38 @@
+using System;
+using System.Diagnostics;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace GodotTools.Core
+{
+ public static class ProcessExtensions
+ {
+ public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ var tcs = new TaskCompletionSource<bool>();
+
+ void ProcessExited(object sender, EventArgs e)
+ {
+ tcs.TrySetResult(true);
+ }
+
+ process.EnableRaisingEvents = true;
+ process.Exited += ProcessExited;
+
+ try
+ {
+ if (process.HasExited)
+ return;
+
+ using (cancellationToken.Register(() => tcs.TrySetCanceled()))
+ {
+ await tcs.Task;
+ }
+ }
+ finally
+ {
+ process.Exited -= ProcessExited;
+ }
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000000..699ae6e741
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.Core/Properties/AssemblyInfo.cs
@@ -0,0 +1,26 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+// Information about this assembly is defined by the following attributes.
+// Change them to the values specific to your project.
+
+[assembly: AssemblyTitle("GodotTools.Core")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("")]
+[assembly: AssemblyCopyright("Godot Engine contributors")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
+// The form "{Major}.{Minor}.*" will automatically update the build and revision,
+// and "{Major}.{Minor}.{Build}.*" will update just the revision.
+
+[assembly: AssemblyVersion("1.0.*")]
+
+// The following attributes are used to specify the signing key for the assembly,
+// if desired. See the Mono documentation for more information about signing.
+
+//[assembly: AssemblyDelaySign(false)]
+//[assembly: AssemblyKeyFile("")]
diff --git a/modules/mono/editor/GodotSharpTools/StringExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs
index b0436d2f18..8cd7e76303 100644
--- a/modules/mono/editor/GodotSharpTools/StringExtensions.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs
@@ -1,7 +1,8 @@
using System;
+using System.Collections.Generic;
using System.IO;
-namespace GodotSharpTools
+namespace GodotTools.Core
{
public static class StringExtensions
{
@@ -25,7 +26,7 @@ namespace GodotSharpTools
path = path.Replace('\\', '/');
- string[] parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
+ string[] parts = path.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
path = string.Join(Path.DirectorySeparatorChar.ToString(), parts).Trim();
@@ -37,18 +38,40 @@ namespace GodotSharpTools
public static bool IsAbsolutePath(this string path)
{
return path.StartsWith("/", StringComparison.Ordinal) ||
- path.StartsWith("\\", StringComparison.Ordinal) ||
- path.StartsWith(driveRoot, StringComparison.Ordinal);
+ path.StartsWith("\\", StringComparison.Ordinal) ||
+ path.StartsWith(driveRoot, StringComparison.Ordinal);
}
public static string CsvEscape(this string value, char delimiter = ',')
{
- bool hasSpecialChar = value.IndexOfAny(new char[] { '\"', '\n', '\r', delimiter }) != -1;
+ bool hasSpecialChar = value.IndexOfAny(new char[] {'\"', '\n', '\r', delimiter}) != -1;
if (hasSpecialChar)
return "\"" + value.Replace("\"", "\"\"") + "\"";
return value;
}
+
+ public static string ToSafeDirName(this string dirName, bool allowDirSeparator)
+ {
+ var invalidChars = new List<string> {":", "*", "?", "\"", "<", ">", "|"};
+
+ if (allowDirSeparator)
+ {
+ // Directory separators are allowed, but disallow ".." to avoid going up the filesystem
+ invalidChars.Add("..");
+ }
+ else
+ {
+ invalidChars.Add("/");
+ }
+
+ string safeDirName = dirName.Replace("\\", "/").Trim();
+
+ foreach (string invalidChar in invalidChars)
+ safeDirName = safeDirName.Replace(invalidChar, "-");
+
+ return safeDirName;
+ }
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiAssembliesInfo.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiAssembliesInfo.cs
new file mode 100644
index 0000000000..345a472185
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiAssembliesInfo.cs
@@ -0,0 +1,15 @@
+namespace GodotTools
+{
+ public static class ApiAssemblyNames
+ {
+ public const string SolutionName = "GodotSharp";
+ public const string Core = "GodotSharp";
+ public const string Editor = "GodotSharpEditor";
+ }
+
+ public enum ApiAssemblyType
+ {
+ Core,
+ Editor
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiSolutionGenerator.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiSolutionGenerator.cs
new file mode 100644
index 0000000000..bfae2afc13
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ApiSolutionGenerator.cs
@@ -0,0 +1,52 @@
+using System.Collections.Generic;
+using System.IO;
+
+namespace GodotTools.ProjectEditor
+{
+ public static class ApiSolutionGenerator
+ {
+ public static void GenerateApiSolution(string solutionDir,
+ string coreProjDir, IEnumerable<string> coreCompileItems,
+ string editorProjDir, IEnumerable<string> editorCompileItems)
+ {
+ var solution = new DotNetSolution(ApiAssemblyNames.SolutionName);
+
+ solution.DirectoryPath = solutionDir;
+
+ // GodotSharp project
+
+ const string coreApiAssemblyName = ApiAssemblyNames.Core;
+
+ string coreGuid = ProjectGenerator.GenCoreApiProject(coreProjDir, coreCompileItems);
+
+ var coreProjInfo = new DotNetSolution.ProjectInfo
+ {
+ Guid = coreGuid,
+ PathRelativeToSolution = Path.Combine(coreApiAssemblyName, $"{coreApiAssemblyName}.csproj")
+ };
+ coreProjInfo.Configs.Add("Debug");
+ coreProjInfo.Configs.Add("Release");
+
+ solution.AddNewProject(coreApiAssemblyName, coreProjInfo);
+
+ // GodotSharpEditor project
+
+ const string editorApiAssemblyName = ApiAssemblyNames.Editor;
+
+ string editorGuid = ProjectGenerator.GenEditorApiProject(editorProjDir,
+ $"../{coreApiAssemblyName}/{coreApiAssemblyName}.csproj", editorCompileItems);
+
+ var editorProjInfo = new DotNetSolution.ProjectInfo();
+ editorProjInfo.Guid = editorGuid;
+ editorProjInfo.PathRelativeToSolution = Path.Combine(editorApiAssemblyName, $"{editorApiAssemblyName}.csproj");
+ editorProjInfo.Configs.Add("Debug");
+ editorProjInfo.Configs.Add("Release");
+
+ solution.AddNewProject(editorApiAssemblyName, editorProjInfo);
+
+ // Save solution
+
+ solution.Save();
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs
new file mode 100644
index 0000000000..76cb249acf
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs
@@ -0,0 +1,122 @@
+using GodotTools.Core;
+using System.Collections.Generic;
+using System.IO;
+
+namespace GodotTools.ProjectEditor
+{
+ public class DotNetSolution
+ {
+ private string directoryPath;
+ private readonly Dictionary<string, ProjectInfo> projects = new Dictionary<string, ProjectInfo>();
+
+ public string Name { get; }
+
+ public string DirectoryPath
+ {
+ get => directoryPath;
+ set => directoryPath = value.IsAbsolutePath() ? value : Path.GetFullPath(value);
+ }
+
+ public class ProjectInfo
+ {
+ public string Guid;
+ public string PathRelativeToSolution;
+ public List<string> Configs = new List<string>();
+ }
+
+ public void AddNewProject(string name, ProjectInfo projectInfo)
+ {
+ projects[name] = projectInfo;
+ }
+
+ public bool HasProject(string name)
+ {
+ return projects.ContainsKey(name);
+ }
+
+ public ProjectInfo GetProjectInfo(string name)
+ {
+ return projects[name];
+ }
+
+ public bool RemoveProject(string name)
+ {
+ return projects.Remove(name);
+ }
+
+ public void Save()
+ {
+ if (!Directory.Exists(DirectoryPath))
+ throw new FileNotFoundException("The solution directory does not exist.");
+
+ string projectsDecl = string.Empty;
+ string slnPlatformsCfg = string.Empty;
+ string projPlatformsCfg = string.Empty;
+
+ bool isFirstProject = true;
+
+ foreach (var pair in projects)
+ {
+ string name = pair.Key;
+ ProjectInfo projectInfo = pair.Value;
+
+ if (!isFirstProject)
+ projectsDecl += "\n";
+
+ projectsDecl += string.Format(ProjectDeclaration,
+ name, projectInfo.PathRelativeToSolution.Replace("/", "\\"), projectInfo.Guid);
+
+ for (int i = 0; i < projectInfo.Configs.Count; i++)
+ {
+ string config = projectInfo.Configs[i];
+
+ if (i != 0 || !isFirstProject)
+ {
+ slnPlatformsCfg += "\n";
+ projPlatformsCfg += "\n";
+ }
+
+ slnPlatformsCfg += string.Format(SolutionPlatformsConfig, config);
+ projPlatformsCfg += string.Format(ProjectPlatformsConfig, projectInfo.Guid, config);
+ }
+
+ isFirstProject = false;
+ }
+
+ string solutionPath = Path.Combine(DirectoryPath, Name + ".sln");
+ string content = string.Format(SolutionTemplate, projectsDecl, slnPlatformsCfg, projPlatformsCfg);
+
+ File.WriteAllText(solutionPath, content);
+ }
+
+ public DotNetSolution(string name)
+ {
+ Name = name;
+ }
+
+ const string SolutionTemplate =
+@"Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 2012
+{0}
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+{1}
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+{2}
+ EndGlobalSection
+EndGlobal
+";
+
+ const string ProjectDeclaration =
+@"Project(""{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}"") = ""{0}"", ""{1}"", ""{{{2}}}""
+EndProject";
+
+ const string SolutionPlatformsConfig =
+@" {0}|Any CPU = {0}|Any CPU";
+
+ const string ProjectPlatformsConfig =
+@" {{{0}}}.{1}|Any CPU.ActiveCfg = {1}|Any CPU
+ {{{0}}}.{1}|Any CPU.Build.0 = {1}|Any CPU";
+ }
+}
diff --git a/modules/mono/editor/GodotSharpTools/GodotSharpTools.csproj b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
index 2871c041f5..08b8ba3946 100644
--- a/modules/mono/editor/GodotSharpTools/GodotSharpTools.csproj
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/GodotTools.ProjectEditor.csproj
@@ -1,12 +1,12 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}</ProjectGuid>
<OutputType>Library</OutputType>
- <RootNamespace>GodotSharpTools</RootNamespace>
- <AssemblyName>GodotSharpTools</AssemblyName>
+ <RootNamespace>GodotTools.ProjectEditor</RootNamespace>
+ <AssemblyName>GodotTools.ProjectEditor</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<BaseIntermediateOutputPath>obj</BaseIntermediateOutputPath>
</PropertyGroup>
@@ -21,7 +21,6 @@
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <DebugType>portable</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
@@ -31,25 +30,35 @@
<ItemGroup>
<Reference Include="System" />
<Reference Include="Microsoft.Build" />
- <Reference Include="Microsoft.Build.Framework" />
<Reference Include="DotNet.Glob, Version=2.1.1.0, Culture=neutral, PublicKeyToken=b68cc888b4f632d1, processorArchitecture=MSIL">
- <HintPath>packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll</HintPath>
+ <!--
+ When building Godot with 'mono_glue=no' SCons will build this project alone instead of the
+ entire solution. $(SolutionDir) is not defined in that case, so we need to workaround that.
+ We make SCons restore the NuGet packages in the project directory instead in this case.
+ -->
+ <HintPath Condition=" '$(SolutionDir)' != '' ">$(SolutionDir)\packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll</HintPath>
+ <HintPath>$(ProjectDir)\packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll</HintPath>
+ <HintPath>packages\DotNet.Glob.2.1.1\lib\net45\DotNet.Glob.dll</HintPath> <!-- Are you happy CI? -->
</Reference>
</ItemGroup>
<ItemGroup>
- <Compile Include="StringExtensions.cs" />
- <Compile Include="Build\BuildSystem.cs" />
- <Compile Include="Editor\MonoDevelopInstance.cs" />
- <Compile Include="Project\ProjectExtensions.cs" />
- <Compile Include="Project\IdentifierUtils.cs" />
- <Compile Include="Project\ProjectGenerator.cs" />
- <Compile Include="Project\ProjectUtils.cs" />
+ <Compile Include="ApiAssembliesInfo.cs" />
+ <Compile Include="ApiSolutionGenerator.cs" />
+ <Compile Include="DotNetSolution.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="Utils\OS.cs" />
- <Compile Include="Editor\GodotSharpExport.cs" />
+ <Compile Include="IdentifierUtils.cs" />
+ <Compile Include="ProjectExtensions.cs" />
+ <Compile Include="ProjectGenerator.cs" />
+ <Compile Include="ProjectUtils.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\GodotTools.Core\GodotTools.Core.csproj">
+ <Project>{639E48BD-44E5-4091-8EDD-22D36DC0768D}</Project>
+ <Name>GodotTools.Core</Name>
+ </ProjectReference>
+ </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/modules/mono/editor/GodotSharpTools/Project/IdentifierUtils.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/IdentifierUtils.cs
index 83e2d2cf8d..f93eb9a1fa 100644
--- a/modules/mono/editor/GodotSharpTools/Project/IdentifierUtils.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/IdentifierUtils.cs
@@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Globalization;
using System.Text;
-namespace GodotSharpTools.Project
+namespace GodotTools.ProjectEditor
{
public static class IdentifierUtils
{
@@ -12,7 +12,7 @@ namespace GodotSharpTools.Project
if (string.IsNullOrEmpty(qualifiedIdentifier))
throw new ArgumentException($"{nameof(qualifiedIdentifier)} cannot be empty", nameof(qualifiedIdentifier));
- string[] identifiers = qualifiedIdentifier.Split(new[] { '.' });
+ string[] identifiers = qualifiedIdentifier.Split('.');
for (int i = 0; i < identifiers.Length; i++)
{
@@ -66,8 +66,6 @@ namespace GodotSharpTools.Project
if (identifierBuilder.Length > startIndex || @char == '_')
identifierBuilder.Append(@char);
break;
- default:
- break;
}
}
@@ -97,14 +95,14 @@ namespace GodotSharpTools.Project
}
else
{
- if (_doubleUnderscoreKeywords.Contains(value))
+ if (DoubleUnderscoreKeywords.Contains(value))
return true;
}
- return _keywords.Contains(value);
+ return Keywords.Contains(value);
}
- static HashSet<string> _doubleUnderscoreKeywords = new HashSet<string>
+ private static readonly HashSet<string> DoubleUnderscoreKeywords = new HashSet<string>
{
"__arglist",
"__makeref",
@@ -112,7 +110,7 @@ namespace GodotSharpTools.Project
"__refvalue",
};
- static HashSet<string> _keywords = new HashSet<string>
+ private static readonly HashSet<string> Keywords = new HashSet<string>
{
"as",
"do",
diff --git a/modules/mono/editor/GodotSharpTools/Project/ProjectExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs
index 647d9ac81d..36961eb45e 100644
--- a/modules/mono/editor/GodotSharpTools/Project/ProjectExtensions.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs
@@ -1,8 +1,9 @@
+using GodotTools.Core;
using System;
using DotNet.Globbing;
using Microsoft.Build.Construction;
-namespace GodotSharpTools.Project
+namespace GodotTools.ProjectEditor
{
public static class ProjectExtensions
{
diff --git a/modules/mono/editor/GodotSharpTools/Project/ProjectGenerator.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs
index f4ab11a222..4f21871f1a 100644
--- a/modules/mono/editor/GodotSharpTools/Project/ProjectGenerator.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectGenerator.cs
@@ -1,17 +1,19 @@
+using GodotTools.Core;
using System;
+using System.Collections.Generic;
using System.IO;
using Microsoft.Build.Construction;
-namespace GodotSharpTools.Project
+namespace GodotTools.ProjectEditor
{
public static class ProjectGenerator
{
- public const string CoreApiProjectName = "GodotSharp";
- public const string EditorApiProjectName = "GodotSharpEditor";
- const string CoreApiProjectGuid = "{AEBF0036-DA76-4341-B651-A3F2856AB2FA}";
- const string EditorApiProjectGuid = "{8FBEC238-D944-4074-8548-B3B524305905}";
+ private const string CoreApiProjectName = "GodotSharp";
+ private const string EditorApiProjectName = "GodotSharpEditor";
+ private const string CoreApiProjectGuid = "{AEBF0036-DA76-4341-B651-A3F2856AB2FA}";
+ private const string EditorApiProjectGuid = "{8FBEC238-D944-4074-8548-B3B524305905}";
- public static string GenCoreApiProject(string dir, string[] compileItems)
+ public static string GenCoreApiProject(string dir, IEnumerable<string> compileItems)
{
string path = Path.Combine(dir, CoreApiProjectName + ".csproj");
@@ -24,8 +26,8 @@ namespace GodotSharpTools.Project
mainGroup.SetProperty("BaseIntermediateOutputPath", "obj");
GenAssemblyInfoFile(root, dir, CoreApiProjectName,
- new string[] { "[assembly: InternalsVisibleTo(\"" + EditorApiProjectName + "\")]" },
- new string[] { "System.Runtime.CompilerServices" });
+ new[] {"[assembly: InternalsVisibleTo(\"" + EditorApiProjectName + "\")]"},
+ new[] {"System.Runtime.CompilerServices"});
foreach (var item in compileItems)
{
@@ -37,7 +39,7 @@ namespace GodotSharpTools.Project
return CoreApiProjectGuid;
}
- public static string GenEditorApiProject(string dir, string coreApiProjPath, string[] compileItems)
+ public static string GenEditorApiProject(string dir, string coreApiProjPath, IEnumerable<string> compileItems)
{
string path = Path.Combine(dir, EditorApiProjectName + ".csproj");
@@ -64,7 +66,7 @@ namespace GodotSharpTools.Project
return EditorApiProjectGuid;
}
- public static string GenGameProject(string dir, string name, string[] compileItems)
+ public static string GenGameProject(string dir, string name, IEnumerable<string> compileItems)
{
string path = Path.Combine(dir, name + ".csproj");
@@ -74,6 +76,8 @@ namespace GodotSharpTools.Project
mainGroup.SetProperty("OutputPath", Path.Combine(".mono", "temp", "bin", "$(Configuration)"));
mainGroup.SetProperty("BaseIntermediateOutputPath", Path.Combine(".mono", "temp", "obj"));
mainGroup.SetProperty("IntermediateOutputPath", Path.Combine("$(BaseIntermediateOutputPath)", "$(Configuration)"));
+ mainGroup.SetProperty("ApiConfiguration", "Debug").Condition = " '$(Configuration)' != 'Release' ";
+ mainGroup.SetProperty("ApiConfiguration", "Release").Condition = " '$(Configuration)' == 'Release' ";
var toolsGroup = root.AddPropertyGroup();
toolsGroup.Condition = " '$(Configuration)|$(Platform)' == 'Tools|AnyCPU' ";
@@ -86,12 +90,12 @@ namespace GodotSharpTools.Project
toolsGroup.AddProperty("ConsolePause", "false");
var coreApiRef = root.AddItem("Reference", CoreApiProjectName);
- coreApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", CoreApiProjectName + ".dll"));
+ coreApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", "$(ApiConfiguration)", CoreApiProjectName + ".dll"));
coreApiRef.AddMetadata("Private", "False");
var editorApiRef = root.AddItem("Reference", EditorApiProjectName);
editorApiRef.Condition = " '$(Configuration)' == 'Tools' ";
- editorApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", EditorApiProjectName + ".dll"));
+ editorApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", "$(ApiConfiguration)", EditorApiProjectName + ".dll"));
editorApiRef.AddMetadata("Private", "False");
GenAssemblyInfoFile(root, dir, name);
@@ -108,7 +112,6 @@ namespace GodotSharpTools.Project
public static void GenAssemblyInfoFile(ProjectRootElement root, string dir, string name, string[] assemblyLines = null, string[] usingDirectives = null)
{
-
string propertiesDir = Path.Combine(dir, "Properties");
if (!Directory.Exists(propertiesDir))
Directory.CreateDirectory(propertiesDir);
@@ -124,12 +127,9 @@ namespace GodotSharpTools.Project
string assemblyLinesText = string.Empty;
if (assemblyLines != null)
- {
- foreach (var assemblyLine in assemblyLines)
- assemblyLinesText += string.Join("\n", assemblyLines) + "\n";
- }
+ assemblyLinesText += string.Join("\n", assemblyLines) + "\n";
- string content = string.Format(assemblyInfoTemplate, usingDirectivesText, name, assemblyLinesText);
+ string content = string.Format(AssemblyInfoTemplate, usingDirectivesText, name, assemblyLinesText);
string assemblyInfoFile = Path.Combine(propertiesDir, "AssemblyInfo.cs");
@@ -194,8 +194,8 @@ namespace GodotSharpTools.Project
}
}
- private const string assemblyInfoTemplate =
-@"using System.Reflection;{0}
+ private const string AssemblyInfoTemplate =
+ @"using System.Reflection;{0}
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs
new file mode 100644
index 0000000000..1edc426e00
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs
@@ -0,0 +1,175 @@
+using GodotTools.Core;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using DotNet.Globbing;
+using Microsoft.Build.Construction;
+
+namespace GodotTools.ProjectEditor
+{
+ public static class ProjectUtils
+ {
+ public static void AddItemToProjectChecked(string projectPath, string itemType, string include)
+ {
+ var dir = Directory.GetParent(projectPath).FullName;
+ var root = ProjectRootElement.Open(projectPath);
+ Debug.Assert(root != null);
+
+ var normalizedInclude = include.RelativeToPath(dir).Replace("/", "\\");
+
+ if (root.AddItemChecked(itemType, normalizedInclude))
+ root.Save();
+ }
+
+ private static string[] GetAllFilesRecursive(string rootDirectory, string mask)
+ {
+ string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories);
+
+ // We want relative paths
+ for (int i = 0; i < files.Length; i++)
+ {
+ files[i] = files[i].RelativeToPath(rootDirectory);
+ }
+
+ return files;
+ }
+
+ public static string[] GetIncludeFiles(string projectPath, string itemType)
+ {
+ var result = new List<string>();
+ var existingFiles = GetAllFilesRecursive(Path.GetDirectoryName(projectPath), "*.cs");
+
+ var globOptions = new GlobOptions();
+ globOptions.Evaluation.CaseInsensitive = false;
+
+ var root = ProjectRootElement.Open(projectPath);
+
+ foreach (var itemGroup in root.ItemGroups)
+ {
+ if (itemGroup.Condition.Length != 0)
+ continue;
+
+ foreach (var item in itemGroup.Items)
+ {
+ if (item.ItemType != itemType)
+ continue;
+
+ string normalizedInclude = item.Include.NormalizePath();
+
+ var glob = Glob.Parse(normalizedInclude, globOptions);
+
+ // TODO Check somehow if path has no blob to avoid the following loop...
+
+ foreach (var existingFile in existingFiles)
+ {
+ if (glob.IsMatch(existingFile))
+ {
+ result.Add(existingFile);
+ }
+ }
+ }
+ }
+
+ return result.ToArray();
+ }
+
+ /// Simple function to make sure the Api assembly references are configured correctly
+ public static void FixApiHintPath(string projectPath)
+ {
+ var root = ProjectRootElement.Open(projectPath);
+ Debug.Assert(root != null);
+
+ bool dirty = false;
+
+ void AddPropertyIfNotPresent(string name, string condition, string value)
+ {
+ if (root.PropertyGroups
+ .Any(g => g.Condition == string.Empty || g.Condition == condition &&
+ g.Properties
+ .Any(p => p.Name == name &&
+ p.Value == value &&
+ (p.Condition == condition || g.Condition == condition))))
+ {
+ return;
+ }
+
+ root.AddProperty(name, value).Condition = condition;
+ dirty = true;
+ }
+
+ AddPropertyIfNotPresent(name: "ApiConfiguration",
+ condition: " '$(Configuration)' != 'Release' ",
+ value: "Debug");
+ AddPropertyIfNotPresent(name: "ApiConfiguration",
+ condition: " '$(Configuration)' == 'Release' ",
+ value: "Release");
+
+ void SetReferenceHintPath(string referenceName, string condition, string hintPath)
+ {
+ foreach (var itemGroup in root.ItemGroups.Where(g =>
+ g.Condition == string.Empty || g.Condition == condition))
+ {
+ var references = itemGroup.Items.Where(item =>
+ item.ItemType == "Reference" &&
+ item.Include == referenceName &&
+ (item.Condition == condition || itemGroup.Condition == condition));
+
+ var referencesWithHintPath = references.Where(reference =>
+ reference.Metadata.Any(m => m.Name == "HintPath"));
+
+ if (referencesWithHintPath.Any(reference => reference.Metadata
+ .Any(m => m.Name == "HintPath" && m.Value == hintPath)))
+ {
+ // Found a Reference item with the right HintPath
+ return;
+ }
+
+ var referenceWithHintPath = referencesWithHintPath.FirstOrDefault();
+ if (referenceWithHintPath != null)
+ {
+ // Found a Reference item with a wrong HintPath
+ foreach (var metadata in referenceWithHintPath.Metadata.ToList()
+ .Where(m => m.Name == "HintPath"))
+ {
+ // Safe to remove as we duplicate with ToList() to loop
+ referenceWithHintPath.RemoveChild(metadata);
+ }
+
+ referenceWithHintPath.AddMetadata("HintPath", hintPath);
+ dirty = true;
+ return;
+ }
+
+ var referenceWithoutHintPath = references.FirstOrDefault();
+ if (referenceWithoutHintPath != null)
+ {
+ // Found a Reference item without a HintPath
+ referenceWithoutHintPath.AddMetadata("HintPath", hintPath);
+ dirty = true;
+ return;
+ }
+ }
+
+ // Found no Reference item at all. Add it.
+ root.AddItem("Reference", referenceName).Condition = condition;
+ dirty = true;
+ }
+
+ const string coreProjectName = "GodotSharp";
+ const string editorProjectName = "GodotSharpEditor";
+
+ const string coreCondition = "";
+ const string editorCondition = " '$(Configuration)' == 'Tools' ";
+
+ var coreHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{coreProjectName}.dll";
+ var editorHintPath = $"$(ProjectDir)/.mono/assemblies/$(ApiConfiguration)/{editorProjectName}.dll";
+
+ SetReferenceHintPath(coreProjectName, coreCondition, coreHintPath);
+ SetReferenceHintPath(editorProjectName, editorCondition, editorHintPath);
+
+ if (dirty)
+ root.Save();
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotSharpTools/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/Properties/AssemblyInfo.cs
index 7115d8fc71..09333850fc 100644
--- a/modules/mono/editor/GodotSharpTools/Properties/AssemblyInfo.cs
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/Properties/AssemblyInfo.cs
@@ -4,12 +4,12 @@ using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
-[assembly: AssemblyTitle("GodotSharpTools")]
+[assembly: AssemblyTitle("GodotTools.ProjectEditor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
-[assembly: AssemblyCopyright("ignacio")]
+[assembly: AssemblyCopyright("Godot Engine contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
diff --git a/modules/mono/editor/GodotSharpTools/packages.config b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/packages.config
index 2c7cb0bd4b..13915000e4 100644
--- a/modules/mono/editor/GodotSharpTools/packages.config
+++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/packages.config
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DotNet.Glob" version="2.1.1" targetFramework="net45" />
</packages> \ No newline at end of file
diff --git a/modules/mono/editor/GodotTools/GodotTools.sln b/modules/mono/editor/GodotTools/GodotTools.sln
new file mode 100644
index 0000000000..6f7d44bec2
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools.sln
@@ -0,0 +1,35 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 2012
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.ProjectEditor", "GodotTools.ProjectEditor\GodotTools.ProjectEditor.csproj", "{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools", "GodotTools\GodotTools.csproj", "{27B00618-A6F2-4828-B922-05CAEB08C286}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.Core", "GodotTools.Core\GodotTools.Core.csproj", "{639E48BD-44E5-4091-8EDD-22D36DC0768D}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodotTools.BuildLogger", "GodotTools.BuildLogger\GodotTools.BuildLogger.csproj", "{6CE9A984-37B1-4F8A-8FE9-609F05F071B3}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}.Release|Any CPU.Build.0 = Release|Any CPU
+ {27B00618-A6F2-4828-B922-05CAEB08C286}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {27B00618-A6F2-4828-B922-05CAEB08C286}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {27B00618-A6F2-4828-B922-05CAEB08C286}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {27B00618-A6F2-4828-B922-05CAEB08C286}.Release|Any CPU.Build.0 = Release|Any CPU
+ {639E48BD-44E5-4091-8EDD-22D36DC0768D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {639E48BD-44E5-4091-8EDD-22D36DC0768D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {639E48BD-44E5-4091-8EDD-22D36DC0768D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {639E48BD-44E5-4091-8EDD-22D36DC0768D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {6CE9A984-37B1-4F8A-8FE9-609F05F071B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {6CE9A984-37B1-4F8A-8FE9-609F05F071B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {6CE9A984-37B1-4F8A-8FE9-609F05F071B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {6CE9A984-37B1-4F8A-8FE9-609F05F071B3}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+EndGlobal
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs
new file mode 100644
index 0000000000..f849356919
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildSystem.cs
@@ -0,0 +1,172 @@
+using GodotTools.Core;
+using System;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.Diagnostics;
+using System.IO;
+using System.Threading.Tasks;
+using GodotTools.BuildLogger;
+using GodotTools.Internals;
+using GodotTools.Utils;
+using Directory = System.IO.Directory;
+
+namespace GodotTools.Build
+{
+ public static class BuildSystem
+ {
+ private static string GetMsBuildPath()
+ {
+ string msbuildPath = MsBuildFinder.FindMsBuild();
+
+ if (msbuildPath == null)
+ throw new FileNotFoundException("Cannot find the MSBuild executable.");
+
+ return msbuildPath;
+ }
+
+ private static string MonoWindowsBinDir
+ {
+ get
+ {
+ string monoWinBinDir = Path.Combine(Internal.MonoWindowsInstallRoot, "bin");
+
+ if (!Directory.Exists(monoWinBinDir))
+ throw new FileNotFoundException("Cannot find the Windows Mono install bin directory.");
+
+ return monoWinBinDir;
+ }
+ }
+
+ private static Godot.EditorSettings EditorSettings =>
+ GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
+
+ private static bool UsingMonoMsBuildOnWindows
+ {
+ get
+ {
+ if (OS.IsWindows())
+ {
+ return (GodotSharpBuilds.BuildTool) EditorSettings.GetSetting("mono/builds/build_tool")
+ == GodotSharpBuilds.BuildTool.MsBuildMono;
+ }
+
+ return false;
+ }
+ }
+
+ private static bool PrintBuildOutput =>
+ (bool) EditorSettings.GetSetting("mono/builds/print_build_output");
+
+ private static Process LaunchBuild(string solution, string config, string loggerOutputDir, IEnumerable<string> customProperties = null)
+ {
+ var customPropertiesList = new List<string>();
+
+ if (customProperties != null)
+ customPropertiesList.AddRange(customProperties);
+
+ string compilerArgs = BuildArguments(solution, config, loggerOutputDir, customPropertiesList);
+
+ var startInfo = new ProcessStartInfo(GetMsBuildPath(), compilerArgs);
+
+ bool redirectOutput = !IsDebugMsBuildRequested() && !PrintBuildOutput;
+
+ if (!redirectOutput || Godot.OS.IsStdoutVerbose())
+ Console.WriteLine($"Running: \"{startInfo.FileName}\" {startInfo.Arguments}");
+
+ startInfo.RedirectStandardOutput = redirectOutput;
+ startInfo.RedirectStandardError = redirectOutput;
+ startInfo.UseShellExecute = false;
+
+ if (UsingMonoMsBuildOnWindows)
+ {
+ // These environment variables are required for Mono's MSBuild to find the compilers.
+ // We use the batch files in Mono's bin directory to make sure the compilers are executed with mono.
+ string monoWinBinDir = MonoWindowsBinDir;
+ startInfo.EnvironmentVariables.Add("CscToolExe", Path.Combine(monoWinBinDir, "csc.bat"));
+ startInfo.EnvironmentVariables.Add("VbcToolExe", Path.Combine(monoWinBinDir, "vbc.bat"));
+ startInfo.EnvironmentVariables.Add("FscToolExe", Path.Combine(monoWinBinDir, "fsharpc.bat"));
+ }
+
+ // Needed when running from Developer Command Prompt for VS
+ RemovePlatformVariable(startInfo.EnvironmentVariables);
+
+ var process = new Process {StartInfo = startInfo};
+
+ process.Start();
+
+ if (redirectOutput)
+ {
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+ }
+
+ return process;
+ }
+
+ public static int Build(MonoBuildInfo monoBuildInfo)
+ {
+ return Build(monoBuildInfo.Solution, monoBuildInfo.Configuration,
+ monoBuildInfo.LogsDirPath, monoBuildInfo.CustomProperties);
+ }
+
+ public static async Task<int> BuildAsync(MonoBuildInfo monoBuildInfo)
+ {
+ return await BuildAsync(monoBuildInfo.Solution, monoBuildInfo.Configuration,
+ monoBuildInfo.LogsDirPath, monoBuildInfo.CustomProperties);
+ }
+
+ public static int Build(string solution, string config, string loggerOutputDir, IEnumerable<string> customProperties = null)
+ {
+ using (var process = LaunchBuild(solution, config, loggerOutputDir, customProperties))
+ {
+ process.WaitForExit();
+
+ return process.ExitCode;
+ }
+ }
+
+ public static async Task<int> BuildAsync(string solution, string config, string loggerOutputDir, IEnumerable<string> customProperties = null)
+ {
+ using (var process = LaunchBuild(solution, config, loggerOutputDir, customProperties))
+ {
+ await process.WaitForExitAsync();
+
+ return process.ExitCode;
+ }
+ }
+
+ private static string BuildArguments(string solution, string config, string loggerOutputDir, List<string> customProperties)
+ {
+ string arguments = $@"""{solution}"" /v:normal /t:Rebuild ""/p:{"Configuration=" + config}"" " +
+ $@"""/l:{typeof(GodotBuildLogger).FullName},{GodotBuildLogger.AssemblyPath};{loggerOutputDir}""";
+
+ foreach (string customProperty in customProperties)
+ {
+ arguments += " /p:" + customProperty;
+ }
+
+ return arguments;
+ }
+
+ private static void RemovePlatformVariable(StringDictionary environmentVariables)
+ {
+ // EnvironmentVariables is case sensitive? Seriously?
+
+ var platformEnvironmentVariables = new List<string>();
+
+ foreach (string env in environmentVariables.Keys)
+ {
+ if (env.ToUpper() == "PLATFORM")
+ platformEnvironmentVariables.Add(env);
+ }
+
+ foreach (string env in platformEnvironmentVariables)
+ environmentVariables.Remove(env);
+ }
+
+ private static bool IsDebugMsBuildRequested()
+ {
+ return Environment.GetEnvironmentVariable("GODOT_DEBUG_MSBUILD")?.Trim() == "1";
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs b/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs
new file mode 100644
index 0000000000..f0068385f4
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Build/MsBuildFinder.cs
@@ -0,0 +1,210 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using Godot;
+using GodotTools.Internals;
+using Directory = System.IO.Directory;
+using Environment = System.Environment;
+using File = System.IO.File;
+using Path = System.IO.Path;
+using OS = GodotTools.Utils.OS;
+
+namespace GodotTools.Build
+{
+ public static class MsBuildFinder
+ {
+ private static string _msbuildToolsPath = string.Empty;
+ private static string _msbuildUnixPath = string.Empty;
+ private static string _xbuildUnixPath = string.Empty;
+
+ public static string FindMsBuild()
+ {
+ var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
+ var buildTool = (GodotSharpBuilds.BuildTool) editorSettings.GetSetting("mono/builds/build_tool");
+
+ if (OS.IsWindows())
+ {
+ switch (buildTool)
+ {
+ case GodotSharpBuilds.BuildTool.MsBuildVs:
+ {
+ if (_msbuildToolsPath.Empty() || !File.Exists(_msbuildToolsPath))
+ {
+ // Try to search it again if it wasn't found last time or if it was removed from its location
+ _msbuildToolsPath = FindMsBuildToolsPathOnWindows();
+
+ if (_msbuildToolsPath.Empty())
+ {
+ throw new FileNotFoundException($"Cannot find executable for '{GodotSharpBuilds.PropNameMsbuildVs}'. Tried with path: {_msbuildToolsPath}");
+ }
+ }
+
+ if (!_msbuildToolsPath.EndsWith("\\"))
+ _msbuildToolsPath += "\\";
+
+ return Path.Combine(_msbuildToolsPath, "MSBuild.exe");
+ }
+
+ case GodotSharpBuilds.BuildTool.MsBuildMono:
+ {
+ string msbuildPath = Path.Combine(Internal.MonoWindowsInstallRoot, "bin", "msbuild.bat");
+
+ if (!File.Exists(msbuildPath))
+ {
+ throw new FileNotFoundException($"Cannot find executable for '{GodotSharpBuilds.PropNameMsbuildMono}'. Tried with path: {msbuildPath}");
+ }
+
+ return msbuildPath;
+ }
+
+ case GodotSharpBuilds.BuildTool.XBuild:
+ {
+ string xbuildPath = Path.Combine(Internal.MonoWindowsInstallRoot, "bin", "xbuild.bat");
+
+ if (!File.Exists(xbuildPath))
+ {
+ throw new FileNotFoundException($"Cannot find executable for '{GodotSharpBuilds.PropNameXbuild}'. Tried with path: {xbuildPath}");
+ }
+
+ return xbuildPath;
+ }
+
+ default:
+ throw new IndexOutOfRangeException("Invalid build tool in editor settings");
+ }
+ }
+
+ if (OS.IsUnix())
+ {
+ if (buildTool == GodotSharpBuilds.BuildTool.XBuild)
+ {
+ if (_xbuildUnixPath.Empty() || !File.Exists(_xbuildUnixPath))
+ {
+ // Try to search it again if it wasn't found last time or if it was removed from its location
+ _xbuildUnixPath = FindBuildEngineOnUnix("msbuild");
+ }
+
+ if (_xbuildUnixPath.Empty())
+ {
+ throw new FileNotFoundException($"Cannot find binary for '{GodotSharpBuilds.PropNameXbuild}'");
+ }
+ }
+ else
+ {
+ if (_msbuildUnixPath.Empty() || !File.Exists(_msbuildUnixPath))
+ {
+ // Try to search it again if it wasn't found last time or if it was removed from its location
+ _msbuildUnixPath = FindBuildEngineOnUnix("msbuild");
+ }
+
+ if (_msbuildUnixPath.Empty())
+ {
+ throw new FileNotFoundException($"Cannot find binary for '{GodotSharpBuilds.PropNameMsbuildMono}'");
+ }
+ }
+
+ return buildTool != GodotSharpBuilds.BuildTool.XBuild ? _msbuildUnixPath : _xbuildUnixPath;
+ }
+
+ throw new PlatformNotSupportedException();
+ }
+
+ private static IEnumerable<string> MsBuildHintDirs
+ {
+ get
+ {
+ var result = new List<string>();
+
+ if (OS.IsOSX())
+ {
+ result.Add("/Library/Frameworks/Mono.framework/Versions/Current/bin/");
+ result.Add("/usr/local/var/homebrew/linked/mono/bin/");
+ }
+
+ result.Add("/opt/novell/mono/bin/");
+
+ return result;
+ }
+ }
+
+ private static string FindBuildEngineOnUnix(string name)
+ {
+ string ret = OS.PathWhich(name);
+
+ if (!ret.Empty())
+ return ret;
+
+ string retFallback = OS.PathWhich($"{name}.exe");
+
+ if (!retFallback.Empty())
+ return retFallback;
+
+ foreach (string hintDir in MsBuildHintDirs)
+ {
+ string hintPath = Path.Combine(hintDir, name);
+
+ if (File.Exists(hintPath))
+ return hintPath;
+ }
+
+ return string.Empty;
+ }
+
+ private static string FindMsBuildToolsPathOnWindows()
+ {
+ if (!OS.IsWindows())
+ throw new PlatformNotSupportedException();
+
+ // Try to find 15.0 with vswhere
+
+ string vsWherePath = Environment.GetEnvironmentVariable(Internal.GodotIs32Bits() ? "ProgramFiles" : "ProgramFiles(x86)");
+ vsWherePath += "\\Microsoft Visual Studio\\Installer\\vswhere.exe";
+
+ var vsWhereArgs = new[] {"-latest", "-products", "*", "-requires", "Microsoft.Component.MSBuild"};
+
+ var outputArray = new Godot.Collections.Array<string>();
+ int exitCode = Godot.OS.Execute(vsWherePath, vsWhereArgs,
+ blocking: true, output: (Godot.Collections.Array) outputArray);
+
+ if (exitCode == 0)
+ return string.Empty;
+
+ if (outputArray.Count == 0)
+ return string.Empty;
+
+ var lines = outputArray[0].Split('\n');
+
+ foreach (string line in lines)
+ {
+ int sepIdx = line.IndexOf(':');
+
+ if (sepIdx <= 0)
+ continue;
+
+ string key = line.Substring(0, sepIdx); // No need to trim
+
+ if (key != "installationPath")
+ continue;
+
+ string value = line.Substring(sepIdx + 1).StripEdges();
+
+ if (value.Empty())
+ throw new FormatException("installationPath value is empty");
+
+ if (!value.EndsWith("\\"))
+ value += "\\";
+
+ // Since VS2019, the directory is simply named "Current"
+ string msbuildDir = Path.Combine(value, "MSBuild\\Current\\Bin");
+
+ if (Directory.Exists(msbuildDir))
+ return msbuildDir;
+
+ // Directory name "15.0" is used in VS 2017
+ return Path.Combine(value, "MSBuild\\15.0\\Bin");
+ }
+
+ return string.Empty;
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/CSharpProject.cs b/modules/mono/editor/GodotTools/GodotTools/CSharpProject.cs
new file mode 100644
index 0000000000..4535ed7247
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/CSharpProject.cs
@@ -0,0 +1,127 @@
+using Godot;
+using System;
+using Godot.Collections;
+using GodotTools.Internals;
+using GodotTools.ProjectEditor;
+using static GodotTools.Internals.Globals;
+using File = GodotTools.Utils.File;
+using Directory = GodotTools.Utils.Directory;
+
+namespace GodotTools
+{
+ public static class CSharpProject
+ {
+ public static string GenerateGameProject(string dir, string name)
+ {
+ try
+ {
+ return ProjectGenerator.GenGameProject(dir, name, compileItems: new string[] { });
+ }
+ catch (Exception e)
+ {
+ GD.PushError(e.ToString());
+ return string.Empty;
+ }
+ }
+
+ public static void AddItem(string projectPath, string itemType, string include)
+ {
+ if (!(bool) GlobalDef("mono/project/auto_update_project", true))
+ return;
+
+ ProjectUtils.AddItemToProjectChecked(projectPath, itemType, include);
+ }
+
+ public static void FixApiHintPath(string projectPath)
+ {
+ try
+ {
+ ProjectUtils.FixApiHintPath(projectPath);
+ }
+ catch (Exception e)
+ {
+ GD.PushError(e.ToString());
+ }
+ }
+
+ private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+
+ private static ulong ConvertToTimestamp(this DateTime value)
+ {
+ TimeSpan elapsedTime = value - Epoch;
+ return (ulong) elapsedTime.TotalSeconds;
+ }
+
+ public static void GenerateScriptsMetadata(string projectPath, string outputPath)
+ {
+ if (File.Exists(outputPath))
+ File.Delete(outputPath);
+
+ var oldDict = Internal.GetScriptsMetadataOrNothing();
+ var newDict = new Godot.Collections.Dictionary<string, object>();
+
+ foreach (var includeFile in ProjectUtils.GetIncludeFiles(projectPath, "Compile"))
+ {
+ string projectIncludeFile = ("res://" + includeFile).SimplifyGodotPath();
+
+ ulong modifiedTime = File.GetLastWriteTime(projectIncludeFile).ConvertToTimestamp();
+
+ if (oldDict.TryGetValue(projectIncludeFile, out var oldFileVar))
+ {
+ var oldFileDict = (Dictionary) oldFileVar;
+
+ if (ulong.TryParse(oldFileDict["modified_time"] as string, out ulong storedModifiedTime))
+ {
+ if (storedModifiedTime == modifiedTime)
+ {
+ // No changes so no need to parse again
+ newDict[projectIncludeFile] = oldFileDict;
+ continue;
+ }
+ }
+ }
+
+ ScriptClassParser.ParseFileOrThrow(projectIncludeFile, out var classes);
+
+ string searchName = System.IO.Path.GetFileNameWithoutExtension(projectIncludeFile);
+
+ var classDict = new Dictionary();
+
+ foreach (var classDecl in classes)
+ {
+ if (classDecl.BaseCount == 0)
+ continue; // Does not inherit nor implement anything, so it can't be a script class
+
+ string classCmp = classDecl.Nested ?
+ classDecl.Name.Substring(classDecl.Name.LastIndexOf(".", StringComparison.Ordinal) + 1) :
+ classDecl.Name;
+
+ if (classCmp != searchName)
+ continue;
+
+ classDict["namespace"] = classDecl.Namespace;
+ classDict["class_name"] = classDecl.Name;
+ classDict["nested"] = classDecl.Nested;
+ break;
+ }
+
+ if (classDict.Count == 0)
+ continue; // Not found
+
+ newDict[projectIncludeFile] = new Dictionary {["modified_time"] = $"{modifiedTime}", ["class"] = classDict};
+ }
+
+ if (newDict.Count > 0)
+ {
+ string json = JSON.Print(newDict);
+
+ string baseDir = outputPath.GetBaseDir();
+
+ if (!Directory.Exists(baseDir))
+ Directory.CreateDirectory(baseDir);
+
+ File.WriteAllText(outputPath, json);
+ }
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpBuilds.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpBuilds.cs
new file mode 100644
index 0000000000..a884b0ead0
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpBuilds.cs
@@ -0,0 +1,277 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Threading.Tasks;
+using GodotTools.Build;
+using GodotTools.Internals;
+using GodotTools.Utils;
+using static GodotTools.Internals.Globals;
+using Error = Godot.Error;
+using File = GodotTools.Utils.File;
+using Directory = GodotTools.Utils.Directory;
+
+namespace GodotTools
+{
+ public static class GodotSharpBuilds
+ {
+ private static readonly List<MonoBuildInfo> BuildsInProgress = new List<MonoBuildInfo>();
+
+ public const string PropNameMsbuildMono = "MSBuild (Mono)";
+ public const string PropNameMsbuildVs = "MSBuild (VS Build Tools)";
+ public const string PropNameXbuild = "xbuild (Deprecated)";
+
+ public const string MsBuildIssuesFileName = "msbuild_issues.csv";
+ public const string MsBuildLogFileName = "msbuild_log.txt";
+
+ public enum BuildTool
+ {
+ MsBuildMono,
+ MsBuildVs,
+ XBuild // Deprecated
+ }
+
+ private static void RemoveOldIssuesFile(MonoBuildInfo buildInfo)
+ {
+ var issuesFile = GetIssuesFilePath(buildInfo);
+
+ if (!File.Exists(issuesFile))
+ return;
+
+ File.Delete(issuesFile);
+ }
+
+ private static string _ApiFolderName(ApiAssemblyType apiType)
+ {
+ ulong apiHash = apiType == ApiAssemblyType.Core ?
+ Internal.GetCoreApiHash() :
+ Internal.GetEditorApiHash();
+ return $"{apiHash}_{BindingsGenerator.Version}_{BindingsGenerator.CsGlueVersion}";
+ }
+
+ private static void ShowBuildErrorDialog(string message)
+ {
+ GodotSharpEditor.Instance.ShowErrorDialog(message, "Build error");
+ GodotSharpEditor.Instance.MonoBottomPanel.ShowBuildTab();
+ }
+
+ public static void RestartBuild(MonoBuildTab buildTab) => throw new NotImplementedException();
+ public static void StopBuild(MonoBuildTab buildTab) => throw new NotImplementedException();
+
+ private static string GetLogFilePath(MonoBuildInfo buildInfo)
+ {
+ return Path.Combine(buildInfo.LogsDirPath, MsBuildLogFileName);
+ }
+
+ private static string GetIssuesFilePath(MonoBuildInfo buildInfo)
+ {
+ return Path.Combine(Godot.ProjectSettings.LocalizePath(buildInfo.LogsDirPath), MsBuildIssuesFileName);
+ }
+
+ private static void PrintVerbose(string text)
+ {
+ if (Godot.OS.IsStdoutVerbose())
+ Godot.GD.Print(text);
+ }
+
+ public static bool Build(MonoBuildInfo buildInfo)
+ {
+ if (BuildsInProgress.Contains(buildInfo))
+ throw new InvalidOperationException("A build is already in progress");
+
+ BuildsInProgress.Add(buildInfo);
+
+ try
+ {
+ MonoBuildTab buildTab = GodotSharpEditor.Instance.MonoBottomPanel.GetBuildTabFor(buildInfo);
+ buildTab.OnBuildStart();
+
+ // Required in order to update the build tasks list
+ Internal.GodotMainIteration();
+
+ try
+ {
+ RemoveOldIssuesFile(buildInfo);
+ }
+ catch (IOException e)
+ {
+ buildTab.OnBuildExecFailed($"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}");
+ Console.Error.WriteLine(e);
+ }
+
+ try
+ {
+ int exitCode = BuildSystem.Build(buildInfo);
+
+ if (exitCode != 0)
+ PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}");
+
+ buildTab.OnBuildExit(exitCode == 0 ? MonoBuildTab.BuildResults.Success : MonoBuildTab.BuildResults.Error);
+
+ return exitCode == 0;
+ }
+ catch (Exception e)
+ {
+ buildTab.OnBuildExecFailed($"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}");
+ Console.Error.WriteLine(e);
+ return false;
+ }
+ }
+ finally
+ {
+ BuildsInProgress.Remove(buildInfo);
+ }
+ }
+
+ public static async Task<bool> BuildAsync(MonoBuildInfo buildInfo)
+ {
+ if (BuildsInProgress.Contains(buildInfo))
+ throw new InvalidOperationException("A build is already in progress");
+
+ BuildsInProgress.Add(buildInfo);
+
+ try
+ {
+ MonoBuildTab buildTab = GodotSharpEditor.Instance.MonoBottomPanel.GetBuildTabFor(buildInfo);
+
+ try
+ {
+ RemoveOldIssuesFile(buildInfo);
+ }
+ catch (IOException e)
+ {
+ buildTab.OnBuildExecFailed($"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}");
+ Console.Error.WriteLine(e);
+ }
+
+ try
+ {
+ int exitCode = await BuildSystem.BuildAsync(buildInfo);
+
+ if (exitCode != 0)
+ PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}");
+
+ buildTab.OnBuildExit(exitCode == 0 ? MonoBuildTab.BuildResults.Success : MonoBuildTab.BuildResults.Error);
+
+ return exitCode == 0;
+ }
+ catch (Exception e)
+ {
+ buildTab.OnBuildExecFailed($"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}");
+ Console.Error.WriteLine(e);
+ return false;
+ }
+ }
+ finally
+ {
+ BuildsInProgress.Remove(buildInfo);
+ }
+ }
+
+ public static bool BuildApiSolution(string apiSlnDir, string config)
+ {
+ string apiSlnFile = Path.Combine(apiSlnDir, $"{ApiAssemblyNames.SolutionName}.sln");
+
+ string coreApiAssemblyDir = Path.Combine(apiSlnDir, ApiAssemblyNames.Core, "bin", config);
+ string coreApiAssemblyFile = Path.Combine(coreApiAssemblyDir, $"{ApiAssemblyNames.Core}.dll");
+
+ string editorApiAssemblyDir = Path.Combine(apiSlnDir, ApiAssemblyNames.Editor, "bin", config);
+ string editorApiAssemblyFile = Path.Combine(editorApiAssemblyDir, $"{ApiAssemblyNames.Editor}.dll");
+
+ if (File.Exists(coreApiAssemblyFile) && File.Exists(editorApiAssemblyFile))
+ return true; // The assemblies are in the output folder; assume the solution is already built
+
+ var apiBuildInfo = new MonoBuildInfo(apiSlnFile, config);
+
+ // TODO Replace this global NoWarn with '#pragma warning' directives on generated files,
+ // once we start to actively document manually maintained C# classes
+ apiBuildInfo.CustomProperties.Add("NoWarn=1591"); // Ignore missing documentation warnings
+
+ if (Build(apiBuildInfo))
+ return true;
+
+ ShowBuildErrorDialog($"Failed to build {ApiAssemblyNames.SolutionName} solution.");
+ return false;
+ }
+
+ public static bool BuildProjectBlocking(string config, IEnumerable<string> godotDefines)
+ {
+ if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
+ return true; // No solution to build
+
+ // Make sure to update the API assemblies if they happen to be missing. Just in
+ // case the user decided to delete them at some point after they were loaded.
+ Internal.UpdateApiAssembliesFromPrebuilt();
+
+ using (var pr = new EditorProgress("mono_project_debug_build", "Building project solution...", 1))
+ {
+ pr.Step("Building project solution", 0);
+
+ var buildInfo = new MonoBuildInfo(GodotSharpDirs.ProjectSlnPath, config);
+
+ // Add Godot defines
+ string constants = OS.IsWindows() ? "GodotDefineConstants=\"" : "GodotDefineConstants=\\\"";
+
+ foreach (var godotDefine in godotDefines)
+ constants += $"GODOT_{godotDefine.ToUpper().Replace("-", "_").Replace(" ", "_").Replace(";", "_")};";
+
+ if (Internal.GodotIsRealTDouble())
+ constants += "GODOT_REAL_T_IS_DOUBLE;";
+
+ constants += OS.IsWindows() ? "\"" : "\\\"";
+
+ buildInfo.CustomProperties.Add(constants);
+
+ if (!Build(buildInfo))
+ {
+ ShowBuildErrorDialog("Failed to build project solution");
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public static bool EditorBuildCallback()
+ {
+ if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
+ return true; // No solution to build
+
+ string editorScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor");
+ string playerScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor_player");
+
+ CSharpProject.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, editorScriptsMetadataPath);
+
+ if (File.Exists(editorScriptsMetadataPath))
+ File.Copy(editorScriptsMetadataPath, playerScriptsMetadataPath);
+
+ var godotDefines = new[]
+ {
+ Godot.OS.GetName(),
+ Internal.GodotIs32Bits() ? "32" : "64"
+ };
+
+ return BuildProjectBlocking("Tools", godotDefines);
+ }
+
+ public static void Initialize()
+ {
+ // Build tool settings
+
+ EditorDef("mono/builds/build_tool", OS.IsWindows() ? BuildTool.MsBuildVs : BuildTool.MsBuildMono);
+
+ var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings();
+
+ editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary
+ {
+ ["type"] = Godot.Variant.Type.Int,
+ ["name"] = "mono/builds/build_tool",
+ ["hint"] = Godot.PropertyHint.Enum,
+ ["hint_string"] = OS.IsWindows() ?
+ $"{PropNameMsbuildMono},{PropNameMsbuildVs},{PropNameXbuild}" :
+ $"{PropNameMsbuildMono},{PropNameXbuild}"
+ });
+
+ EditorDef("mono/builds/print_build_output", false);
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
new file mode 100644
index 0000000000..90dec43412
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs
@@ -0,0 +1,491 @@
+using Godot;
+using GodotTools.Utils;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using GodotTools.Internals;
+using GodotTools.ProjectEditor;
+using static GodotTools.Internals.Globals;
+using File = GodotTools.Utils.File;
+using Path = System.IO.Path;
+using OS = GodotTools.Utils.OS;
+
+namespace GodotTools
+{
+ public class GodotSharpEditor : EditorPlugin, ISerializationListener
+ {
+ private EditorSettings editorSettings;
+
+ private PopupMenu menuPopup;
+
+ private AcceptDialog errorDialog;
+ private AcceptDialog aboutDialog;
+ private CheckBox aboutDialogCheckBox;
+
+ private ToolButton bottomPanelBtn;
+
+ private MonoDevelopInstance monoDevelopInstance;
+ private MonoDevelopInstance visualStudioForMacInstance;
+
+ private WeakRef exportPluginWeak; // TODO Use WeakReference once we have proper serialization
+
+ public MonoBottomPanel MonoBottomPanel { get; private set; }
+
+ private bool CreateProjectSolution()
+ {
+ using (var pr = new EditorProgress("create_csharp_solution", "Generating solution...".TTR(), 2))
+ {
+ pr.Step("Generating C# project...".TTR());
+
+ string resourceDir = ProjectSettings.GlobalizePath("res://");
+
+ string path = resourceDir;
+ string name = (string) ProjectSettings.GetSetting("application/config/name");
+ if (name.Empty())
+ name = "UnnamedProject";
+
+ string guid = CSharpProject.GenerateGameProject(path, name);
+
+ if (guid.Length > 0)
+ {
+ var solution = new DotNetSolution(name)
+ {
+ DirectoryPath = path
+ };
+
+ var projectInfo = new DotNetSolution.ProjectInfo
+ {
+ Guid = guid,
+ PathRelativeToSolution = name + ".csproj",
+ Configs = new List<string> {"Debug", "Release", "Tools"}
+ };
+
+ solution.AddNewProject(name, projectInfo);
+
+ try
+ {
+ solution.Save();
+ }
+ catch (IOException e)
+ {
+ ShowErrorDialog("Failed to save solution. Exception message: ".TTR() + e.Message);
+ return false;
+ }
+
+ // Make sure to update the API assemblies if they happen to be missing. Just in
+ // case the user decided to delete them at some point after they were loaded.
+ Internal.UpdateApiAssembliesFromPrebuilt();
+
+ pr.Step("Done".TTR());
+
+ // Here, after all calls to progress_task_step
+ CallDeferred(nameof(_RemoveCreateSlnMenuOption));
+ }
+ else
+ {
+ ShowErrorDialog("Failed to create C# project.".TTR());
+ }
+
+ return true;
+ }
+ }
+
+ private void _RemoveCreateSlnMenuOption()
+ {
+ menuPopup.RemoveItem(menuPopup.GetItemIndex((int) MenuOptions.CreateSln));
+ bottomPanelBtn.Show();
+ }
+
+ private void _ShowAboutDialog()
+ {
+ bool showOnStart = (bool) editorSettings.GetSetting("mono/editor/show_info_on_start");
+ aboutDialogCheckBox.Pressed = showOnStart;
+ aboutDialog.PopupCenteredMinsize();
+ }
+
+ private void _ToggleAboutDialogOnStart(bool enabled)
+ {
+ bool showOnStart = (bool) editorSettings.GetSetting("mono/editor/show_info_on_start");
+ if (showOnStart != enabled)
+ editorSettings.SetSetting("mono/editor/show_info_on_start", enabled);
+ }
+
+ private void _MenuOptionPressed(MenuOptions id)
+ {
+ switch (id)
+ {
+ case MenuOptions.CreateSln:
+ CreateProjectSolution();
+ break;
+ case MenuOptions.AboutCSharp:
+ _ShowAboutDialog();
+ break;
+ default:
+ throw new ArgumentOutOfRangeException(nameof(id), id, "Invalid menu option");
+ }
+ }
+
+ private void _BuildSolutionPressed()
+ {
+ if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
+ {
+ if (!CreateProjectSolution())
+ return; // Failed to create solution
+ }
+
+ Instance.MonoBottomPanel.BuildProjectPressed();
+ }
+
+ public override void _Notification(int what)
+ {
+ base._Notification(what);
+
+ if (what == NotificationReady)
+ {
+ bool showInfoDialog = (bool) editorSettings.GetSetting("mono/editor/show_info_on_start");
+ if (showInfoDialog)
+ {
+ aboutDialog.PopupExclusive = true;
+ _ShowAboutDialog();
+ // Once shown a first time, it can be seen again via the Mono menu - it doesn't have to be exclusive from that time on.
+ aboutDialog.PopupExclusive = false;
+ }
+ }
+ }
+
+ public enum MenuOptions
+ {
+ CreateSln,
+ AboutCSharp,
+ }
+
+ public enum ExternalEditor
+ {
+ None,
+ VisualStudio, // TODO (Windows-only)
+ VisualStudioForMac, // Mac-only
+ MonoDevelop,
+ VsCode
+ }
+
+ public void ShowErrorDialog(string message, string title = "Error")
+ {
+ errorDialog.WindowTitle = title;
+ errorDialog.DialogText = message;
+ errorDialog.PopupCenteredMinsize();
+ }
+
+ private static string _vsCodePath = string.Empty;
+
+ private static readonly string[] VsCodeNames =
+ {
+ "code", "code-oss", "vscode", "vscode-oss", "visual-studio-code", "visual-studio-code-oss"
+ };
+
+ public Error OpenInExternalEditor(Script script, int line, int col)
+ {
+ var editor = (ExternalEditor) editorSettings.GetSetting("mono/editor/external_editor");
+
+ switch (editor)
+ {
+ case ExternalEditor.VsCode:
+ {
+ if (_vsCodePath.Empty() || !File.Exists(_vsCodePath))
+ {
+ // Try to search it again if it wasn't found last time or if it was removed from its location
+ _vsCodePath = VsCodeNames.SelectFirstNotNull(OS.PathWhich, orElse: string.Empty);
+ }
+
+ var args = new List<string>();
+
+ bool osxAppBundleInstalled = false;
+
+ if (OS.IsOSX())
+ {
+ // The package path is '/Applications/Visual Studio Code.app'
+ const string vscodeBundleId = "com.microsoft.VSCode";
+
+ osxAppBundleInstalled = Internal.IsOsxAppBundleInstalled(vscodeBundleId);
+
+ if (osxAppBundleInstalled)
+ {
+ args.Add("-b");
+ args.Add(vscodeBundleId);
+
+ // The reusing of existing windows made by the 'open' command might not choose a wubdiw that is
+ // editing our folder. It's better to ask for a new window and let VSCode do the window management.
+ args.Add("-n");
+
+ // The open process must wait until the application finishes (which is instant in VSCode's case)
+ args.Add("--wait-apps");
+
+ args.Add("--args");
+ }
+ }
+
+ var resourcePath = ProjectSettings.GlobalizePath("res://");
+ args.Add(resourcePath);
+
+ string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);
+
+ if (line >= 0)
+ {
+ args.Add("-g");
+ args.Add($"{scriptPath}:{line + 1}:{col}");
+ }
+ else
+ {
+ args.Add(scriptPath);
+ }
+
+ string command;
+
+ if (OS.IsOSX())
+ {
+ if (!osxAppBundleInstalled && _vsCodePath.Empty())
+ {
+ GD.PushError("Cannot find code editor: VSCode");
+ return Error.FileNotFound;
+ }
+
+ command = osxAppBundleInstalled ? "/usr/bin/open" : _vsCodePath;
+ }
+ else
+ {
+ if (_vsCodePath.Empty())
+ {
+ GD.PushError("Cannot find code editor: VSCode");
+ return Error.FileNotFound;
+ }
+
+ command = _vsCodePath;
+ }
+
+ try
+ {
+ OS.RunProcess(command, args);
+ }
+ catch (Exception e)
+ {
+ GD.PushError($"Error when trying to run code editor: VSCode. Exception message: '{e.Message}'");
+ }
+
+ break;
+ }
+
+ case ExternalEditor.VisualStudioForMac:
+ goto case ExternalEditor.MonoDevelop;
+ case ExternalEditor.MonoDevelop:
+ {
+ MonoDevelopInstance GetMonoDevelopInstance(string solutionPath)
+ {
+ if (OS.IsOSX() && editor == ExternalEditor.VisualStudioForMac)
+ {
+ if (visualStudioForMacInstance == null)
+ visualStudioForMacInstance = new MonoDevelopInstance(solutionPath, MonoDevelopInstance.EditorId.VisualStudioForMac);
+
+ return visualStudioForMacInstance;
+ }
+
+ if (monoDevelopInstance == null)
+ monoDevelopInstance = new MonoDevelopInstance(solutionPath, MonoDevelopInstance.EditorId.MonoDevelop);
+
+ return monoDevelopInstance;
+ }
+
+ string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath);
+
+ if (line >= 0)
+ scriptPath += $";{line + 1};{col}";
+
+ GetMonoDevelopInstance(GodotSharpDirs.ProjectSlnPath).Execute(scriptPath);
+
+ break;
+ }
+
+ case ExternalEditor.None:
+ return Error.Unavailable;
+ default:
+ throw new ArgumentOutOfRangeException();
+ }
+
+ return Error.Ok;
+ }
+
+ public bool OverridesExternalEditor()
+ {
+ return (ExternalEditor) editorSettings.GetSetting("mono/editor/external_editor") != ExternalEditor.None;
+ }
+
+ public override bool Build()
+ {
+ return GodotSharpBuilds.EditorBuildCallback();
+ }
+
+ public override void EnablePlugin()
+ {
+ base.EnablePlugin();
+
+ if (Instance != null)
+ throw new InvalidOperationException();
+ Instance = this;
+
+ var editorInterface = GetEditorInterface();
+ var editorBaseControl = editorInterface.GetBaseControl();
+
+ editorSettings = editorInterface.GetEditorSettings();
+
+ errorDialog = new AcceptDialog();
+ editorBaseControl.AddChild(errorDialog);
+
+ MonoBottomPanel = new MonoBottomPanel();
+
+ bottomPanelBtn = AddControlToBottomPanel(MonoBottomPanel, "Mono".TTR());
+
+ AddChild(new HotReloadAssemblyWatcher {Name = "HotReloadAssemblyWatcher"});
+
+ menuPopup = new PopupMenu();
+ menuPopup.Hide();
+ menuPopup.SetAsToplevel(true);
+
+ AddToolSubmenuItem("Mono", menuPopup);
+
+ // TODO: Remove or edit this info dialog once Mono support is no longer in alpha
+ {
+ menuPopup.AddItem("About C# support".TTR(), (int) MenuOptions.AboutCSharp);
+ aboutDialog = new AcceptDialog();
+ editorBaseControl.AddChild(aboutDialog);
+ aboutDialog.WindowTitle = "Important: C# support is not feature-complete";
+
+ // We don't use DialogText as the default AcceptDialog Label doesn't play well with the TextureRect and CheckBox
+ // we'll add. Instead we add containers and a new autowrapped Label inside.
+
+ // Main VBoxContainer (icon + label on top, checkbox at bottom)
+ var aboutVBox = new VBoxContainer();
+ aboutDialog.AddChild(aboutVBox);
+
+ // HBoxContainer for icon + label
+ var aboutHBox = new HBoxContainer();
+ aboutVBox.AddChild(aboutHBox);
+
+ var aboutIcon = new TextureRect();
+ aboutIcon.Texture = aboutIcon.GetIcon("NodeWarning", "EditorIcons");
+ aboutHBox.AddChild(aboutIcon);
+
+ var aboutLabel = new Label();
+ aboutHBox.AddChild(aboutLabel);
+ aboutLabel.RectMinSize = new Vector2(600, 150) * EditorScale;
+ aboutLabel.SizeFlagsVertical = (int) Control.SizeFlags.ExpandFill;
+ aboutLabel.Autowrap = true;
+ aboutLabel.Text =
+ "C# support in Godot Engine is in late alpha stage and, while already usable, " +
+ "it is not meant for use in production.\n\n" +
+ "Projects can be exported to Linux, macOS and Windows, but not yet to mobile or web platforms. " +
+ "Bugs and usability issues will be addressed gradually over future releases, " +
+ "potentially including compatibility breaking changes as new features are implemented for a better overall C# experience.\n\n" +
+ "If you experience issues with this Mono build, please report them on Godot's issue tracker with details about your system, MSBuild version, IDE, etc.:\n\n" +
+ " https://github.com/godotengine/godot/issues\n\n" +
+ "Your critical feedback at this stage will play a great role in shaping the C# support in future releases, so thank you!";
+
+ EditorDef("mono/editor/show_info_on_start", true);
+
+ // CheckBox in main container
+ aboutDialogCheckBox = new CheckBox {Text = "Show this warning when starting the editor"};
+ aboutDialogCheckBox.Connect("toggled", this, nameof(_ToggleAboutDialogOnStart));
+ aboutVBox.AddChild(aboutDialogCheckBox);
+ }
+
+ if (File.Exists(GodotSharpDirs.ProjectSlnPath) && File.Exists(GodotSharpDirs.ProjectCsProjPath))
+ {
+ // Make sure the existing project has Api assembly references configured correctly
+ CSharpProject.FixApiHintPath(GodotSharpDirs.ProjectCsProjPath);
+ }
+ else
+ {
+ bottomPanelBtn.Hide();
+ menuPopup.AddItem("Create C# solution".TTR(), (int) MenuOptions.CreateSln);
+ }
+
+ menuPopup.Connect("id_pressed", this, nameof(_MenuOptionPressed));
+
+ var buildButton = new ToolButton
+ {
+ Text = "Build",
+ HintTooltip = "Build solution",
+ FocusMode = Control.FocusModeEnum.None
+ };
+ buildButton.Connect("pressed", this, nameof(_BuildSolutionPressed));
+ AddControlToContainer(CustomControlContainer.Toolbar, buildButton);
+
+ // External editor settings
+ EditorDef("mono/editor/external_editor", ExternalEditor.None);
+
+ string settingsHintStr = "Disabled";
+
+ if (OS.IsWindows())
+ {
+ settingsHintStr += $",MonoDevelop:{(int) ExternalEditor.MonoDevelop}" +
+ $",Visual Studio Code:{(int) ExternalEditor.VsCode}";
+ }
+ else if (OS.IsOSX())
+ {
+ settingsHintStr += $",Visual Studio:{(int) ExternalEditor.VisualStudioForMac}" +
+ $",MonoDevelop:{(int) ExternalEditor.MonoDevelop}" +
+ $",Visual Studio Code:{(int) ExternalEditor.VsCode}";
+ }
+ else if (OS.IsUnix())
+ {
+ settingsHintStr += $",MonoDevelop:{(int) ExternalEditor.MonoDevelop}" +
+ $",Visual Studio Code:{(int) ExternalEditor.VsCode}";
+ }
+
+ editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary
+ {
+ ["type"] = Variant.Type.Int,
+ ["name"] = "mono/editor/external_editor",
+ ["hint"] = PropertyHint.Enum,
+ ["hint_string"] = settingsHintStr
+ });
+
+ // Export plugin
+ var exportPlugin = new GodotSharpExport();
+ AddExportPlugin(exportPlugin);
+ exportPluginWeak = WeakRef(exportPlugin);
+
+ GodotSharpBuilds.Initialize();
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ base.Dispose(disposing);
+
+ if (exportPluginWeak != null)
+ {
+ // We need to dispose our export plugin before the editor destroys EditorSettings.
+ // Otherwise, if the GC disposes it at a later time, EditorExportPlatformAndroid
+ // will be freed after EditorSettings already was, and its device polling thread
+ // will try to access the EditorSettings singleton, resulting in null dereferencing.
+ (exportPluginWeak.GetRef() as GodotSharpExport)?.Dispose();
+
+ exportPluginWeak.Dispose();
+ }
+ }
+
+ public void OnBeforeSerialize()
+ {
+ }
+
+ public void OnAfterDeserialize()
+ {
+ Instance = this;
+ }
+
+ // Singleton
+
+ public static GodotSharpEditor Instance { get; private set; }
+
+ private GodotSharpEditor()
+ {
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpExport.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpExport.cs
new file mode 100644
index 0000000000..b80fe1fab7
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpExport.cs
@@ -0,0 +1,197 @@
+using Godot;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using GodotTools.Core;
+using GodotTools.Internals;
+using Directory = GodotTools.Utils.Directory;
+using File = GodotTools.Utils.File;
+using Path = System.IO.Path;
+
+namespace GodotTools
+{
+ public class GodotSharpExport : EditorExportPlugin
+ {
+ private void AddFile(string srcPath, string dstPath, bool remap = false)
+ {
+ AddFile(dstPath, File.ReadAllBytes(srcPath), remap);
+ }
+
+ public override void _ExportFile(string path, string type, string[] features)
+ {
+ base._ExportFile(path, type, features);
+
+ if (type != Internal.CSharpLanguageType)
+ return;
+
+ if (Path.GetExtension(path) != $".{Internal.CSharpLanguageExtension}")
+ throw new ArgumentException($"Resource of type {Internal.CSharpLanguageType} has an invalid file extension: {path}", nameof(path));
+
+ // TODO What if the source file is not part of the game's C# project
+
+ bool includeScriptsContent = (bool) ProjectSettings.GetSetting("mono/export/include_scripts_content");
+
+ if (!includeScriptsContent)
+ {
+ // We don't want to include the source code on exported games
+ AddFile(path, new byte[] { }, remap: false);
+ Skip();
+ }
+ }
+
+ public override void _ExportBegin(string[] features, bool isDebug, string path, int flags)
+ {
+ base._ExportBegin(features, isDebug, path, flags);
+
+ try
+ {
+ _ExportBeginImpl(features, isDebug, path, flags);
+ }
+ catch (Exception e)
+ {
+ GD.PushError($"Failed to export project. Exception message: {e.Message}");
+ Console.Error.WriteLine(e);
+ }
+ }
+
+ public void _ExportBeginImpl(string[] features, bool isDebug, string path, int flags)
+ {
+ // TODO Right now there is no way to stop the export process with an error
+
+ if (File.Exists(GodotSharpDirs.ProjectSlnPath))
+ {
+ string buildConfig = isDebug ? "Debug" : "Release";
+
+ string scriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, $"scripts_metadata.{(isDebug ? "debug" : "release")}");
+ CSharpProject.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, scriptsMetadataPath);
+
+ AddFile(scriptsMetadataPath, scriptsMetadataPath);
+
+ // Turn export features into defines
+ var godotDefines = features;
+
+ if (!GodotSharpBuilds.BuildProjectBlocking(buildConfig, godotDefines))
+ {
+ GD.PushError("Failed to build project");
+ return;
+ }
+
+ // Add dependency assemblies
+
+ var dependencies = new Godot.Collections.Dictionary<string, string>();
+
+ var projectDllName = (string) ProjectSettings.GetSetting("application/config/name");
+ if (projectDllName.Empty())
+ {
+ projectDllName = "UnnamedProject";
+ }
+
+ string projectDllSrcDir = Path.Combine(GodotSharpDirs.ResTempAssembliesBaseDir, buildConfig);
+ string projectDllSrcPath = Path.Combine(projectDllSrcDir, $"{projectDllName}.dll");
+
+ dependencies[projectDllName] = projectDllSrcPath;
+
+ {
+ string templatesDir = Internal.FullTemplatesDir;
+ string androidBclDir = Path.Combine(templatesDir, "android-bcl");
+
+ string customLibDir = features.Contains("Android") && Directory.Exists(androidBclDir) ? androidBclDir : string.Empty;
+
+ GetExportedAssemblyDependencies(projectDllName, projectDllSrcPath, buildConfig, customLibDir, dependencies);
+ }
+
+ string apiConfig = isDebug ? "Debug" : "Release";
+ string resAssembliesDir = Path.Combine(GodotSharpDirs.ResAssembliesBaseDir, apiConfig);
+
+ foreach (var dependency in dependencies)
+ {
+ string dependSrcPath = dependency.Value;
+ string dependDstPath = Path.Combine(resAssembliesDir, dependSrcPath.GetFile());
+ AddFile(dependSrcPath, dependDstPath);
+ }
+ }
+
+ // Mono specific export template extras (data dir)
+ ExportDataDirectory(features, isDebug, path);
+ }
+
+ private static void ExportDataDirectory(IEnumerable<string> features, bool debug, string path)
+ {
+ var featureSet = new HashSet<string>(features);
+
+ if (!PlatformHasTemplateDir(featureSet))
+ return;
+
+ string templateDirName = "data.mono";
+
+ if (featureSet.Contains("Windows"))
+ {
+ templateDirName += ".windows";
+ templateDirName += featureSet.Contains("64") ? ".64" : ".32";
+ }
+ else if (featureSet.Contains("X11"))
+ {
+ templateDirName += ".x11";
+ templateDirName += featureSet.Contains("64") ? ".64" : ".32";
+ }
+ else
+ {
+ throw new NotSupportedException("Target platform not supported");
+ }
+
+ templateDirName += debug ? ".release_debug" : ".release";
+
+ string templateDirPath = Path.Combine(Internal.FullTemplatesDir, templateDirName);
+
+ if (!Directory.Exists(templateDirPath))
+ throw new FileNotFoundException("Data template directory not found");
+
+ string outputDir = new FileInfo(path).Directory?.FullName ??
+ throw new FileNotFoundException("Base directory not found");
+
+ string outputDataDir = Path.Combine(outputDir, DataDirName);
+
+ if (Directory.Exists(outputDataDir))
+ Directory.Delete(outputDataDir, recursive: true); // Clean first
+
+ Directory.CreateDirectory(outputDataDir);
+
+ foreach (string dir in Directory.GetDirectories(templateDirPath, "*", SearchOption.AllDirectories))
+ {
+ Directory.CreateDirectory(Path.Combine(outputDataDir, dir.Substring(templateDirPath.Length + 1)));
+ }
+
+ foreach (string file in Directory.GetFiles(templateDirPath, "*", SearchOption.AllDirectories))
+ {
+ File.Copy(file, Path.Combine(outputDataDir, file.Substring(templateDirPath.Length + 1)));
+ }
+ }
+
+ private static bool PlatformHasTemplateDir(IEnumerable<string> featureSet)
+ {
+ // OSX export templates are contained in a zip, so we place
+ // our custom template inside it and let Godot do the rest.
+ return !featureSet.Any(f => new[] {"OSX", "Android"}.Contains(f));
+ }
+
+ private static string DataDirName
+ {
+ get
+ {
+ var appName = (string) ProjectSettings.GetSetting("application/config/name");
+ string appNameSafe = appName.ToSafeDirName(allowDirSeparator: false);
+ return $"data_{appNameSafe}";
+ }
+ }
+
+ private static void GetExportedAssemblyDependencies(string projectDllName, string projectDllSrcPath,
+ string buildConfig, string customLibDir, Godot.Collections.Dictionary<string, string> dependencies) =>
+ internal_GetExportedAssemblyDependencies(projectDllName, projectDllSrcPath, buildConfig, customLibDir, dependencies);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void internal_GetExportedAssemblyDependencies(string projectDllName, string projectDllSrcPath,
+ string buildConfig, string customLibDir, Godot.Collections.Dictionary<string, string> dependencies);
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
new file mode 100644
index 0000000000..01e8c87d14
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProjectGuid>{27B00618-A6F2-4828-B922-05CAEB08C286}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <RootNamespace>GodotTools</RootNamespace>
+ <AssemblyName>GodotTools</AssemblyName>
+ <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <GodotSourceRootPath>$(SolutionDir)/../../../../</GodotSourceRootPath>
+ <GodotApiConfiguration>Debug</GodotApiConfiguration>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>portable</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug</OutputPath>
+ <DefineConstants>DEBUG;</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <ConsolePause>false</ConsolePause>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release</OutputPath>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ <ConsolePause>false</ConsolePause>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ <Reference Include="GodotSharp">
+ <HintPath>$(GodotSourceRootPath)/bin/GodotSharp/Api/$(GodotApiConfiguration)/GodotSharp.dll</HintPath>
+ </Reference>
+ <Reference Include="GodotSharpEditor">
+ <HintPath>$(GodotSourceRootPath)/bin/GodotSharp/Api/$(GodotApiConfiguration)/GodotSharpEditor.dll</HintPath>
+ </Reference>
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Build\MsBuildFinder.cs" />
+ <Compile Include="Internals\BindingsGenerator.cs" />
+ <Compile Include="Internals\EditorProgress.cs" />
+ <Compile Include="Internals\GodotSharpDirs.cs" />
+ <Compile Include="Internals\Internal.cs" />
+ <Compile Include="Internals\ScriptClassParser.cs" />
+ <Compile Include="Internals\Globals.cs" />
+ <Compile Include="MonoDevelopInstance.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Build\BuildSystem.cs" />
+ <Compile Include="Utils\Directory.cs" />
+ <Compile Include="Utils\File.cs" />
+ <Compile Include="Utils\OS.cs" />
+ <Compile Include="GodotSharpEditor.cs" />
+ <Compile Include="GodotSharpBuilds.cs" />
+ <Compile Include="HotReloadAssemblyWatcher.cs" />
+ <Compile Include="MonoBuildInfo.cs" />
+ <Compile Include="MonoBuildTab.cs" />
+ <Compile Include="MonoBottomPanel.cs" />
+ <Compile Include="GodotSharpExport.cs" />
+ <Compile Include="CSharpProject.cs" />
+ <Compile Include="Utils\CollectionExtensions.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\GodotTools.BuildLogger\GodotTools.BuildLogger.csproj">
+ <Project>{6ce9a984-37b1-4f8a-8fe9-609f05f071b3}</Project>
+ <Name>GodotTools.BuildLogger</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\GodotTools.ProjectEditor\GodotTools.ProjectEditor.csproj">
+ <Project>{A8CDAD94-C6D4-4B19-A7E7-76C53CC92984}</Project>
+ <Name>GodotTools.ProjectEditor</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\GodotTools.Core\GodotTools.Core.csproj">
+ <Project>{639E48BD-44E5-4091-8EDD-22D36DC0768D}</Project>
+ <Name>GodotTools.Core</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <ItemGroup>
+ <Folder Include="Editor" />
+ </ItemGroup>
+ <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+</Project> \ No newline at end of file
diff --git a/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs b/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs
new file mode 100644
index 0000000000..0f6f5ffadc
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs
@@ -0,0 +1,48 @@
+using Godot;
+using GodotTools.Internals;
+using static GodotTools.Internals.Globals;
+
+namespace GodotTools
+{
+ public class HotReloadAssemblyWatcher : Node
+ {
+ private Timer watchTimer;
+
+ public override void _Notification(int what)
+ {
+ if (what == MainLoop.NotificationWmFocusIn)
+ {
+ RestartTimer();
+
+ if (Internal.IsAssembliesReloadingNeeded())
+ Internal.ReloadAssemblies(softReload: false);
+ }
+ }
+
+ private void TimerTimeout()
+ {
+ if (Internal.IsAssembliesReloadingNeeded())
+ Internal.ReloadAssemblies(softReload: false);
+ }
+
+ public void RestartTimer()
+ {
+ watchTimer.Stop();
+ watchTimer.Start();
+ }
+
+ public override void _Ready()
+ {
+ base._Ready();
+
+ watchTimer = new Timer
+ {
+ OneShot = false,
+ WaitTime = (float) EditorDef("mono/assembly_watch_interval_sec", 0.5)
+ };
+ watchTimer.Connect("timeout", this, nameof(TimerTimeout));
+ AddChild(watchTimer);
+ watchTimer.Start();
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/BindingsGenerator.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/BindingsGenerator.cs
new file mode 100644
index 0000000000..1daa5e138e
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/BindingsGenerator.cs
@@ -0,0 +1,87 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace GodotTools.Internals
+{
+ public class BindingsGenerator : IDisposable
+ {
+ class BindingsGeneratorSafeHandle : SafeHandle
+ {
+ public BindingsGeneratorSafeHandle(IntPtr handle) : base(IntPtr.Zero, true)
+ {
+ this.handle = handle;
+ }
+
+ public override bool IsInvalid => handle == IntPtr.Zero;
+
+ protected override bool ReleaseHandle()
+ {
+ internal_Dtor(handle);
+ return true;
+ }
+ }
+
+ private BindingsGeneratorSafeHandle safeHandle;
+ private bool disposed = false;
+
+ public bool LogPrintEnabled
+ {
+ get => internal_LogPrintEnabled(GetPtr());
+ set => internal_SetLogPrintEnabled(GetPtr(), value);
+ }
+
+ public static uint Version => internal_Version();
+ public static uint CsGlueVersion => internal_CsGlueVersion();
+
+ public Godot.Error GenerateCsApi(string outputDir) => internal_GenerateCsApi(GetPtr(), outputDir);
+
+ internal IntPtr GetPtr()
+ {
+ if (disposed)
+ throw new ObjectDisposedException(GetType().FullName);
+
+ return safeHandle.DangerousGetHandle();
+ }
+
+ public void Dispose()
+ {
+ if (disposed)
+ return;
+
+ if (safeHandle != null && !safeHandle.IsInvalid)
+ {
+ safeHandle.Dispose();
+ safeHandle = null;
+ }
+
+ disposed = true;
+ }
+
+ public BindingsGenerator()
+ {
+ safeHandle = new BindingsGeneratorSafeHandle(internal_Ctor());
+ }
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern IntPtr internal_Ctor();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void internal_Dtor(IntPtr handle);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern bool internal_LogPrintEnabled(IntPtr handle);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void internal_SetLogPrintEnabled(IntPtr handle, bool enabled);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern Godot.Error internal_GenerateCsApi(IntPtr handle, string outputDir);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern uint internal_Version();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern uint internal_CsGlueVersion();
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs
new file mode 100644
index 0000000000..70ba7c733a
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/EditorProgress.cs
@@ -0,0 +1,50 @@
+using System;
+using System.Runtime.CompilerServices;
+using Godot;
+
+namespace GodotTools.Internals
+{
+ public class EditorProgress : IDisposable
+ {
+ public string Task { get; }
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void internal_Create(string task, string label, int amount, bool canCancel);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void internal_Dispose(string task);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern bool internal_Step(string task, string state, int step, bool forceRefresh);
+
+ public EditorProgress(string task, string label, int amount, bool canCancel = false)
+ {
+ Task = task;
+ internal_Create(task, label, amount, canCancel);
+ }
+
+ ~EditorProgress()
+ {
+ // Should never rely on the GC to dispose EditorProgress.
+ // It should be disposed immediately when the task finishes.
+ GD.PushError("EditorProgress disposed by the Garbage Collector");
+ Dispose();
+ }
+
+ public void Dispose()
+ {
+ internal_Dispose(Task);
+ GC.SuppressFinalize(this);
+ }
+
+ public void Step(string state, int step = -1, bool forceRefresh = true)
+ {
+ internal_Step(Task, state, step, forceRefresh);
+ }
+
+ public bool TryStep(string state, int step = -1, bool forceRefresh = true)
+ {
+ return internal_Step(Task, state, step, forceRefresh);
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs
new file mode 100644
index 0000000000..793f84fd77
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/Globals.cs
@@ -0,0 +1,33 @@
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.CompilerServices;
+
+namespace GodotTools.Internals
+{
+ public static class Globals
+ {
+ public static float EditorScale => internal_EditorScale();
+
+ public static object GlobalDef(string setting, object defaultValue, bool restartIfChanged = false) =>
+ internal_GlobalDef(setting, defaultValue, restartIfChanged);
+
+ public static object EditorDef(string setting, object defaultValue, bool restartIfChanged = false) =>
+ internal_EditorDef(setting, defaultValue, restartIfChanged);
+
+ [SuppressMessage("ReSharper", "InconsistentNaming")]
+ public static string TTR(this string text) => internal_TTR(text);
+
+ // Internal Calls
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern float internal_EditorScale();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern object internal_GlobalDef(string setting, object defaultValue, bool restartIfChanged);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern object internal_EditorDef(string setting, object defaultValue, bool restartIfChanged);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_TTR(string text);
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs
new file mode 100644
index 0000000000..ddf3b829b5
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/GodotSharpDirs.cs
@@ -0,0 +1,91 @@
+using System.Runtime.CompilerServices;
+
+namespace GodotTools.Internals
+{
+ public static class GodotSharpDirs
+ {
+ public static string ResDataDir => internal_ResDataDir();
+ public static string ResMetadataDir => internal_ResMetadataDir();
+ public static string ResAssembliesBaseDir => internal_ResAssembliesBaseDir();
+ public static string ResAssembliesDir => internal_ResAssembliesDir();
+ public static string ResConfigDir => internal_ResConfigDir();
+ public static string ResTempDir => internal_ResTempDir();
+ public static string ResTempAssembliesBaseDir => internal_ResTempAssembliesBaseDir();
+ public static string ResTempAssembliesDir => internal_ResTempAssembliesDir();
+
+ public static string MonoUserDir => internal_MonoUserDir();
+ public static string MonoLogsDir => internal_MonoLogsDir();
+
+ #region Tools-only
+ public static string MonoSolutionsDir => internal_MonoSolutionsDir();
+ public static string BuildLogsDirs => internal_BuildLogsDirs();
+
+ public static string ProjectSlnPath => internal_ProjectSlnPath();
+ public static string ProjectCsProjPath => internal_ProjectCsProjPath();
+
+ public static string DataEditorToolsDir => internal_DataEditorToolsDir();
+ public static string DataEditorPrebuiltApiDir => internal_DataEditorPrebuiltApiDir();
+ #endregion
+
+ public static string DataMonoEtcDir => internal_DataMonoEtcDir();
+ public static string DataMonoLibDir => internal_DataMonoLibDir();
+
+ #region Windows-only
+ public static string DataMonoBinDir => internal_DataMonoBinDir();
+ #endregion
+
+
+ #region Internal
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_ResDataDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_ResMetadataDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_ResAssembliesBaseDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_ResAssembliesDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_ResConfigDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_ResTempDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_ResTempAssembliesBaseDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_ResTempAssembliesDir();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_MonoUserDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_MonoLogsDir();
+
+ #region Tools-only
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_MonoSolutionsDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_BuildLogsDirs();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_ProjectSlnPath();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_ProjectCsProjPath();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_DataEditorToolsDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_DataEditorPrebuiltApiDir();
+ #endregion
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_DataMonoEtcDir();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_DataMonoLibDir();
+
+ #region Windows-only
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_DataMonoBinDir();
+ #endregion
+
+ #endregion
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs
new file mode 100644
index 0000000000..9526dd3c6f
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs
@@ -0,0 +1,99 @@
+using System;
+using System.Runtime.CompilerServices;
+using Godot;
+using Godot.Collections;
+
+namespace GodotTools.Internals
+{
+ public static class Internal
+ {
+ public const string CSharpLanguageType = "CSharpScript";
+ public const string CSharpLanguageExtension = "cs";
+
+ public static string UpdateApiAssembliesFromPrebuilt() =>
+ internal_UpdateApiAssembliesFromPrebuilt();
+
+ public static string FullTemplatesDir =>
+ internal_FullTemplatesDir();
+
+ public static string SimplifyGodotPath(this string path) => internal_SimplifyGodotPath(path);
+
+ public static bool IsOsxAppBundleInstalled(string bundleId) => internal_IsOsxAppBundleInstalled(bundleId);
+
+ public static bool GodotIs32Bits() => internal_GodotIs32Bits();
+
+ public static bool GodotIsRealTDouble() => internal_GodotIsRealTDouble();
+
+ public static void GodotMainIteration() => internal_GodotMainIteration();
+
+ public static ulong GetCoreApiHash() => internal_GetCoreApiHash();
+
+ public static ulong GetEditorApiHash() => internal_GetEditorApiHash();
+
+ public static bool IsAssembliesReloadingNeeded() => internal_IsAssembliesReloadingNeeded();
+
+ public static void ReloadAssemblies(bool softReload) => internal_ReloadAssemblies(softReload);
+
+ public static void ScriptEditorDebuggerReloadScripts() => internal_ScriptEditorDebuggerReloadScripts();
+
+ public static bool ScriptEditorEdit(Resource resource, int line, int col, bool grabFocus = true) =>
+ internal_ScriptEditorEdit(resource, line, col, grabFocus);
+
+ public static void EditorNodeShowScriptScreen() => internal_EditorNodeShowScriptScreen();
+
+ public static Dictionary<string, object> GetScriptsMetadataOrNothing() =>
+ internal_GetScriptsMetadataOrNothing(typeof(Dictionary<string, object>));
+
+ public static string MonoWindowsInstallRoot => internal_MonoWindowsInstallRoot();
+
+ // Internal Calls
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_UpdateApiAssembliesFromPrebuilt();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_FullTemplatesDir();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_SimplifyGodotPath(this string path);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern bool internal_IsOsxAppBundleInstalled(string bundleId);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern bool internal_GodotIs32Bits();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern bool internal_GodotIsRealTDouble();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void internal_GodotMainIteration();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern ulong internal_GetCoreApiHash();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern ulong internal_GetEditorApiHash();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern bool internal_IsAssembliesReloadingNeeded();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void internal_ReloadAssemblies(bool softReload);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void internal_ScriptEditorDebuggerReloadScripts();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern bool internal_ScriptEditorEdit(Resource resource, int line, int col, bool grabFocus);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void internal_EditorNodeShowScriptScreen();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern Dictionary<string, object> internal_GetScriptsMetadataOrNothing(Type dictType);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern string internal_MonoWindowsInstallRoot();
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs
new file mode 100644
index 0000000000..2497d276a9
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Internals/ScriptClassParser.cs
@@ -0,0 +1,52 @@
+using System;
+using System.Collections.Generic;
+using System.Runtime.CompilerServices;
+using Godot;
+using Godot.Collections;
+
+namespace GodotTools.Internals
+{
+ public static class ScriptClassParser
+ {
+ public class ClassDecl
+ {
+ public string Name { get; }
+ public string Namespace { get; }
+ public bool Nested { get; }
+ public int BaseCount { get; }
+
+ public ClassDecl(string name, string @namespace, bool nested, int baseCount)
+ {
+ Name = name;
+ Namespace = @namespace;
+ Nested = nested;
+ BaseCount = baseCount;
+ }
+ }
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern Error internal_ParseFile(string filePath, Array<Dictionary> classes);
+
+ public static void ParseFileOrThrow(string filePath, out IEnumerable<ClassDecl> classes)
+ {
+ var classesArray = new Array<Dictionary>();
+ var error = internal_ParseFile(filePath, classesArray);
+ if (error != Error.Ok)
+ throw new Exception($"Failed to determine namespace and class for script: {filePath}. Parse error: {error}");
+
+ var classesList = new List<ClassDecl>();
+
+ foreach (var classDeclDict in classesArray)
+ {
+ classesList.Add(new ClassDecl(
+ (string) classDeclDict["name"],
+ (string) classDeclDict["namespace"],
+ (bool) classDeclDict["nested"],
+ (int) classDeclDict["base_count"]
+ ));
+ }
+
+ classes = classesList;
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/MonoBottomPanel.cs b/modules/mono/editor/GodotTools/GodotTools/MonoBottomPanel.cs
new file mode 100644
index 0000000000..53ff0891d5
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/MonoBottomPanel.cs
@@ -0,0 +1,343 @@
+using Godot;
+using System;
+using System.IO;
+using Godot.Collections;
+using GodotTools.Internals;
+using static GodotTools.Internals.Globals;
+using File = GodotTools.Utils.File;
+using Path = System.IO.Path;
+
+namespace GodotTools
+{
+ public class MonoBottomPanel : VBoxContainer
+ {
+ private EditorInterface editorInterface;
+
+ private TabContainer panelTabs;
+
+ private VBoxContainer panelBuildsTab;
+
+ private ItemList buildTabsList;
+ private TabContainer buildTabs;
+
+ private ToolButton warningsBtn;
+ private ToolButton errorsBtn;
+ private Button viewLogBtn;
+
+ private void _UpdateBuildTabsList()
+ {
+ buildTabsList.Clear();
+
+ int currentTab = buildTabs.CurrentTab;
+
+ bool noCurrentTab = currentTab < 0 || currentTab >= buildTabs.GetTabCount();
+
+ for (int i = 0; i < buildTabs.GetChildCount(); i++)
+ {
+ var tab = (MonoBuildTab) buildTabs.GetChild(i);
+
+ if (tab == null)
+ continue;
+
+ string itemName = Path.GetFileNameWithoutExtension(tab.BuildInfo.Solution);
+ itemName += " [" + tab.BuildInfo.Configuration + "]";
+
+ buildTabsList.AddItem(itemName, tab.IconTexture);
+
+ string itemTooltip = "Solution: " + tab.BuildInfo.Solution;
+ itemTooltip += "\nConfiguration: " + tab.BuildInfo.Configuration;
+ itemTooltip += "\nStatus: ";
+
+ if (tab.BuildExited)
+ itemTooltip += tab.BuildResult == MonoBuildTab.BuildResults.Success ? "Succeeded" : "Errored";
+ else
+ itemTooltip += "Running";
+
+ if (!tab.BuildExited || tab.BuildResult == MonoBuildTab.BuildResults.Error)
+ itemTooltip += $"\nErrors: {tab.ErrorCount}";
+
+ itemTooltip += $"\nWarnings: {tab.WarningCount}";
+
+ buildTabsList.SetItemTooltip(i, itemTooltip);
+
+ if (noCurrentTab || currentTab == i)
+ {
+ buildTabsList.Select(i);
+ _BuildTabsItemSelected(i);
+ }
+ }
+ }
+
+ public MonoBuildTab GetBuildTabFor(MonoBuildInfo buildInfo)
+ {
+ foreach (var buildTab in new Array<MonoBuildTab>(buildTabs.GetChildren()))
+ {
+ if (buildTab.BuildInfo.Equals(buildInfo))
+ return buildTab;
+ }
+
+ var newBuildTab = new MonoBuildTab(buildInfo);
+ AddBuildTab(newBuildTab);
+
+ return newBuildTab;
+ }
+
+ private void _BuildTabsItemSelected(int idx)
+ {
+ if (idx < 0 || idx >= buildTabs.GetTabCount())
+ throw new IndexOutOfRangeException();
+
+ buildTabs.CurrentTab = idx;
+ if (!buildTabs.Visible)
+ buildTabs.Visible = true;
+
+ warningsBtn.Visible = true;
+ errorsBtn.Visible = true;
+ viewLogBtn.Visible = true;
+ }
+
+ private void _BuildTabsNothingSelected()
+ {
+ if (buildTabs.GetTabCount() != 0)
+ {
+ // just in case
+ buildTabs.Visible = false;
+
+ // This callback is called when clicking on the empty space of the list.
+ // ItemList won't deselect the items automatically, so we must do it ourselves.
+ buildTabsList.UnselectAll();
+ }
+
+ warningsBtn.Visible = false;
+ errorsBtn.Visible = false;
+ viewLogBtn.Visible = false;
+ }
+
+ private void _WarningsToggled(bool pressed)
+ {
+ int currentTab = buildTabs.CurrentTab;
+
+ if (currentTab < 0 || currentTab >= buildTabs.GetTabCount())
+ throw new InvalidOperationException("No tab selected");
+
+ var buildTab = (MonoBuildTab) buildTabs.GetChild(currentTab);
+ buildTab.WarningsVisible = pressed;
+ buildTab.UpdateIssuesList();
+ }
+
+ private void _ErrorsToggled(bool pressed)
+ {
+ int currentTab = buildTabs.CurrentTab;
+
+ if (currentTab < 0 || currentTab >= buildTabs.GetTabCount())
+ throw new InvalidOperationException("No tab selected");
+
+ var buildTab = (MonoBuildTab) buildTabs.GetChild(currentTab);
+ buildTab.ErrorsVisible = pressed;
+ buildTab.UpdateIssuesList();
+ }
+
+ public void BuildProjectPressed()
+ {
+ if (!File.Exists(GodotSharpDirs.ProjectSlnPath))
+ return; // No solution to build
+
+ string editorScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor");
+ string playerScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor_player");
+
+ CSharpProject.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, editorScriptsMetadataPath);
+
+ if (File.Exists(editorScriptsMetadataPath))
+ {
+ try
+ {
+ File.Copy(editorScriptsMetadataPath, playerScriptsMetadataPath);
+ }
+ catch (IOException e)
+ {
+ GD.PushError($"Failed to copy scripts metadata file. Exception message: {e.Message}");
+ return;
+ }
+ }
+
+ var godotDefines = new[]
+ {
+ OS.GetName(),
+ Internal.GodotIs32Bits() ? "32" : "64"
+ };
+
+ bool buildSuccess = GodotSharpBuilds.BuildProjectBlocking("Tools", godotDefines);
+
+ if (!buildSuccess)
+ return;
+
+ // Notify running game for hot-reload
+ Internal.ScriptEditorDebuggerReloadScripts();
+
+ // Hot-reload in the editor
+ GodotSharpEditor.Instance.GetNode<HotReloadAssemblyWatcher>("HotReloadAssemblyWatcher").RestartTimer();
+
+ if (Internal.IsAssembliesReloadingNeeded())
+ Internal.ReloadAssemblies(softReload: false);
+ }
+
+ private void _ViewLogPressed()
+ {
+ if (!buildTabsList.IsAnythingSelected())
+ return;
+
+ var selectedItems = buildTabsList.GetSelectedItems();
+
+ if (selectedItems.Length != 1)
+ throw new InvalidOperationException($"Expected 1 selected item, got {selectedItems.Length}");
+
+ int selectedItem = selectedItems[0];
+
+ var buildTab = (MonoBuildTab) buildTabs.GetTabControl(selectedItem);
+
+ OS.ShellOpen(Path.Combine(buildTab.BuildInfo.LogsDirPath, GodotSharpBuilds.MsBuildLogFileName));
+ }
+
+ public override void _Notification(int what)
+ {
+ base._Notification(what);
+
+ if (what == EditorSettings.NotificationEditorSettingsChanged)
+ {
+ var editorBaseControl = editorInterface.GetBaseControl();
+ panelTabs.AddStyleboxOverride("panel", editorBaseControl.GetStylebox("DebuggerPanel", "EditorStyles"));
+ panelTabs.AddStyleboxOverride("tab_fg", editorBaseControl.GetStylebox("DebuggerTabFG", "EditorStyles"));
+ panelTabs.AddStyleboxOverride("tab_bg", editorBaseControl.GetStylebox("DebuggerTabBG", "EditorStyles"));
+ }
+ }
+
+ public void AddBuildTab(MonoBuildTab buildTab)
+ {
+ buildTabs.AddChild(buildTab);
+ RaiseBuildTab(buildTab);
+ }
+
+ public void RaiseBuildTab(MonoBuildTab buildTab)
+ {
+ if (buildTab.GetParent() != buildTabs)
+ throw new InvalidOperationException("Build tab is not in the tabs list");
+
+ buildTabs.MoveChild(buildTab, 0);
+ _UpdateBuildTabsList();
+ }
+
+ public void ShowBuildTab()
+ {
+ for (int i = 0; i < panelTabs.GetTabCount(); i++)
+ {
+ if (panelTabs.GetTabControl(i) == panelBuildsTab)
+ {
+ panelTabs.CurrentTab = i;
+ GodotSharpEditor.Instance.MakeBottomPanelItemVisible(this);
+ return;
+ }
+ }
+
+ GD.PushError("Builds tab not found");
+ }
+
+ public override void _Ready()
+ {
+ base._Ready();
+
+ editorInterface = GodotSharpEditor.Instance.GetEditorInterface();
+
+ var editorBaseControl = editorInterface.GetBaseControl();
+
+ SizeFlagsVertical = (int) SizeFlags.ExpandFill;
+ SetAnchorsAndMarginsPreset(LayoutPreset.Wide);
+
+ panelTabs = new TabContainer
+ {
+ TabAlign = TabContainer.TabAlignEnum.Left,
+ RectMinSize = new Vector2(0, 228) * EditorScale,
+ SizeFlagsVertical = (int) SizeFlags.ExpandFill
+ };
+ panelTabs.AddStyleboxOverride("panel", editorBaseControl.GetStylebox("DebuggerPanel", "EditorStyles"));
+ panelTabs.AddStyleboxOverride("tab_fg", editorBaseControl.GetStylebox("DebuggerTabFG", "EditorStyles"));
+ panelTabs.AddStyleboxOverride("tab_bg", editorBaseControl.GetStylebox("DebuggerTabBG", "EditorStyles"));
+ AddChild(panelTabs);
+
+ {
+ // Builds tab
+ panelBuildsTab = new VBoxContainer
+ {
+ Name = "Builds".TTR(),
+ SizeFlagsHorizontal = (int) SizeFlags.ExpandFill
+ };
+ panelTabs.AddChild(panelBuildsTab);
+
+ var toolBarHBox = new HBoxContainer {SizeFlagsHorizontal = (int) SizeFlags.ExpandFill};
+ panelBuildsTab.AddChild(toolBarHBox);
+
+ var buildProjectBtn = new Button
+ {
+ Text = "Build Project".TTR(),
+ FocusMode = FocusModeEnum.None
+ };
+ buildProjectBtn.Connect("pressed", this, nameof(BuildProjectPressed));
+ toolBarHBox.AddChild(buildProjectBtn);
+
+ toolBarHBox.AddSpacer(begin: false);
+
+ warningsBtn = new ToolButton
+ {
+ Text = "Warnings".TTR(),
+ ToggleMode = true,
+ Pressed = true,
+ Visible = false,
+ FocusMode = FocusModeEnum.None
+ };
+ warningsBtn.Connect("toggled", this, nameof(_WarningsToggled));
+ toolBarHBox.AddChild(warningsBtn);
+
+ errorsBtn = new ToolButton
+ {
+ Text = "Errors".TTR(),
+ ToggleMode = true,
+ Pressed = true,
+ Visible = false,
+ FocusMode = FocusModeEnum.None
+ };
+ errorsBtn.Connect("toggled", this, nameof(_ErrorsToggled));
+ toolBarHBox.AddChild(errorsBtn);
+
+ toolBarHBox.AddSpacer(begin: false);
+
+ viewLogBtn = new Button
+ {
+ Text = "View log".TTR(),
+ FocusMode = FocusModeEnum.None,
+ Visible = false
+ };
+ viewLogBtn.Connect("pressed", this, nameof(_ViewLogPressed));
+ toolBarHBox.AddChild(viewLogBtn);
+
+ var hsc = new HSplitContainer
+ {
+ SizeFlagsHorizontal = (int) SizeFlags.ExpandFill,
+ SizeFlagsVertical = (int) SizeFlags.ExpandFill
+ };
+ panelBuildsTab.AddChild(hsc);
+
+ buildTabsList = new ItemList {SizeFlagsHorizontal = (int) SizeFlags.ExpandFill};
+ buildTabsList.Connect("item_selected", this, nameof(_BuildTabsItemSelected));
+ buildTabsList.Connect("nothing_selected", this, nameof(_BuildTabsNothingSelected));
+ hsc.AddChild(buildTabsList);
+
+ buildTabs = new TabContainer
+ {
+ TabAlign = TabContainer.TabAlignEnum.Left,
+ SizeFlagsHorizontal = (int) SizeFlags.ExpandFill,
+ TabsVisible = false
+ };
+ hsc.AddChild(buildTabs);
+ }
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/MonoBuildInfo.cs b/modules/mono/editor/GodotTools/GodotTools/MonoBuildInfo.cs
new file mode 100644
index 0000000000..858e852392
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/MonoBuildInfo.cs
@@ -0,0 +1,47 @@
+using System;
+using Godot;
+using Godot.Collections;
+using GodotTools.Internals;
+using Path = System.IO.Path;
+
+namespace GodotTools
+{
+ [Serializable]
+ public sealed class MonoBuildInfo : Reference // TODO Remove Reference once we have proper serialization
+ {
+ public string Solution { get; }
+ public string Configuration { get; }
+ public Array<string> CustomProperties { get; } = new Array<string>(); // TODO Use List once we have proper serialization
+
+ public string LogsDirPath => Path.Combine(GodotSharpDirs.BuildLogsDirs, $"{Solution.MD5Text()}_{Configuration}");
+
+ public override bool Equals(object obj)
+ {
+ if (obj is MonoBuildInfo other)
+ return other.Solution == Solution && other.Configuration == Configuration;
+
+ return false;
+ }
+
+ public override int GetHashCode()
+ {
+ unchecked
+ {
+ int hash = 17;
+ hash = hash * 29 + Solution.GetHashCode();
+ hash = hash * 29 + Configuration.GetHashCode();
+ return hash;
+ }
+ }
+
+ private MonoBuildInfo()
+ {
+ }
+
+ public MonoBuildInfo(string solution, string configuration)
+ {
+ Solution = solution;
+ Configuration = configuration;
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/MonoBuildTab.cs b/modules/mono/editor/GodotTools/GodotTools/MonoBuildTab.cs
new file mode 100644
index 0000000000..75fdacc0da
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/MonoBuildTab.cs
@@ -0,0 +1,260 @@
+using Godot;
+using System;
+using Godot.Collections;
+using GodotTools.Internals;
+using File = GodotTools.Utils.File;
+using Path = System.IO.Path;
+
+namespace GodotTools
+{
+ public class MonoBuildTab : VBoxContainer
+ {
+ public enum BuildResults
+ {
+ Error,
+ Success
+ }
+
+ [Serializable]
+ private class BuildIssue : Reference // TODO Remove Reference once we have proper serialization
+ {
+ public bool Warning { get; set; }
+ public string File { get; set; }
+ public int Line { get; set; }
+ public int Column { get; set; }
+ public string Code { get; set; }
+ public string Message { get; set; }
+ public string ProjectFile { get; set; }
+ }
+
+ private readonly Array<BuildIssue> issues = new Array<BuildIssue>(); // TODO Use List once we have proper serialization
+ private ItemList issuesList;
+
+ public bool BuildExited { get; private set; } = false;
+
+ public BuildResults? BuildResult { get; private set; } = null;
+
+ public int ErrorCount { get; private set; } = 0;
+
+ public int WarningCount { get; private set; } = 0;
+
+ public bool ErrorsVisible { get; set; } = true;
+ public bool WarningsVisible { get; set; } = true;
+
+ public Texture IconTexture
+ {
+ get
+ {
+ if (!BuildExited)
+ return GetIcon("Stop", "EditorIcons");
+
+ if (BuildResult == BuildResults.Error)
+ return GetIcon("StatusError", "EditorIcons");
+
+ return GetIcon("StatusSuccess", "EditorIcons");
+ }
+ }
+
+ public MonoBuildInfo BuildInfo { get; private set; }
+
+ private void _LoadIssuesFromFile(string csvFile)
+ {
+ using (var file = new Godot.File())
+ {
+ Error openError = file.Open(csvFile, Godot.File.ModeFlags.Read);
+
+ if (openError != Error.Ok)
+ return;
+
+ while (!file.EofReached())
+ {
+ string[] csvColumns = file.GetCsvLine();
+
+ if (csvColumns.Length == 1 && csvColumns[0].Empty())
+ return;
+
+ if (csvColumns.Length != 7)
+ {
+ GD.PushError($"Expected 7 columns, got {csvColumns.Length}");
+ continue;
+ }
+
+ var issue = new BuildIssue
+ {
+ Warning = csvColumns[0] == "warning",
+ File = csvColumns[1],
+ Line = int.Parse(csvColumns[2]),
+ Column = int.Parse(csvColumns[3]),
+ Code = csvColumns[4],
+ Message = csvColumns[5],
+ ProjectFile = csvColumns[6]
+ };
+
+ if (issue.Warning)
+ WarningCount += 1;
+ else
+ ErrorCount += 1;
+
+ issues.Add(issue);
+ }
+ }
+ }
+
+ private void _IssueActivated(int idx)
+ {
+ if (idx < 0 || idx >= issuesList.GetItemCount())
+ throw new IndexOutOfRangeException("Item list index out of range");
+
+ // Get correct issue idx from issue list
+ int issueIndex = (int) issuesList.GetItemMetadata(idx);
+
+ if (idx < 0 || idx >= issues.Count)
+ throw new IndexOutOfRangeException("Issue index out of range");
+
+ BuildIssue issue = issues[issueIndex];
+
+ if (issue.ProjectFile.Empty() && issue.File.Empty())
+ return;
+
+ string projectDir = issue.ProjectFile.Length > 0 ? issue.ProjectFile.GetBaseDir() : BuildInfo.Solution.GetBaseDir();
+
+ string file = Path.Combine(projectDir.SimplifyGodotPath(), issue.File.SimplifyGodotPath());
+
+ if (!File.Exists(file))
+ return;
+
+ file = ProjectSettings.LocalizePath(file);
+
+ if (file.StartsWith("res://"))
+ {
+ var script = (Script) ResourceLoader.Load(file, typeHint: Internal.CSharpLanguageType);
+
+ if (script != null && Internal.ScriptEditorEdit(script, issue.Line, issue.Column))
+ Internal.EditorNodeShowScriptScreen();
+ }
+ }
+
+ public void UpdateIssuesList()
+ {
+ issuesList.Clear();
+
+ using (var warningIcon = GetIcon("Warning", "EditorIcons"))
+ using (var errorIcon = GetIcon("Error", "EditorIcons"))
+ {
+ for (int i = 0; i < issues.Count; i++)
+ {
+ BuildIssue issue = issues[i];
+
+ if (!(issue.Warning ? WarningsVisible : ErrorsVisible))
+ continue;
+
+ string tooltip = string.Empty;
+ tooltip += $"Message: {issue.Message}";
+
+ if (!issue.Code.Empty())
+ tooltip += $"\nCode: {issue.Code}";
+
+ tooltip += $"\nType: {(issue.Warning ? "warning" : "error")}";
+
+ string text = string.Empty;
+
+ if (!issue.File.Empty())
+ {
+ text += $"{issue.File}({issue.Line},{issue.Column}): ";
+
+ tooltip += $"\nFile: {issue.File}";
+ tooltip += $"\nLine: {issue.Line}";
+ tooltip += $"\nColumn: {issue.Column}";
+ }
+
+ if (!issue.ProjectFile.Empty())
+ tooltip += $"\nProject: {issue.ProjectFile}";
+
+ text += issue.Message;
+
+ int lineBreakIdx = text.IndexOf("\n", StringComparison.Ordinal);
+ string itemText = lineBreakIdx == -1 ? text : text.Substring(0, lineBreakIdx);
+ issuesList.AddItem(itemText, issue.Warning ? warningIcon : errorIcon);
+
+ int index = issuesList.GetItemCount() - 1;
+ issuesList.SetItemTooltip(index, tooltip);
+ issuesList.SetItemMetadata(index, i);
+ }
+ }
+ }
+
+ public void OnBuildStart()
+ {
+ BuildExited = false;
+
+ issues.Clear();
+ WarningCount = 0;
+ ErrorCount = 0;
+ UpdateIssuesList();
+
+ GodotSharpEditor.Instance.MonoBottomPanel.RaiseBuildTab(this);
+ }
+
+ public void OnBuildExit(BuildResults result)
+ {
+ BuildExited = true;
+ BuildResult = result;
+
+ _LoadIssuesFromFile(Path.Combine(BuildInfo.LogsDirPath, GodotSharpBuilds.MsBuildIssuesFileName));
+ UpdateIssuesList();
+
+ GodotSharpEditor.Instance.MonoBottomPanel.RaiseBuildTab(this);
+ }
+
+ public void OnBuildExecFailed(string cause)
+ {
+ BuildExited = true;
+ BuildResult = BuildResults.Error;
+
+ issuesList.Clear();
+
+ var issue = new BuildIssue {Message = cause, Warning = false};
+
+ ErrorCount += 1;
+ issues.Add(issue);
+
+ UpdateIssuesList();
+
+ GodotSharpEditor.Instance.MonoBottomPanel.RaiseBuildTab(this);
+ }
+
+ public void RestartBuild()
+ {
+ if (!BuildExited)
+ throw new InvalidOperationException("Build already started");
+
+ GodotSharpBuilds.RestartBuild(this);
+ }
+
+ public void StopBuild()
+ {
+ if (!BuildExited)
+ throw new InvalidOperationException("Build is not in progress");
+
+ GodotSharpBuilds.StopBuild(this);
+ }
+
+ public override void _Ready()
+ {
+ base._Ready();
+
+ issuesList = new ItemList {SizeFlagsVertical = (int) SizeFlags.ExpandFill};
+ issuesList.Connect("item_activated", this, nameof(_IssueActivated));
+ AddChild(issuesList);
+ }
+
+ private MonoBuildTab()
+ {
+ }
+
+ public MonoBuildTab(MonoBuildInfo buildInfo)
+ {
+ BuildInfo = buildInfo;
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotSharpTools/Editor/MonoDevelopInstance.cs b/modules/mono/editor/GodotTools/GodotTools/MonoDevelopInstance.cs
index fba4a8f65c..0c8d86e799 100644
--- a/modules/mono/editor/GodotSharpTools/Editor/MonoDevelopInstance.cs
+++ b/modules/mono/editor/GodotTools/GodotTools/MonoDevelopInstance.cs
@@ -1,11 +1,11 @@
+using GodotTools.Core;
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
+using GodotTools.Internals;
-namespace GodotSharpTools.Editor
+namespace GodotTools
{
public class MonoDevelopInstance
{
@@ -15,24 +15,24 @@ namespace GodotSharpTools.Editor
VisualStudioForMac = 1
}
- readonly string solutionFile;
- readonly EditorId editorId;
+ private readonly string solutionFile;
+ private readonly EditorId editorId;
- Process process;
+ private Process process;
- public void Execute(string[] files)
+ public void Execute(params string[] files)
{
bool newWindow = process == null || process.HasExited;
- List<string> args = new List<string>();
+ var args = new List<string>();
string command;
if (Utils.OS.IsOSX())
{
- string bundleId = codeEditorBundleIds[editorId];
+ string bundleId = CodeEditorBundleIds[editorId];
- if (IsApplicationBundleInstalled(bundleId))
+ if (Internal.IsOsxAppBundleInstalled(bundleId))
{
command = "open";
@@ -47,12 +47,12 @@ namespace GodotSharpTools.Editor
}
else
{
- command = codeEditorPaths[editorId];
+ command = CodeEditorPaths[editorId];
}
}
else
{
- command = codeEditorPaths[editorId];
+ command = CodeEditorPaths[editorId];
}
args.Add("--ipc-tcp");
@@ -72,7 +72,7 @@ namespace GodotSharpTools.Editor
if (newWindow)
{
- process = Process.Start(new ProcessStartInfo()
+ process = Process.Start(new ProcessStartInfo
{
FileName = command,
Arguments = string.Join(" ", args),
@@ -81,12 +81,12 @@ namespace GodotSharpTools.Editor
}
else
{
- Process.Start(new ProcessStartInfo()
+ Process.Start(new ProcessStartInfo
{
FileName = command,
Arguments = string.Join(" ", args),
UseShellExecute = false
- });
+ })?.Dispose();
}
}
@@ -99,45 +99,42 @@ namespace GodotSharpTools.Editor
this.editorId = editorId;
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- private extern static bool IsApplicationBundleInstalled(string bundleId);
-
- static readonly IReadOnlyDictionary<EditorId, string> codeEditorPaths;
- static readonly IReadOnlyDictionary<EditorId, string> codeEditorBundleIds;
+ private static readonly IReadOnlyDictionary<EditorId, string> CodeEditorPaths;
+ private static readonly IReadOnlyDictionary<EditorId, string> CodeEditorBundleIds;
static MonoDevelopInstance()
{
if (Utils.OS.IsOSX())
{
- codeEditorPaths = new Dictionary<EditorId, string>
+ CodeEditorPaths = new Dictionary<EditorId, string>
{
// Rely on PATH
- { EditorId.MonoDevelop, "monodevelop" },
- { EditorId.VisualStudioForMac, "VisualStudio" }
+ {EditorId.MonoDevelop, "monodevelop"},
+ {EditorId.VisualStudioForMac, "VisualStudio"}
};
- codeEditorBundleIds = new Dictionary<EditorId, string>
+ CodeEditorBundleIds = new Dictionary<EditorId, string>
{
// TODO EditorId.MonoDevelop
- { EditorId.VisualStudioForMac, "com.microsoft.visual-studio" }
+ {EditorId.VisualStudioForMac, "com.microsoft.visual-studio"}
};
}
else if (Utils.OS.IsWindows())
{
- codeEditorPaths = new Dictionary<EditorId, string>
+ CodeEditorPaths = new Dictionary<EditorId, string>
{
// XamarinStudio is no longer a thing, and the latest version is quite old
// MonoDevelop is available from source only on Windows. The recommendation
// is to use Visual Studio instead. Since there are no official builds, we
// will rely on custom MonoDevelop builds being added to PATH.
- { EditorId.MonoDevelop, "MonoDevelop.exe" }
+ {EditorId.MonoDevelop, "MonoDevelop.exe"}
};
}
else if (Utils.OS.IsUnix())
{
- codeEditorPaths = new Dictionary<EditorId, string>
+ CodeEditorPaths = new Dictionary<EditorId, string>
{
// Rely on PATH
- { EditorId.MonoDevelop, "monodevelop" }
+ {EditorId.MonoDevelop, "monodevelop"}
};
}
}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs b/modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000000..f5fe85c722
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Properties/AssemblyInfo.cs
@@ -0,0 +1,26 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+// Information about this assembly is defined by the following attributes.
+// Change them to the values specific to your project.
+
+[assembly: AssemblyTitle("GodotTools")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("")]
+[assembly: AssemblyCopyright("Godot Engine contributors")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
+// The form "{Major}.{Minor}.*" will automatically update the build and revision,
+// and "{Major}.{Minor}.{Build}.*" will update just the revision.
+
+[assembly: AssemblyVersion("1.0.*")]
+
+// The following attributes are used to specify the signing key for the assembly,
+// if desired. See the Mono documentation for more information about signing.
+
+//[assembly: AssemblyDelaySign(false)]
+//[assembly: AssemblyKeyFile("")]
diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/CollectionExtensions.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/CollectionExtensions.cs
new file mode 100644
index 0000000000..3ae6c10bbf
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Utils/CollectionExtensions.cs
@@ -0,0 +1,20 @@
+using System;
+using System.Collections.Generic;
+
+namespace GodotTools.Utils
+{
+ public static class CollectionExtensions
+ {
+ public static T SelectFirstNotNull<T>(this IEnumerable<T> enumerable, Func<T, T> predicate, T orElse = null)
+ where T : class
+ {
+ foreach (T elem in enumerable)
+ {
+ if (predicate(elem) != null)
+ return elem;
+ }
+
+ return orElse;
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/Directory.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/Directory.cs
new file mode 100644
index 0000000000..c67d48b92a
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Utils/Directory.cs
@@ -0,0 +1,40 @@
+using System.IO;
+using Godot;
+
+namespace GodotTools.Utils
+{
+ public static class Directory
+ {
+ private static string GlobalizePath(this string path)
+ {
+ return ProjectSettings.GlobalizePath(path);
+ }
+
+ public static bool Exists(string path)
+ {
+ return System.IO.Directory.Exists(path.GlobalizePath());
+ }
+
+ /// Create directory recursively
+ public static DirectoryInfo CreateDirectory(string path)
+ {
+ return System.IO.Directory.CreateDirectory(path.GlobalizePath());
+ }
+
+ public static void Delete(string path, bool recursive)
+ {
+ System.IO.Directory.Delete(path.GlobalizePath(), recursive);
+ }
+
+
+ public static string[] GetDirectories(string path, string searchPattern, SearchOption searchOption)
+ {
+ return System.IO.Directory.GetDirectories(path.GlobalizePath(), searchPattern, searchOption);
+ }
+
+ public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
+ {
+ return System.IO.Directory.GetFiles(path.GlobalizePath(), searchPattern, searchOption);
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/File.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/File.cs
new file mode 100644
index 0000000000..e1e2188edb
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Utils/File.cs
@@ -0,0 +1,43 @@
+using System;
+using Godot;
+
+namespace GodotTools.Utils
+{
+ public static class File
+ {
+ private static string GlobalizePath(this string path)
+ {
+ return ProjectSettings.GlobalizePath(path);
+ }
+
+ public static void WriteAllText(string path, string contents)
+ {
+ System.IO.File.WriteAllText(path.GlobalizePath(), contents);
+ }
+
+ public static bool Exists(string path)
+ {
+ return System.IO.File.Exists(path.GlobalizePath());
+ }
+
+ public static DateTime GetLastWriteTime(string path)
+ {
+ return System.IO.File.GetLastWriteTime(path.GlobalizePath());
+ }
+
+ public static void Delete(string path)
+ {
+ System.IO.File.Delete(path.GlobalizePath());
+ }
+
+ public static void Copy(string sourceFileName, string destFileName)
+ {
+ System.IO.File.Copy(sourceFileName.GlobalizePath(), destFileName.GlobalizePath(), overwrite: true);
+ }
+
+ public static byte[] ReadAllBytes(string path)
+ {
+ return System.IO.File.ReadAllBytes(path.GlobalizePath());
+ }
+ }
+}
diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs
new file mode 100644
index 0000000000..e48b1115db
--- /dev/null
+++ b/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs
@@ -0,0 +1,127 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Runtime.CompilerServices;
+
+namespace GodotTools.Utils
+{
+ public static class OS
+ {
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ extern static string GetPlatformName();
+
+ const string HaikuName = "Haiku";
+ const string OSXName = "OSX";
+ const string ServerName = "Server";
+ const string UWPName = "UWP";
+ const string WindowsName = "Windows";
+ const string X11Name = "X11";
+
+ public static bool IsHaiku()
+ {
+ return HaikuName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ public static bool IsOSX()
+ {
+ return OSXName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ public static bool IsServer()
+ {
+ return ServerName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ public static bool IsUWP()
+ {
+ return UWPName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ public static bool IsWindows()
+ {
+ return WindowsName.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ public static bool IsX11()
+ {
+ return X11Name.Equals(GetPlatformName(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static bool? _isUnixCache;
+ private static readonly string[] UnixPlatforms = {HaikuName, OSXName, ServerName, X11Name};
+
+ public static bool IsUnix()
+ {
+ if (_isUnixCache.HasValue)
+ return _isUnixCache.Value;
+
+ string osName = GetPlatformName();
+ _isUnixCache = UnixPlatforms.Any(p => p.Equals(osName, StringComparison.OrdinalIgnoreCase));
+ return _isUnixCache.Value;
+ }
+
+ public static char PathSep => IsWindows() ? ';' : ':';
+
+ public static string PathWhich(string name)
+ {
+ string[] windowsExts = IsWindows() ? Environment.GetEnvironmentVariable("PATHEXT")?.Split(PathSep) : null;
+ string[] pathDirs = Environment.GetEnvironmentVariable("PATH")?.Split(PathSep);
+
+ var searchDirs = new List<string>();
+
+ if (pathDirs != null)
+ searchDirs.AddRange(pathDirs);
+
+ searchDirs.Add(System.IO.Directory.GetCurrentDirectory()); // last in the list
+
+ foreach (var dir in searchDirs)
+ {
+ string path = Path.Combine(dir, name);
+
+ if (IsWindows() && windowsExts != null)
+ {
+ foreach (var extension in windowsExts)
+ {
+ string pathWithExtension = path + extension;
+
+ if (File.Exists(pathWithExtension))
+ return pathWithExtension;
+ }
+ }
+ else
+ {
+ if (File.Exists(path))
+ return path;
+ }
+ }
+
+ return null;
+ }
+
+ public static void RunProcess(string command, IEnumerable<string> arguments)
+ {
+ string CmdLineArgsToString(IEnumerable<string> args)
+ {
+ return string.Join(" ", args.Select(arg => arg.Contains(" ") ? $@"""{arg}""" : arg));
+ }
+
+ ProcessStartInfo startInfo = new ProcessStartInfo(command, CmdLineArgsToString(arguments))
+ {
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ UseShellExecute = false
+ };
+
+ using (Process process = Process.Start(startInfo))
+ {
+ if (process == null)
+ throw new Exception("No process was started");
+
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+ }
+ }
+ }
+}
diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp
index cd7774e7a1..45037bf637 100644
--- a/modules/mono/editor/bindings_generator.cpp
+++ b/modules/mono/editor/bindings_generator.cpp
@@ -861,37 +861,33 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
p_output.append("\n#pragma warning restore CS1591\n");
}
-Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir, DotNetSolution &r_solution) {
-
- String proj_dir = p_solution_dir.plus_file(CORE_API_ASSEMBLY_NAME);
+Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir, Vector<String> &r_compile_items) {
DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
- if (!DirAccess::exists(proj_dir)) {
- Error err = da->make_dir_recursive(proj_dir);
+ if (!DirAccess::exists(p_proj_dir)) {
+ Error err = da->make_dir_recursive(p_proj_dir);
ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
}
- da->change_dir(proj_dir);
+ da->change_dir(p_proj_dir);
da->make_dir("Core");
da->make_dir("ObjectType");
- String core_dir = path_join(proj_dir, "Core");
- String obj_type_dir = path_join(proj_dir, "ObjectType");
-
- Vector<String> compile_items;
+ String core_dir = path::join(p_proj_dir, "Core");
+ String obj_type_dir = path::join(p_proj_dir, "ObjectType");
// Generate source file for global scope constants and enums
{
StringBuilder constants_source;
_generate_global_constants(constants_source);
- String output_file = path_join(core_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_constants.cs");
+ String output_file = path::join(core_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_constants.cs");
Error save_err = _save_file(output_file, constants_source);
if (save_err != OK)
return save_err;
- compile_items.push_back(output_file);
+ r_compile_items.push_back(output_file);
}
for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
@@ -900,7 +896,7 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir,
if (itype.api_type == ClassDB::API_EDITOR)
continue;
- String output_file = path_join(obj_type_dir, itype.proxy_name + ".cs");
+ String output_file = path::join(obj_type_dir, itype.proxy_name + ".cs");
Error err = _generate_cs_type(itype, output_file);
if (err == ERR_SKIP)
@@ -909,19 +905,19 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir,
if (err != OK)
return err;
- compile_items.push_back(output_file);
+ r_compile_items.push_back(output_file);
}
// Generate sources from compressed files
- Map<String, CompressedFile> compressed_files;
+ Map<String, GodotCsCompressedFile> compressed_files;
get_compressed_files(compressed_files);
- for (Map<String, CompressedFile>::Element *E = compressed_files.front(); E; E = E->next()) {
+ for (Map<String, GodotCsCompressedFile>::Element *E = compressed_files.front(); E; E = E->next()) {
const String &file_name = E->key();
- const CompressedFile &file_data = E->value();
+ const GodotCsCompressedFile &file_data = E->value();
- String output_file = path_join(core_dir, file_name);
+ String output_file = path::join(core_dir, file_name);
Vector<uint8_t> data;
data.resize(file_data.uncompressed_size);
@@ -939,7 +935,7 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir,
file->store_buffer(data.ptr(), data.size());
file->close();
- compile_items.push_back(output_file);
+ r_compile_items.push_back(output_file);
}
StringBuilder cs_icalls_content;
@@ -975,49 +971,33 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_solution_dir,
cs_icalls_content.append(INDENT1 CLOSE_BLOCK CLOSE_BLOCK);
- String internal_methods_file = path_join(core_dir, BINDINGS_CLASS_NATIVECALLS ".cs");
+ String internal_methods_file = path::join(core_dir, BINDINGS_CLASS_NATIVECALLS ".cs");
Error err = _save_file(internal_methods_file, cs_icalls_content);
if (err != OK)
return err;
- compile_items.push_back(internal_methods_file);
-
- String guid = CSharpProject::generate_core_api_project(proj_dir, compile_items);
-
- DotNetSolution::ProjectInfo proj_info;
- proj_info.guid = guid;
- proj_info.relpath = String(CORE_API_ASSEMBLY_NAME).plus_file(CORE_API_ASSEMBLY_NAME ".csproj");
- proj_info.configs.push_back("Debug");
- proj_info.configs.push_back("Release");
-
- r_solution.add_new_project(CORE_API_ASSEMBLY_NAME, proj_info);
-
- _log("The solution and C# project for the Core API was generated successfully\n");
+ r_compile_items.push_back(internal_methods_file);
return OK;
}
-Error BindingsGenerator::generate_cs_editor_project(const String &p_solution_dir, DotNetSolution &r_solution) {
-
- String proj_dir = p_solution_dir.plus_file(EDITOR_API_ASSEMBLY_NAME);
+Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir, Vector<String> &r_compile_items) {
DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
- if (!DirAccess::exists(proj_dir)) {
- Error err = da->make_dir_recursive(proj_dir);
+ if (!DirAccess::exists(p_proj_dir)) {
+ Error err = da->make_dir_recursive(p_proj_dir);
ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
}
- da->change_dir(proj_dir);
+ da->change_dir(p_proj_dir);
da->make_dir("Core");
da->make_dir("ObjectType");
- String core_dir = path_join(proj_dir, "Core");
- String obj_type_dir = path_join(proj_dir, "ObjectType");
-
- Vector<String> compile_items;
+ String core_dir = path::join(p_proj_dir, "Core");
+ String obj_type_dir = path::join(p_proj_dir, "ObjectType");
for (OrderedHashMap<StringName, TypeInterface>::Element E = obj_types.front(); E; E = E.next()) {
const TypeInterface &itype = E.get();
@@ -1025,7 +1005,7 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_solution_dir
if (itype.api_type != ClassDB::API_EDITOR)
continue;
- String output_file = path_join(obj_type_dir, itype.proxy_name + ".cs");
+ String output_file = path::join(obj_type_dir, itype.proxy_name + ".cs");
Error err = _generate_cs_type(itype, output_file);
if (err == ERR_SKIP)
@@ -1034,7 +1014,7 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_solution_dir
if (err != OK)
return err;
- compile_items.push_back(output_file);
+ r_compile_items.push_back(output_file);
}
StringBuilder cs_icalls_content;
@@ -1071,64 +1051,62 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_solution_dir
cs_icalls_content.append(INDENT1 CLOSE_BLOCK CLOSE_BLOCK);
- String internal_methods_file = path_join(core_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs");
+ String internal_methods_file = path::join(core_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs");
Error err = _save_file(internal_methods_file, cs_icalls_content);
if (err != OK)
return err;
- compile_items.push_back(internal_methods_file);
-
- String guid = CSharpProject::generate_editor_api_project(proj_dir, "../" CORE_API_ASSEMBLY_NAME "/" CORE_API_ASSEMBLY_NAME ".csproj", compile_items);
-
- DotNetSolution::ProjectInfo proj_info;
- proj_info.guid = guid;
- proj_info.relpath = String(EDITOR_API_ASSEMBLY_NAME).plus_file(EDITOR_API_ASSEMBLY_NAME ".csproj");
- proj_info.configs.push_back("Debug");
- proj_info.configs.push_back("Release");
-
- r_solution.add_new_project(EDITOR_API_ASSEMBLY_NAME, proj_info);
-
- _log("The solution and C# project for the Editor API was generated successfully\n");
+ r_compile_items.push_back(internal_methods_file);
return OK;
}
Error BindingsGenerator::generate_cs_api(const String &p_output_dir) {
+ String output_dir = path::abspath(path::realpath(p_output_dir));
+
DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
ERR_FAIL_COND_V(!da, ERR_CANT_CREATE);
- if (!DirAccess::exists(p_output_dir)) {
- Error err = da->make_dir_recursive(p_output_dir);
+ if (!DirAccess::exists(output_dir)) {
+ Error err = da->make_dir_recursive(output_dir);
ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
}
- DotNetSolution solution(API_SOLUTION_NAME);
+ Error proj_err;
- if (!solution.set_path(p_output_dir))
- return ERR_FILE_NOT_FOUND;
+ // Generate GodotSharp source files
- Error proj_err;
+ String core_proj_dir = output_dir.plus_file(CORE_API_ASSEMBLY_NAME);
+ Vector<String> core_compile_items;
- proj_err = generate_cs_core_project(p_output_dir, solution);
+ proj_err = generate_cs_core_project(core_proj_dir, core_compile_items);
if (proj_err != OK) {
ERR_PRINT("Generation of the Core API C# project failed");
return proj_err;
}
- proj_err = generate_cs_editor_project(p_output_dir, solution);
+ // Generate GodotSharpEditor source files
+
+ String editor_proj_dir = output_dir.plus_file(EDITOR_API_ASSEMBLY_NAME);
+ Vector<String> editor_compile_items;
+
+ proj_err = generate_cs_editor_project(editor_proj_dir, editor_compile_items);
if (proj_err != OK) {
ERR_PRINT("Generation of the Editor API C# project failed");
return proj_err;
}
- Error sln_error = solution.save();
- if (sln_error != OK) {
- ERR_PRINT("Failed to save API solution");
- return sln_error;
+ // Generate solution
+
+ if (!CSharpProject::generate_api_solution(output_dir,
+ core_proj_dir, core_compile_items, editor_proj_dir, editor_compile_items)) {
+ return ERR_CANT_CREATE;
}
+ _log("The solution for the Godot API was generated successfully\n");
+
return OK;
}
@@ -1311,8 +1289,9 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str
output.append(MEMBER_BEGIN "private static Godot.Object singleton;\n");
output.append(MEMBER_BEGIN "public static Godot.Object Singleton\n" INDENT2 "{\n" INDENT3
"get\n" INDENT3 "{\n" INDENT4 "if (singleton == null)\n" INDENT5
- "singleton = Engine.GetSingleton(" BINDINGS_NATIVE_NAME_FIELD ");\n" INDENT4
- "return singleton;\n" INDENT3 "}\n" INDENT2 "}\n");
+ "singleton = Engine.GetSingleton(typeof(");
+ output.append(itype.proxy_name);
+ output.append(").Name);\n" INDENT4 "return singleton;\n" INDENT3 "}\n" INDENT2 "}\n");
output.append(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \"");
output.append(itype.name);
@@ -1883,7 +1862,7 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) {
output.append("\n#endif // MONO_GLUE_ENABLED\n");
- Error save_err = _save_file(path_join(p_output_dir, "mono_glue.gen.cpp"), output);
+ Error save_err = _save_file(path::join(p_output_dir, "mono_glue.gen.cpp"), output);
if (save_err != OK)
return save_err;
@@ -2213,7 +2192,7 @@ void BindingsGenerator::_populate_object_type_interfaces() {
itype.base_name = ClassDB::get_parent_class(type_cname);
itype.is_singleton = Engine::get_singleton()->has_singleton(itype.proxy_name);
- itype.is_instantiable = ClassDB::can_instance(type_cname) && !itype.is_singleton;
+ itype.is_instantiable = class_info->creation_func && !itype.is_singleton;
itype.is_reference = ClassDB::is_parent_class(type_cname, name_cache.type_Reference);
itype.memory_own = itype.is_reference;
@@ -2347,6 +2326,13 @@ void BindingsGenerator::_populate_object_type_interfaces() {
imethod.return_type.is_enum = true;
} else if (return_info.class_name != StringName()) {
imethod.return_type.cname = return_info.class_name;
+ if (!imethod.is_virtual && ClassDB::is_parent_class(return_info.class_name, name_cache.type_Reference) && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE) {
+ /* clang-format off */
+ ERR_PRINTS("Return type is reference but hint is not " _STR(PROPERTY_HINT_RESOURCE_TYPE) "."
+ " Are you returning a reference type by pointer? Method: " + itype.name + "." + imethod.name);
+ /* clang-format on */
+ ERR_FAIL();
+ }
} else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
imethod.return_type.cname = return_info.hint_string;
} else if (return_info.type == Variant::NIL && return_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
@@ -2536,13 +2522,8 @@ void BindingsGenerator::_default_argument_from_variant(const Variant &p_val, Arg
switch (p_val.get_type()) {
case Variant::NIL:
- if (ClassDB::class_exists(r_iarg.type.cname)) {
- // Object type
- r_iarg.default_argument = "null";
- } else {
- // Variant
- r_iarg.default_argument = "null";
- }
+ // Either Object type or Variant
+ r_iarg.default_argument = "null";
break;
// Atomic types
case Variant::BOOL:
@@ -3023,36 +3004,49 @@ void BindingsGenerator::_initialize() {
void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) {
const int NUM_OPTIONS = 2;
- String mono_glue_option = "--generate-mono-glue";
- String cs_api_option = "--generate-cs-api";
+ String generate_all_glue_option = "--generate-mono-glue";
+ String generate_cs_glue_option = "--generate-mono-cs-glue";
+ String generate_cpp_glue_option = "--generate-mono-cpp-glue";
- String mono_glue_path;
- String cs_api_path;
+ String glue_dir_path;
+ String cs_dir_path;
+ String cpp_dir_path;
int options_left = NUM_OPTIONS;
const List<String>::Element *elem = p_cmdline_args.front();
while (elem && options_left) {
- if (elem->get() == mono_glue_option) {
+ if (elem->get() == generate_all_glue_option) {
+ const List<String>::Element *path_elem = elem->next();
+
+ if (path_elem) {
+ glue_dir_path = path_elem->get();
+ elem = elem->next();
+ } else {
+ ERR_PRINTS(generate_all_glue_option + ": No output directory specified (expected path to {GODOT_ROOT}/modules/mono/glue)");
+ }
+
+ --options_left;
+ } else if (elem->get() == generate_cs_glue_option) {
const List<String>::Element *path_elem = elem->next();
if (path_elem) {
- mono_glue_path = path_elem->get();
+ cs_dir_path = path_elem->get();
elem = elem->next();
} else {
- ERR_PRINTS(mono_glue_option + ": No output directory specified");
+ ERR_PRINTS(generate_cs_glue_option + ": No output directory specified");
}
--options_left;
- } else if (elem->get() == cs_api_option) {
+ } else if (elem->get() == generate_cpp_glue_option) {
const List<String>::Element *path_elem = elem->next();
if (path_elem) {
- cs_api_path = path_elem->get();
+ cpp_dir_path = path_elem->get();
elem = elem->next();
} else {
- ERR_PRINTS(cs_api_option + ": No output directory specified");
+ ERR_PRINTS(generate_cpp_glue_option + ": No output directory specified");
}
--options_left;
@@ -3061,18 +3055,26 @@ void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args)
elem = elem->next();
}
- if (mono_glue_path.length() || cs_api_path.length()) {
+ if (glue_dir_path.length() || cs_dir_path.length() || cpp_dir_path.length()) {
BindingsGenerator bindings_generator;
bindings_generator.set_log_print_enabled(true);
- if (mono_glue_path.length()) {
- if (bindings_generator.generate_glue(mono_glue_path) != OK)
- ERR_PRINTS(mono_glue_option + ": Failed to generate mono glue");
+ if (glue_dir_path.length()) {
+ if (bindings_generator.generate_glue(glue_dir_path) != OK)
+ ERR_PRINTS(generate_all_glue_option + ": Failed to generate the C++ glue");
+
+ if (bindings_generator.generate_cs_api(glue_dir_path.plus_file("Managed/Generated")) != OK)
+ ERR_PRINTS(generate_all_glue_option + ": Failed to generate the C# API");
+ }
+
+ if (cs_dir_path.length()) {
+ if (bindings_generator.generate_cs_api(cs_dir_path) != OK)
+ ERR_PRINTS(generate_cs_glue_option + ": Failed to generate the C# API");
}
- if (cs_api_path.length()) {
- if (bindings_generator.generate_cs_api(cs_api_path) != OK)
- ERR_PRINTS(cs_api_option + ": Failed to generate the C# API");
+ if (cpp_dir_path.length()) {
+ if (bindings_generator.generate_glue(cpp_dir_path) != OK)
+ ERR_PRINTS(generate_cpp_glue_option + ": Failed to generate the C++ glue");
}
// Exit once done
diff --git a/modules/mono/editor/bindings_generator.h b/modules/mono/editor/bindings_generator.h
index ffc73a7e3e..8be51a6c55 100644
--- a/modules/mono/editor/bindings_generator.h
+++ b/modules/mono/editor/bindings_generator.h
@@ -33,7 +33,6 @@
#include "core/class_db.h"
#include "core/string_builder.h"
-#include "dotnet_solution.h"
#include "editor/doc/doc_data.h"
#include "editor/editor_help.h"
@@ -614,12 +613,13 @@ class BindingsGenerator {
void _initialize();
public:
- Error generate_cs_core_project(const String &p_solution_dir, DotNetSolution &r_solution);
- Error generate_cs_editor_project(const String &p_solution_dir, DotNetSolution &r_solution);
+ Error generate_cs_core_project(const String &p_proj_dir, Vector<String> &r_compile_files);
+ Error generate_cs_editor_project(const String &p_proj_dir, Vector<String> &r_compile_items);
Error generate_cs_api(const String &p_output_dir);
Error generate_glue(const String &p_output_dir);
- void set_log_print_enabled(bool p_enabled) { log_print_enabled = p_enabled; }
+ _FORCE_INLINE_ bool is_log_print_enabled() { return log_print_enabled; }
+ _FORCE_INLINE_ void set_log_print_enabled(bool p_enabled) { log_print_enabled = p_enabled; }
static uint32_t get_version();
diff --git a/modules/mono/editor/csharp_project.cpp b/modules/mono/editor/csharp_project.cpp
index fe79286556..d88b08c646 100644
--- a/modules/mono/editor/csharp_project.cpp
+++ b/modules/mono/editor/csharp_project.cpp
@@ -44,66 +44,54 @@
namespace CSharpProject {
-String generate_core_api_project(const String &p_dir, const Vector<String> &p_files) {
-
- _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN)
-
- GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectGenerator");
-
- Variant dir = p_dir;
- Variant compile_items = p_files;
- const Variant *args[2] = { &dir, &compile_items };
+bool generate_api_solution_impl(const String &p_solution_dir, const String &p_core_proj_dir, const Vector<String> &p_core_compile_items,
+ const String &p_editor_proj_dir, const Vector<String> &p_editor_compile_items,
+ GDMonoAssembly *p_tools_project_editor_assembly) {
+
+ GDMonoClass *klass = p_tools_project_editor_assembly->get_class("GodotTools.ProjectEditor", "ApiSolutionGenerator");
+
+ Variant solution_dir = p_solution_dir;
+ Variant core_proj_dir = p_core_proj_dir;
+ Variant core_compile_items = p_core_compile_items;
+ Variant editor_proj_dir = p_editor_proj_dir;
+ Variant editor_compile_items = p_editor_compile_items;
+ const Variant *args[5] = { &solution_dir, &core_proj_dir, &core_compile_items, &editor_proj_dir, &editor_compile_items };
MonoException *exc = NULL;
- MonoObject *ret = klass->get_method("GenCoreApiProject", 2)->invoke(NULL, args, &exc);
+ klass->get_method("GenerateApiSolution", 5)->invoke(NULL, args, &exc);
if (exc) {
GDMonoUtils::debug_print_unhandled_exception(exc);
- ERR_FAIL_V(String());
+ ERR_FAIL_V(false);
}
- return ret ? GDMonoMarshal::mono_string_to_godot((MonoString *)ret) : String();
+ return true;
}
-String generate_editor_api_project(const String &p_dir, const String &p_core_proj_path, const Vector<String> &p_files) {
-
- _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN)
-
- GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectGenerator");
-
- Variant dir = p_dir;
- Variant core_proj_path = p_core_proj_path;
- Variant compile_items = p_files;
- const Variant *args[3] = { &dir, &core_proj_path, &compile_items };
- MonoException *exc = NULL;
- MonoObject *ret = klass->get_method("GenEditorApiProject", 3)->invoke(NULL, args, &exc);
-
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- ERR_FAIL_V(String());
- }
-
- return ret ? GDMonoMarshal::mono_string_to_godot((MonoString *)ret) : String();
-}
+bool generate_api_solution(const String &p_solution_dir, const String &p_core_proj_dir, const Vector<String> &p_core_compile_items,
+ const String &p_editor_proj_dir, const Vector<String> &p_editor_compile_items) {
-String generate_game_project(const String &p_dir, const String &p_name, const Vector<String> &p_files) {
+ if (GDMono::get_singleton()->get_tools_project_editor_assembly()) {
+ return generate_api_solution_impl(p_solution_dir, p_core_proj_dir, p_core_compile_items,
+ p_editor_proj_dir, p_editor_compile_items,
+ GDMono::get_singleton()->get_tools_project_editor_assembly());
+ } else {
+ MonoDomain *temp_domain = GDMonoUtils::create_domain("GodotEngine.ApiSolutionGenerationDomain");
+ CRASH_COND(temp_domain == NULL);
+ _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(temp_domain);
- _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN)
+ _GDMONO_SCOPE_DOMAIN_(temp_domain);
- GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectGenerator");
+ GDMonoAssembly *tools_project_editor_assembly = NULL;
- Variant dir = p_dir;
- Variant name = p_name;
- Variant compile_items = p_files;
- const Variant *args[3] = { &dir, &name, &compile_items };
- MonoException *exc = NULL;
- MonoObject *ret = klass->get_method("GenGameProject", 3)->invoke(NULL, args, &exc);
+ if (!GDMono::get_singleton()->load_assembly("GodotTools.ProjectEditor", &tools_project_editor_assembly)) {
+ ERR_EXPLAIN("Failed to load assembly: 'GodotTools.ProjectEditor'");
+ ERR_FAIL_V(false);
+ }
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- ERR_FAIL_V(String());
+ return generate_api_solution_impl(p_solution_dir, p_core_proj_dir, p_core_compile_items,
+ p_editor_proj_dir, p_editor_compile_items,
+ tools_project_editor_assembly);
}
-
- return ret ? GDMonoMarshal::mono_string_to_godot((MonoString *)ret) : String();
}
void add_item(const String &p_project_path, const String &p_item_type, const String &p_include) {
@@ -111,9 +99,9 @@ void add_item(const String &p_project_path, const String &p_item_type, const Str
if (!GLOBAL_DEF("mono/project/auto_update_project", true))
return;
- _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN)
+ GDMonoAssembly *tools_project_editor_assembly = GDMono::get_singleton()->get_tools_project_editor_assembly();
- GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectUtils");
+ GDMonoClass *klass = tools_project_editor_assembly->get_class("GodotTools.ProjectEditor", "ProjectUtils");
Variant project_path = p_project_path;
Variant item_type = p_item_type;
@@ -128,126 +116,4 @@ void add_item(const String &p_project_path, const String &p_item_type, const Str
}
}
-Error generate_scripts_metadata(const String &p_project_path, const String &p_output_path) {
-
- _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN)
-
- if (FileAccess::exists(p_output_path)) {
- DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- Error rm_err = da->remove(p_output_path);
-
- ERR_EXPLAIN("Failed to remove old scripts metadata file");
- ERR_FAIL_COND_V(rm_err != OK, rm_err);
- }
-
- GDMonoClass *project_utils = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Project", "ProjectUtils");
-
- void *args[2] = {
- GDMonoMarshal::mono_string_from_godot(p_project_path),
- GDMonoMarshal::mono_string_from_godot("Compile")
- };
-
- MonoException *exc = NULL;
- MonoArray *ret = (MonoArray *)project_utils->get_method("GetIncludeFiles", 2)->invoke_raw(NULL, args, &exc);
-
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- ERR_FAIL_V(FAILED);
- }
-
- PoolStringArray project_files = GDMonoMarshal::mono_array_to_PoolStringArray(ret);
- PoolStringArray::Read r = project_files.read();
-
- Dictionary old_dict = CSharpLanguage::get_singleton()->get_scripts_metadata_or_nothing();
- Dictionary new_dict;
-
- for (int i = 0; i < project_files.size(); i++) {
- const String &project_file = ("res://" + r[i]).simplify_path();
-
- uint64_t modified_time = FileAccess::get_modified_time(project_file);
-
- const Variant *old_file_var = old_dict.getptr(project_file);
- if (old_file_var) {
- Dictionary old_file_dict = old_file_var->operator Dictionary();
-
- if (old_file_dict["modified_time"].operator uint64_t() == modified_time) {
- // No changes so no need to parse again
- new_dict[project_file] = old_file_dict;
- continue;
- }
- }
-
- ScriptClassParser scp;
- Error err = scp.parse_file(project_file);
- if (err != OK) {
- ERR_PRINTS("Parse error: " + scp.get_error());
- ERR_EXPLAIN("Failed to determine namespace and class for script: " + project_file);
- ERR_FAIL_V(err);
- }
-
- Vector<ScriptClassParser::ClassDecl> classes = scp.get_classes();
-
- bool found = false;
- Dictionary class_dict;
-
- String search_name = project_file.get_file().get_basename();
-
- for (int j = 0; j < classes.size(); j++) {
- const ScriptClassParser::ClassDecl &class_decl = classes[j];
-
- if (class_decl.base.size() == 0)
- continue; // Does not inherit nor implement anything, so it can't be a script class
-
- String class_cmp;
-
- if (class_decl.nested) {
- class_cmp = class_decl.name.get_slice(".", class_decl.name.get_slice_count(".") - 1);
- } else {
- class_cmp = class_decl.name;
- }
-
- if (class_cmp != search_name)
- continue;
-
- class_dict["namespace"] = class_decl.namespace_;
- class_dict["class_name"] = class_decl.name;
- class_dict["nested"] = class_decl.nested;
-
- found = true;
- break;
- }
-
- if (found) {
- Dictionary file_dict;
- file_dict["modified_time"] = modified_time;
- file_dict["class"] = class_dict;
- new_dict[project_file] = file_dict;
- }
- }
-
- if (new_dict.size()) {
- String json = JSON::print(new_dict, "", false);
-
- String base_dir = p_output_path.get_base_dir();
-
- if (!DirAccess::exists(base_dir)) {
- DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
-
- Error err = da->make_dir_recursive(base_dir);
- ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
- }
-
- Error ferr;
- FileAccess *f = FileAccess::open(p_output_path, FileAccess::WRITE, &ferr);
- ERR_EXPLAIN("Cannot open file for writing: " + p_output_path);
- ERR_FAIL_COND_V(ferr != OK, ferr);
- f->store_string(json);
- f->flush();
- f->close();
- memdelete(f);
- }
-
- return OK;
-}
-
} // namespace CSharpProject
diff --git a/modules/mono/editor/csharp_project.h b/modules/mono/editor/csharp_project.h
index 3d5a65f8da..b42762cea2 100644
--- a/modules/mono/editor/csharp_project.h
+++ b/modules/mono/editor/csharp_project.h
@@ -35,14 +35,11 @@
namespace CSharpProject {
-String generate_core_api_project(const String &p_dir, const Vector<String> &p_files = Vector<String>());
-String generate_editor_api_project(const String &p_dir, const String &p_core_dll_path, const Vector<String> &p_files = Vector<String>());
-String generate_game_project(const String &p_dir, const String &p_name, const Vector<String> &p_files = Vector<String>());
+bool generate_api_solution(const String &p_solution_dir, const String &p_core_proj_dir, const Vector<String> &p_core_compile_items,
+ const String &p_editor_proj_dir, const Vector<String> &p_editor_compile_items);
void add_item(const String &p_project_path, const String &p_item_type, const String &p_include);
-Error generate_scripts_metadata(const String &p_project_path, const String &p_output_path);
-
} // namespace CSharpProject
#endif // CSHARP_PROJECT_H
diff --git a/modules/mono/editor/dotnet_solution.cpp b/modules/mono/editor/dotnet_solution.cpp
deleted file mode 100644
index 324752cafc..0000000000
--- a/modules/mono/editor/dotnet_solution.cpp
+++ /dev/null
@@ -1,140 +0,0 @@
-/*************************************************************************/
-/* dotnet_solution.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "dotnet_solution.h"
-
-#include "core/os/dir_access.h"
-#include "core/os/file_access.h"
-
-#include "../utils/path_utils.h"
-#include "../utils/string_utils.h"
-#include "csharp_project.h"
-
-#define SOLUTION_TEMPLATE \
- "Microsoft Visual Studio Solution File, Format Version 12.00\n" \
- "# Visual Studio 2012\n" \
- "%0\n" \
- "Global\n" \
- "\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n" \
- "%1\n" \
- "\tEndGlobalSection\n" \
- "\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n" \
- "%2\n" \
- "\tEndGlobalSection\n" \
- "EndGlobal\n"
-
-#define PROJECT_DECLARATION "Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"%0\", \"%1\", \"{%2}\"\nEndProject"
-
-#define SOLUTION_PLATFORMS_CONFIG "\t%0|Any CPU = %0|Any CPU"
-
-#define PROJECT_PLATFORMS_CONFIG \
- "\t\t{%0}.%1|Any CPU.ActiveCfg = %1|Any CPU\n" \
- "\t\t{%0}.%1|Any CPU.Build.0 = %1|Any CPU"
-
-void DotNetSolution::add_new_project(const String &p_name, const ProjectInfo &p_project_info) {
- projects[p_name] = p_project_info;
-}
-
-bool DotNetSolution::has_project(const String &p_name) const {
- return projects.find(p_name) != NULL;
-}
-
-const DotNetSolution::ProjectInfo &DotNetSolution::get_project_info(const String &p_name) const {
- return projects[p_name];
-}
-
-bool DotNetSolution::remove_project(const String &p_name) {
- return projects.erase(p_name);
-}
-
-Error DotNetSolution::save() {
- bool dir_exists = DirAccess::exists(path);
- ERR_EXPLAIN("The directory does not exist.");
- ERR_FAIL_COND_V(!dir_exists, ERR_FILE_NOT_FOUND);
-
- String projs_decl;
- String sln_platform_cfg;
- String proj_platform_cfg;
-
- for (Map<String, ProjectInfo>::Element *E = projects.front(); E; E = E->next()) {
- const String &name = E->key();
- const ProjectInfo &proj_info = E->value();
-
- bool is_front = E == projects.front();
-
- if (!is_front)
- projs_decl += "\n";
-
- projs_decl += sformat(PROJECT_DECLARATION, name, proj_info.relpath.replace("/", "\\"), proj_info.guid);
-
- for (int i = 0; i < proj_info.configs.size(); i++) {
- const String &config = proj_info.configs[i];
-
- if (i != 0 || !is_front) {
- sln_platform_cfg += "\n";
- proj_platform_cfg += "\n";
- }
-
- sln_platform_cfg += sformat(SOLUTION_PLATFORMS_CONFIG, config);
- proj_platform_cfg += sformat(PROJECT_PLATFORMS_CONFIG, proj_info.guid, config);
- }
- }
-
- String content = sformat(SOLUTION_TEMPLATE, projs_decl, sln_platform_cfg, proj_platform_cfg);
-
- FileAccess *file = FileAccess::open(path_join(path, name + ".sln"), FileAccess::WRITE);
- ERR_FAIL_NULL_V(file, ERR_FILE_CANT_WRITE);
- file->store_string(content);
- file->close();
- memdelete(file);
-
- return OK;
-}
-
-bool DotNetSolution::set_path(const String &p_existing_path) {
- if (p_existing_path.is_abs_path()) {
- path = p_existing_path;
- } else {
- String abspath;
- if (!rel_path_to_abs(p_existing_path, abspath))
- return false;
- path = abspath;
- }
-
- return true;
-}
-
-String DotNetSolution::get_path() {
- return path;
-}
-
-DotNetSolution::DotNetSolution(const String &p_name) {
- name = p_name;
-}
diff --git a/modules/mono/editor/editor_internal_calls.cpp b/modules/mono/editor/editor_internal_calls.cpp
new file mode 100644
index 0000000000..0014aaca70
--- /dev/null
+++ b/modules/mono/editor/editor_internal_calls.cpp
@@ -0,0 +1,427 @@
+/*************************************************************************/
+/* editor_internal_calls.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "editor_internal_calls.h"
+
+#include "core/os/os.h"
+#include "core/version.h"
+#include "editor/editor_node.h"
+#include "editor/plugins/script_editor_plugin.h"
+#include "editor/script_editor_debugger.h"
+#include "main/main.h"
+
+#include "../csharp_script.h"
+#include "../glue/cs_glue_version.gen.h"
+#include "../godotsharp_dirs.h"
+#include "../mono_gd/gd_mono_marshal.h"
+#include "../utils/osx_utils.h"
+#include "bindings_generator.h"
+#include "godotsharp_export.h"
+#include "script_class_parser.h"
+
+MonoString *godot_icall_GodotSharpDirs_ResDataDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_data_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_ResMetadataDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_metadata_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_ResAssembliesBaseDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_assemblies_base_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_ResAssembliesDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_assemblies_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_ResConfigDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_config_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_ResTempDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_temp_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_ResTempAssembliesBaseDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_temp_assemblies_base_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_ResTempAssembliesDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_res_temp_assemblies_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_MonoUserDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_mono_user_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_MonoLogsDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_mono_logs_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_MonoSolutionsDir() {
+#ifdef TOOLS_ENABLED
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_mono_solutions_dir());
+#else
+ return NULL;
+#endif
+}
+
+MonoString *godot_icall_GodotSharpDirs_BuildLogsDirs() {
+#ifdef TOOLS_ENABLED
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_build_logs_dir());
+#else
+ return NULL;
+#endif
+}
+
+MonoString *godot_icall_GodotSharpDirs_ProjectSlnPath() {
+#ifdef TOOLS_ENABLED
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_project_sln_path());
+#else
+ return NULL;
+#endif
+}
+
+MonoString *godot_icall_GodotSharpDirs_ProjectCsProjPath() {
+#ifdef TOOLS_ENABLED
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_project_csproj_path());
+#else
+ return NULL;
+#endif
+}
+
+MonoString *godot_icall_GodotSharpDirs_DataEditorToolsDir() {
+#ifdef TOOLS_ENABLED
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_editor_tools_dir());
+#else
+ return NULL;
+#endif
+}
+
+MonoString *godot_icall_GodotSharpDirs_DataEditorPrebuiltApiDir() {
+#ifdef TOOLS_ENABLED
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_editor_prebuilt_api_dir());
+#else
+ return NULL;
+#endif
+}
+
+MonoString *godot_icall_GodotSharpDirs_DataMonoEtcDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_mono_etc_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_DataMonoLibDir() {
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_mono_lib_dir());
+}
+
+MonoString *godot_icall_GodotSharpDirs_DataMonoBinDir() {
+#ifdef WINDOWS_ENABLED
+ return GDMonoMarshal::mono_string_from_godot(GodotSharpDirs::get_data_mono_bin_dir());
+#else
+ return NULL;
+#endif
+}
+
+void godot_icall_EditorProgress_Create(MonoString *p_task, MonoString *p_label, int32_t p_amount, MonoBoolean p_can_cancel) {
+ String task = GDMonoMarshal::mono_string_to_godot(p_task);
+ String label = GDMonoMarshal::mono_string_to_godot(p_label);
+ EditorNode::progress_add_task(task, label, p_amount, (bool)p_can_cancel);
+}
+
+void godot_icall_EditorProgress_Dispose(MonoString *p_task) {
+ String task = GDMonoMarshal::mono_string_to_godot(p_task);
+ EditorNode::progress_end_task(task);
+}
+
+MonoBoolean godot_icall_EditorProgress_Step(MonoString *p_task, MonoString *p_state, int32_t p_step, MonoBoolean p_force_refresh) {
+ String task = GDMonoMarshal::mono_string_to_godot(p_task);
+ String state = GDMonoMarshal::mono_string_to_godot(p_state);
+ return EditorNode::progress_task_step(task, state, p_step, (bool)p_force_refresh);
+}
+
+BindingsGenerator *godot_icall_BindingsGenerator_Ctor() {
+ return memnew(BindingsGenerator);
+}
+
+void godot_icall_BindingsGenerator_Dtor(BindingsGenerator *p_handle) {
+ memdelete(p_handle);
+}
+
+MonoBoolean godot_icall_BindingsGenerator_LogPrintEnabled(BindingsGenerator *p_handle) {
+ return p_handle->is_log_print_enabled();
+}
+
+void godot_icall_BindingsGenerator_SetLogPrintEnabled(BindingsGenerator p_handle, MonoBoolean p_enabled) {
+ p_handle.set_log_print_enabled(p_enabled);
+}
+
+int32_t godot_icall_BindingsGenerator_GenerateCsApi(BindingsGenerator *p_handle, MonoString *p_output_dir) {
+ String output_dir = GDMonoMarshal::mono_string_to_godot(p_output_dir);
+ return p_handle->generate_cs_api(output_dir);
+}
+
+uint32_t godot_icall_BindingsGenerator_Version() {
+ return BindingsGenerator::get_version();
+}
+
+uint32_t godot_icall_BindingsGenerator_CsGlueVersion() {
+ return CS_GLUE_VERSION;
+}
+
+int32_t godot_icall_ScriptClassParser_ParseFile(MonoString *p_filepath, MonoObject *p_classes) {
+ String filepath = GDMonoMarshal::mono_string_to_godot(p_filepath);
+
+ ScriptClassParser scp;
+ Error err = scp.parse_file(filepath);
+ if (err == OK) {
+ Array classes = GDMonoMarshal::mono_object_to_variant(p_classes);
+ const Vector<ScriptClassParser::ClassDecl> &class_decls = scp.get_classes();
+
+ for (int i = 0; i < class_decls.size(); i++) {
+ const ScriptClassParser::ClassDecl &classDecl = class_decls[i];
+
+ Dictionary classDeclDict;
+ classDeclDict["name"] = classDecl.name;
+ classDeclDict["namespace"] = classDecl.namespace_;
+ classDeclDict["nested"] = classDecl.nested;
+ classDeclDict["base_count"] = classDecl.base.size();
+ classes.push_back(classDeclDict);
+ }
+ }
+ return err;
+}
+
+uint32_t godot_icall_GodotSharpExport_GetExportedAssemblyDependencies(MonoString *p_project_dll_name, MonoString *p_project_dll_src_path,
+ MonoString *p_build_config, MonoString *p_custom_lib_dir, MonoObject *r_dependencies) {
+ String project_dll_name = GDMonoMarshal::mono_string_to_godot(p_project_dll_name);
+ String project_dll_src_path = GDMonoMarshal::mono_string_to_godot(p_project_dll_src_path);
+ String build_config = GDMonoMarshal::mono_string_to_godot(p_build_config);
+ String custom_lib_dir = GDMonoMarshal::mono_string_to_godot(p_custom_lib_dir);
+ Dictionary dependencies = GDMonoMarshal::mono_object_to_variant(r_dependencies);
+
+ return GodotSharpExport::get_exported_assembly_dependencies(project_dll_name, project_dll_src_path, build_config, custom_lib_dir, dependencies);
+}
+
+float godot_icall_Globals_EditorScale() {
+ return EDSCALE;
+}
+
+MonoObject *godot_icall_Globals_GlobalDef(MonoString *p_setting, MonoObject *p_default_value, MonoBoolean p_restart_if_changed) {
+ String setting = GDMonoMarshal::mono_string_to_godot(p_setting);
+ Variant default_value = GDMonoMarshal::mono_object_to_variant(p_default_value);
+ Variant result = _GLOBAL_DEF(setting, default_value, (bool)p_restart_if_changed);
+ return GDMonoMarshal::variant_to_mono_object(result);
+}
+
+MonoObject *godot_icall_Globals_EditorDef(MonoString *p_setting, MonoObject *p_default_value, MonoBoolean p_restart_if_changed) {
+ String setting = GDMonoMarshal::mono_string_to_godot(p_setting);
+ Variant default_value = GDMonoMarshal::mono_object_to_variant(p_default_value);
+ Variant result = _EDITOR_DEF(setting, default_value, (bool)p_restart_if_changed);
+ return GDMonoMarshal::variant_to_mono_object(result);
+}
+
+MonoString *godot_icall_Globals_TTR(MonoString *p_text) {
+ String text = GDMonoMarshal::mono_string_to_godot(p_text);
+ return GDMonoMarshal::mono_string_from_godot(TTR(text));
+}
+
+MonoString *godot_icall_Internal_UpdateApiAssembliesFromPrebuilt() {
+ String error_str = GDMono::get_singleton()->update_api_assemblies_from_prebuilt();
+ return GDMonoMarshal::mono_string_from_godot(error_str);
+}
+
+MonoString *godot_icall_Internal_FullTemplatesDir() {
+ String full_templates_dir = EditorSettings::get_singleton()->get_templates_dir().plus_file(VERSION_FULL_CONFIG);
+ return GDMonoMarshal::mono_string_from_godot(full_templates_dir);
+}
+
+MonoString *godot_icall_Internal_SimplifyGodotPath(MonoString *p_path) {
+ String path = GDMonoMarshal::mono_string_to_godot(p_path);
+ return GDMonoMarshal::mono_string_from_godot(path.simplify_path());
+}
+
+MonoBoolean godot_icall_Internal_IsOsxAppBundleInstalled(MonoString *p_bundle_id) {
+#ifdef OSX_ENABLED
+ String bundle_id = GDMonoMarshal::mono_string_to_godot(p_bundle_id);
+ return (MonoBoolean)osx_is_app_bundle_installed;
+#else
+ (void)p_bundle_id; // UNUSED
+ return (MonoBoolean) false;
+#endif
+}
+
+MonoBoolean godot_icall_Internal_GodotIs32Bits() {
+ return sizeof(void *) == 4;
+}
+
+MonoBoolean godot_icall_Internal_GodotIsRealTDouble() {
+#ifdef REAL_T_IS_DOUBLE
+ return (MonoBoolean) true;
+#else
+ return (MonoBoolean) false;
+#endif
+}
+
+void godot_icall_Internal_GodotMainIteration() {
+ Main::iteration();
+}
+
+uint64_t godot_icall_Internal_GetCoreApiHash() {
+ return ClassDB::get_api_hash(ClassDB::API_CORE);
+}
+
+uint64_t godot_icall_Internal_GetEditorApiHash() {
+ return ClassDB::get_api_hash(ClassDB::API_EDITOR);
+}
+
+MonoBoolean godot_icall_Internal_IsAssembliesReloadingNeeded() {
+#ifdef GD_MONO_HOT_RELOAD
+ return (MonoBoolean)CSharpLanguage::get_singleton()->is_assembly_reloading_needed();
+#else
+ return (MonoBoolean) false;
+#endif
+}
+
+void godot_icall_Internal_ReloadAssemblies(MonoBoolean p_soft_reload) {
+#ifdef GD_MONO_HOT_RELOAD
+ _GodotSharp::get_singleton()->call_deferred("_reload_assemblies", (bool)p_soft_reload);
+#endif
+}
+
+void godot_icall_Internal_ScriptEditorDebuggerReloadScripts() {
+ ScriptEditor::get_singleton()->get_debugger()->reload_scripts();
+}
+
+MonoBoolean godot_icall_Internal_ScriptEditorEdit(MonoObject *p_resource, int32_t p_line, int32_t p_col, MonoBoolean p_grab_focus) {
+ Ref<Resource> resource = GDMonoMarshal::mono_object_to_variant(p_resource);
+ return (MonoBoolean)ScriptEditor::get_singleton()->edit(resource, p_line, p_col, (bool)p_grab_focus);
+}
+
+void godot_icall_Internal_EditorNodeShowScriptScreen() {
+ EditorNode::get_singleton()->call("_editor_select", EditorNode::EDITOR_SCRIPT);
+}
+
+MonoObject *godot_icall_Internal_GetScriptsMetadataOrNothing(MonoReflectionType *p_dict_reftype) {
+ Dictionary maybe_metadata = CSharpLanguage::get_singleton()->get_scripts_metadata_or_nothing();
+
+ MonoType *dict_type = mono_reflection_type_get_type(p_dict_reftype);
+
+ uint32_t type_encoding = mono_type_get_type(dict_type);
+ MonoClass *type_class_raw = mono_class_from_mono_type(dict_type);
+ GDMonoClass *type_class = GDMono::get_singleton()->get_class(type_class_raw);
+
+ return GDMonoMarshal::variant_to_mono_object(maybe_metadata, ManagedType(type_encoding, type_class));
+}
+
+MonoString *godot_icall_Internal_MonoWindowsInstallRoot() {
+#ifdef WINDOWS_ENABLED
+ String install_root_dir = GDMono::get_singleton()->get_mono_reg_info().install_root_dir;
+ return GDMonoMarshal::mono_string_from_godot(install_root_dir);
+#else
+ return NULL;
+#endif
+}
+
+MonoString *godot_icall_Utils_OS_GetPlatformName() {
+ String os_name = OS::get_singleton()->get_name();
+ return GDMonoMarshal::mono_string_from_godot(os_name);
+}
+
+void register_editor_internal_calls() {
+
+ // GodotSharpDirs
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResDataDir", (void *)godot_icall_GodotSharpDirs_ResDataDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResMetadataDir", (void *)godot_icall_GodotSharpDirs_ResMetadataDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResAssembliesBaseDir", (void *)godot_icall_GodotSharpDirs_ResAssembliesBaseDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResAssembliesDir", (void *)godot_icall_GodotSharpDirs_ResAssembliesDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResConfigDir", (void *)godot_icall_GodotSharpDirs_ResConfigDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempDir", (void *)godot_icall_GodotSharpDirs_ResTempDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempAssembliesBaseDir", (void *)godot_icall_GodotSharpDirs_ResTempAssembliesBaseDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ResTempAssembliesDir", (void *)godot_icall_GodotSharpDirs_ResTempAssembliesDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoUserDir", (void *)godot_icall_GodotSharpDirs_MonoUserDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoLogsDir", (void *)godot_icall_GodotSharpDirs_MonoLogsDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_MonoSolutionsDir", (void *)godot_icall_GodotSharpDirs_MonoSolutionsDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_BuildLogsDirs", (void *)godot_icall_GodotSharpDirs_BuildLogsDirs);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ProjectSlnPath", (void *)godot_icall_GodotSharpDirs_ProjectSlnPath);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_ProjectCsProjPath", (void *)godot_icall_GodotSharpDirs_ProjectCsProjPath);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataEditorToolsDir", (void *)godot_icall_GodotSharpDirs_DataEditorToolsDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataEditorPrebuiltApiDir", (void *)godot_icall_GodotSharpDirs_DataEditorPrebuiltApiDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoEtcDir", (void *)godot_icall_GodotSharpDirs_DataMonoEtcDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoLibDir", (void *)godot_icall_GodotSharpDirs_DataMonoLibDir);
+ mono_add_internal_call("GodotTools.Internals.GodotSharpDirs::internal_DataMonoBinDir", (void *)godot_icall_GodotSharpDirs_DataMonoBinDir);
+
+ // EditorProgress
+ mono_add_internal_call("GodotTools.Internals.EditorProgress::internal_Create", (void *)godot_icall_EditorProgress_Create);
+ mono_add_internal_call("GodotTools.Internals.EditorProgress::internal_Dispose", (void *)godot_icall_EditorProgress_Dispose);
+ mono_add_internal_call("GodotTools.Internals.EditorProgress::internal_Step", (void *)godot_icall_EditorProgress_Step);
+
+ // BiningsGenerator
+ mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_Ctor", (void *)godot_icall_BindingsGenerator_Ctor);
+ mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_Dtor", (void *)godot_icall_BindingsGenerator_Dtor);
+ mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_LogPrintEnabled", (void *)godot_icall_BindingsGenerator_LogPrintEnabled);
+ mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_SetLogPrintEnabled", (void *)godot_icall_BindingsGenerator_SetLogPrintEnabled);
+ mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_GenerateCsApi", (void *)godot_icall_BindingsGenerator_GenerateCsApi);
+ mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_Version", (void *)godot_icall_BindingsGenerator_Version);
+ mono_add_internal_call("GodotTools.Internals.BindingsGenerator::internal_CsGlueVersion", (void *)godot_icall_BindingsGenerator_CsGlueVersion);
+
+ // ScriptClassParser
+ mono_add_internal_call("GodotTools.Internals.ScriptClassParser::internal_ParseFile", (void *)godot_icall_ScriptClassParser_ParseFile);
+
+ // GodotSharpExport
+ mono_add_internal_call("GodotTools.GodotSharpExport::internal_GetExportedAssemblyDependencies", (void *)godot_icall_GodotSharpExport_GetExportedAssemblyDependencies);
+
+ // Internals
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_UpdateApiAssembliesFromPrebuilt", (void *)godot_icall_Internal_UpdateApiAssembliesFromPrebuilt);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_FullTemplatesDir", (void *)godot_icall_Internal_FullTemplatesDir);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_SimplifyGodotPath", (void *)godot_icall_Internal_SimplifyGodotPath);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_IsOsxAppBundleInstalled", (void *)godot_icall_Internal_IsOsxAppBundleInstalled);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_GodotIs32Bits", (void *)godot_icall_Internal_GodotIs32Bits);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_GodotIsRealTDouble", (void *)godot_icall_Internal_GodotIsRealTDouble);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_GodotMainIteration", (void *)godot_icall_Internal_GodotMainIteration);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_GetCoreApiHash", (void *)godot_icall_Internal_GetCoreApiHash);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_GetEditorApiHash", (void *)godot_icall_Internal_GetEditorApiHash);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_IsAssembliesReloadingNeeded", (void *)godot_icall_Internal_IsAssembliesReloadingNeeded);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_ReloadAssemblies", (void *)godot_icall_Internal_ReloadAssemblies);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_ScriptEditorDebuggerReloadScripts", (void *)godot_icall_Internal_ScriptEditorDebuggerReloadScripts);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_ScriptEditorEdit", (void *)godot_icall_Internal_ScriptEditorEdit);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_EditorNodeShowScriptScreen", (void *)godot_icall_Internal_EditorNodeShowScriptScreen);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_GetScriptsMetadataOrNothing", (void *)godot_icall_Internal_GetScriptsMetadataOrNothing);
+ mono_add_internal_call("GodotTools.Internals.Internal::internal_MonoWindowsInstallRoot", (void *)godot_icall_Internal_MonoWindowsInstallRoot);
+
+ // Globals
+ mono_add_internal_call("GodotTools.Internals.Globals::internal_EditorScale", (void *)godot_icall_Globals_EditorScale);
+ mono_add_internal_call("GodotTools.Internals.Globals::internal_GlobalDef", (void *)godot_icall_Globals_GlobalDef);
+ mono_add_internal_call("GodotTools.Internals.Globals::internal_EditorDef", (void *)godot_icall_Globals_EditorDef);
+ mono_add_internal_call("GodotTools.Internals.Globals::internal_TTR", (void *)godot_icall_Globals_TTR);
+
+ // Utils.OS
+ mono_add_internal_call("GodotTools.Utils.OS::GetPlatformName", (void *)godot_icall_Utils_OS_GetPlatformName);
+}
diff --git a/modules/mono/editor/dotnet_solution.h b/modules/mono/editor/editor_internal_calls.h
index 18933364fa..1682da66e5 100644
--- a/modules/mono/editor/dotnet_solution.h
+++ b/modules/mono/editor/editor_internal_calls.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* dotnet_solution.h */
+/* editor_internal_calls.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,36 +28,9 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef NET_SOLUTION_H
-#define NET_SOLUTION_H
+#ifndef EDITOR_INTERNAL_CALL_H
+#define EDITOR_INTERNAL_CALL_H
-#include "core/map.h"
-#include "core/ustring.h"
+void register_editor_internal_calls();
-struct DotNetSolution {
- String name;
-
- struct ProjectInfo {
- String guid;
- String relpath; // Must be relative to the solution directory
- Vector<String> configs;
- };
-
- void add_new_project(const String &p_name, const ProjectInfo &p_project_info);
- bool has_project(const String &p_name) const;
- const ProjectInfo &get_project_info(const String &p_name) const;
- bool remove_project(const String &p_name);
-
- Error save();
-
- bool set_path(const String &p_existing_path);
- String get_path();
-
- DotNetSolution(const String &p_name);
-
-private:
- String path;
- Map<String, ProjectInfo> projects;
-};
-
-#endif // NET_SOLUTION_H
+#endif // EDITOR_INTERNAL_CALL_H
diff --git a/modules/mono/editor/godotsharp_builds.cpp b/modules/mono/editor/godotsharp_builds.cpp
deleted file mode 100644
index 9f132825fb..0000000000
--- a/modules/mono/editor/godotsharp_builds.cpp
+++ /dev/null
@@ -1,624 +0,0 @@
-/*************************************************************************/
-/* godotsharp_builds.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "godotsharp_builds.h"
-
-#include "core/os/os.h"
-#include "core/vector.h"
-#include "main/main.h"
-
-#include "../glue/cs_glue_version.gen.h"
-#include "../godotsharp_dirs.h"
-#include "../mono_gd/gd_mono_class.h"
-#include "../mono_gd/gd_mono_marshal.h"
-#include "../utils/path_utils.h"
-#include "bindings_generator.h"
-#include "csharp_project.h"
-#include "godotsharp_editor.h"
-
-#define PROP_NAME_MSBUILD_MONO "MSBuild (Mono)"
-#define PROP_NAME_MSBUILD_VS "MSBuild (VS Build Tools)"
-#define PROP_NAME_XBUILD "xbuild (Deprecated)"
-
-void godot_icall_BuildInstance_ExitCallback(MonoString *p_solution, MonoString *p_config, int p_exit_code) {
-
- String solution = GDMonoMarshal::mono_string_to_godot(p_solution);
- String config = GDMonoMarshal::mono_string_to_godot(p_config);
- GodotSharpBuilds::get_singleton()->build_exit_callback(MonoBuildInfo(solution, config), p_exit_code);
-}
-
-static Vector<const char *> _get_msbuild_hint_dirs() {
- Vector<const char *> ret;
-#ifdef OSX_ENABLED
- ret.push_back("/Library/Frameworks/Mono.framework/Versions/Current/bin/");
- ret.push_back("/usr/local/var/homebrew/linked/mono/bin/");
-#endif
- ret.push_back("/opt/novell/mono/bin/");
- return ret;
-}
-
-#ifdef UNIX_ENABLED
-String _find_build_engine_on_unix(const String &p_name) {
- String ret = path_which(p_name);
-
- if (ret.length())
- return ret;
-
- String ret_fallback = path_which(p_name + ".exe");
- if (ret_fallback.length())
- return ret_fallback;
-
- static Vector<const char *> locations = _get_msbuild_hint_dirs();
-
- for (int i = 0; i < locations.size(); i++) {
- String hint_path = locations[i] + p_name;
-
- if (FileAccess::exists(hint_path)) {
- return hint_path;
- }
- }
-
- return String();
-}
-#endif
-
-MonoString *godot_icall_BuildInstance_get_MSBuildPath() {
-
- GodotSharpBuilds::BuildTool build_tool = GodotSharpBuilds::BuildTool(int(EditorSettings::get_singleton()->get("mono/builds/build_tool")));
-
-#if defined(WINDOWS_ENABLED)
- switch (build_tool) {
- case GodotSharpBuilds::MSBUILD_VS: {
- static String msbuild_tools_path;
-
- if (msbuild_tools_path.empty() || !FileAccess::exists(msbuild_tools_path)) {
- // Try to search it again if it wasn't found last time or if it was removed from its location
- msbuild_tools_path = MonoRegUtils::find_msbuild_tools_path();
-
- if (msbuild_tools_path.empty()) {
- ERR_PRINTS("Cannot find executable for '" PROP_NAME_MSBUILD_VS "'. Tried with path: " + msbuild_tools_path);
- return NULL;
- }
- }
-
- if (!msbuild_tools_path.ends_with("\\"))
- msbuild_tools_path += "\\";
-
- return GDMonoMarshal::mono_string_from_godot(msbuild_tools_path + "MSBuild.exe");
- } break;
- case GodotSharpBuilds::MSBUILD_MONO: {
- String msbuild_path = GDMono::get_singleton()->get_mono_reg_info().bin_dir.plus_file("msbuild.bat");
-
- if (!FileAccess::exists(msbuild_path)) {
- ERR_PRINTS("Cannot find executable for '" PROP_NAME_MSBUILD_MONO "'. Tried with path: " + msbuild_path);
- return NULL;
- }
-
- return GDMonoMarshal::mono_string_from_godot(msbuild_path);
- } break;
- case GodotSharpBuilds::XBUILD: {
- String xbuild_path = GDMono::get_singleton()->get_mono_reg_info().bin_dir.plus_file("xbuild.bat");
-
- if (!FileAccess::exists(xbuild_path)) {
- ERR_PRINTS("Cannot find executable for '" PROP_NAME_XBUILD "'. Tried with path: " + xbuild_path);
- return NULL;
- }
-
- return GDMonoMarshal::mono_string_from_godot(xbuild_path);
- } break;
- default:
- ERR_EXPLAIN("You don't deserve to live");
- CRASH_NOW();
- }
-#elif defined(UNIX_ENABLED)
- static String msbuild_path;
- static String xbuild_path;
-
- if (build_tool == GodotSharpBuilds::XBUILD) {
- if (xbuild_path.empty() || !FileAccess::exists(xbuild_path)) {
- // Try to search it again if it wasn't found last time or if it was removed from its location
- xbuild_path = _find_build_engine_on_unix("msbuild");
- }
-
- if (xbuild_path.empty()) {
- ERR_PRINT("Cannot find binary for '" PROP_NAME_XBUILD "'");
- return NULL;
- }
- } else {
- if (msbuild_path.empty() || !FileAccess::exists(msbuild_path)) {
- // Try to search it again if it wasn't found last time or if it was removed from its location
- msbuild_path = _find_build_engine_on_unix("msbuild");
- }
-
- if (msbuild_path.empty()) {
- ERR_PRINT("Cannot find binary for '" PROP_NAME_MSBUILD_MONO "'");
- return NULL;
- }
- }
-
- return GDMonoMarshal::mono_string_from_godot(build_tool != GodotSharpBuilds::XBUILD ? msbuild_path : xbuild_path);
-#else
- (void)build_tool; // UNUSED
-
- ERR_EXPLAIN("Not implemented on this platform");
- ERR_FAIL_V(NULL);
-#endif
-}
-
-MonoString *godot_icall_BuildInstance_get_MonoWindowsBinDir() {
-
-#if defined(WINDOWS_ENABLED)
- const MonoRegInfo &mono_reg_info = GDMono::get_singleton()->get_mono_reg_info();
- if (mono_reg_info.bin_dir.length()) {
- return GDMonoMarshal::mono_string_from_godot(mono_reg_info.bin_dir);
- }
-
- ERR_EXPLAIN("Cannot find Mono's binaries directory in the registry");
- ERR_FAIL_V(NULL);
-#else
- return NULL;
-#endif
-}
-
-MonoBoolean godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows() {
-
-#if defined(WINDOWS_ENABLED)
- return GodotSharpBuilds::BuildTool(int(EditorSettings::get_singleton()->get("mono/builds/build_tool"))) == GodotSharpBuilds::MSBUILD_MONO;
-#else
- return false;
-#endif
-}
-
-MonoBoolean godot_icall_BuildInstance_get_PrintBuildOutput() {
-
- return (bool)EDITOR_GET("mono/builds/print_build_output");
-}
-
-void GodotSharpBuilds::register_internal_calls() {
-
- static bool registered = false;
- ERR_FAIL_COND(registered);
- registered = true;
-
- mono_add_internal_call("GodotSharpTools.Build.BuildSystem::godot_icall_BuildInstance_ExitCallback", (void *)godot_icall_BuildInstance_ExitCallback);
- mono_add_internal_call("GodotSharpTools.Build.BuildInstance::godot_icall_BuildInstance_get_MSBuildPath", (void *)godot_icall_BuildInstance_get_MSBuildPath);
- mono_add_internal_call("GodotSharpTools.Build.BuildInstance::godot_icall_BuildInstance_get_MonoWindowsBinDir", (void *)godot_icall_BuildInstance_get_MonoWindowsBinDir);
- mono_add_internal_call("GodotSharpTools.Build.BuildInstance::godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows", (void *)godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows);
- mono_add_internal_call("GodotSharpTools.Build.BuildInstance::godot_icall_BuildInstance_get_PrintBuildOutput", (void *)godot_icall_BuildInstance_get_PrintBuildOutput);
-}
-
-void GodotSharpBuilds::show_build_error_dialog(const String &p_message) {
-
- GodotSharpEditor::get_singleton()->show_error_dialog(p_message, "Build error");
- MonoBottomPanel::get_singleton()->show_build_tab();
-}
-
-bool GodotSharpBuilds::build_api_sln(const String &p_api_sln_dir, const String &p_config) {
-
- String api_sln_file = p_api_sln_dir.plus_file(API_SOLUTION_NAME ".sln");
-
- String core_api_assembly_dir = p_api_sln_dir.plus_file(CORE_API_ASSEMBLY_NAME).plus_file("bin").plus_file(p_config);
- String core_api_assembly_file = core_api_assembly_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
-
- String editor_api_assembly_dir = p_api_sln_dir.plus_file(EDITOR_API_ASSEMBLY_NAME).plus_file("bin").plus_file(p_config);
- String editor_api_assembly_file = editor_api_assembly_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
-
- if (!FileAccess::exists(core_api_assembly_file) || !FileAccess::exists(editor_api_assembly_file)) {
- MonoBuildInfo api_build_info(api_sln_file, p_config);
- // TODO Replace this global NoWarn with '#pragma warning' directives on generated files,
- // once we start to actively document manually maintained C# classes
- api_build_info.custom_props.push_back("NoWarn=1591"); // Ignore missing documentation warnings
-
- if (!GodotSharpBuilds::get_singleton()->build(api_build_info)) {
- show_build_error_dialog("Failed to build " API_SOLUTION_NAME " solution.");
- return false;
- }
- }
-
- return true;
-}
-
-bool GodotSharpBuilds::copy_api_assembly(const String &p_src_dir, const String &p_dst_dir, const String &p_assembly_name, APIAssembly::Type p_api_type) {
-
- // Create destination directory if needed
- if (!DirAccess::exists(p_dst_dir)) {
- DirAccess *da = DirAccess::create_for_path(p_dst_dir);
- Error err = da->make_dir_recursive(p_dst_dir);
- memdelete(da);
-
- if (err != OK) {
- show_build_error_dialog("Failed to create destination directory for the API assemblies. Error: " + itos(err));
- return false;
- }
- }
-
- String assembly_file = p_assembly_name + ".dll";
- String assembly_src = p_src_dir.plus_file(assembly_file);
- String assembly_dst = p_dst_dir.plus_file(assembly_file);
-
- if (!FileAccess::exists(assembly_dst) ||
- FileAccess::get_modified_time(assembly_src) > FileAccess::get_modified_time(assembly_dst) ||
- GDMono::get_singleton()->metadata_is_api_assembly_invalidated(p_api_type)) {
- DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
-
- String xml_file = p_assembly_name + ".xml";
- if (da->copy(p_src_dir.plus_file(xml_file), p_dst_dir.plus_file(xml_file)) != OK)
- WARN_PRINTS("Failed to copy " + xml_file);
-
- String pdb_file = p_assembly_name + ".pdb";
- if (da->copy(p_src_dir.plus_file(pdb_file), p_dst_dir.plus_file(pdb_file)) != OK)
- WARN_PRINTS("Failed to copy " + pdb_file);
-
- Error err = da->copy(assembly_src, assembly_dst);
-
- if (err != OK) {
- show_build_error_dialog("Failed to copy " + assembly_file);
- return false;
- }
-
- GDMono::get_singleton()->metadata_set_api_assembly_invalidated(p_api_type, false);
- }
-
- return true;
-}
-
-String GodotSharpBuilds::_api_folder_name(APIAssembly::Type p_api_type) {
-
- uint64_t api_hash = p_api_type == APIAssembly::API_CORE ?
- GDMono::get_singleton()->get_api_core_hash() :
- GDMono::get_singleton()->get_api_editor_hash();
- return String::num_uint64(api_hash) +
- "_" + String::num_uint64(BindingsGenerator::get_version()) +
- "_" + String::num_uint64(CS_GLUE_VERSION);
-}
-
-bool GodotSharpBuilds::make_api_assembly(APIAssembly::Type p_api_type) {
-
- String api_name = p_api_type == APIAssembly::API_CORE ? CORE_API_ASSEMBLY_NAME : EDITOR_API_ASSEMBLY_NAME;
-
- String editor_prebuilt_api_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir();
- String res_assemblies_dir = GodotSharpDirs::get_res_assemblies_dir();
-
- if (FileAccess::exists(editor_prebuilt_api_dir.plus_file(api_name + ".dll"))) {
- EditorProgress pr("mono_copy_prebuilt_api_assembly", "Copying prebuilt " + api_name + " assembly...", 1);
- pr.step("Copying " + api_name + " assembly", 0);
- return GodotSharpBuilds::copy_api_assembly(editor_prebuilt_api_dir, res_assemblies_dir, api_name, p_api_type);
- }
-
- String api_build_config = "Release";
-
- EditorProgress pr("mono_build_release_" API_SOLUTION_NAME, "Building " API_SOLUTION_NAME " solution...", 3);
-
- pr.step("Generating " API_SOLUTION_NAME " solution", 0);
-
- String api_sln_dir = GodotSharpDirs::get_mono_solutions_dir()
- .plus_file(_api_folder_name(APIAssembly::API_CORE));
-
- String api_sln_file = api_sln_dir.plus_file(API_SOLUTION_NAME ".sln");
-
- if (!DirAccess::exists(api_sln_dir) || !FileAccess::exists(api_sln_file)) {
- BindingsGenerator bindings_generator;
-
- if (!OS::get_singleton()->is_stdout_verbose()) {
- bindings_generator.set_log_print_enabled(false);
- }
-
- Error err = bindings_generator.generate_cs_api(api_sln_dir);
- if (err != OK) {
- show_build_error_dialog("Failed to generate " API_SOLUTION_NAME " solution. Error: " + itos(err));
- return false;
- }
- }
-
- pr.step("Building " API_SOLUTION_NAME " solution", 1);
-
- if (!GodotSharpBuilds::build_api_sln(api_sln_dir, api_build_config))
- return false;
-
- pr.step("Copying " + api_name + " assembly", 2);
-
- // Copy the built assembly to the assemblies directory
- String api_assembly_dir = api_sln_dir.plus_file(api_name).plus_file("bin").plus_file(api_build_config);
- if (!GodotSharpBuilds::copy_api_assembly(api_assembly_dir, res_assemblies_dir, api_name, p_api_type))
- return false;
-
- return true;
-}
-
-bool GodotSharpBuilds::build_project_blocking(const String &p_config, const Vector<String> &p_godot_defines) {
-
- if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path()))
- return true; // No solution to build
-
- if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_CORE))
- return false;
-
- if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_EDITOR))
- return false;
-
- EditorProgress pr("mono_project_debug_build", "Building project solution...", 1);
- pr.step("Building project solution", 0);
-
- MonoBuildInfo build_info(GodotSharpDirs::get_project_sln_path(), p_config);
-
- // Add Godot defines
- String constants = "GodotDefineConstants=\"";
-
- for (int i = 0; i < p_godot_defines.size(); i++) {
- constants += "GODOT_" + p_godot_defines[i].to_upper().replace("-", "_").replace(" ", "_").replace(";", "_") + ";";
- }
-
-#ifdef REAL_T_IS_DOUBLE
- constants += "GODOT_REAL_T_IS_DOUBLE;";
-#endif
-
- constants += "\"";
- build_info.custom_props.push_back(constants);
-
- if (!GodotSharpBuilds::get_singleton()->build(build_info)) {
- GodotSharpBuilds::show_build_error_dialog("Failed to build project solution");
- return false;
- }
-
- return true;
-}
-
-bool GodotSharpBuilds::editor_build_callback() {
-
- if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path()))
- return true; // No solution to build
-
- String scripts_metadata_path_editor = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor");
- String scripts_metadata_path_player = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor_player");
-
- Error metadata_err = CSharpProject::generate_scripts_metadata(GodotSharpDirs::get_project_csproj_path(), scripts_metadata_path_editor);
- ERR_FAIL_COND_V(metadata_err != OK, false);
-
- if (FileAccess::exists(scripts_metadata_path_editor)) {
- DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- Error copy_err = da->copy(scripts_metadata_path_editor, scripts_metadata_path_player);
-
- ERR_EXPLAIN("Failed to copy scripts metadata file");
- ERR_FAIL_COND_V(copy_err != OK, false);
- }
-
- Vector<String> godot_defines;
- godot_defines.push_back(OS::get_singleton()->get_name());
- godot_defines.push_back(sizeof(void *) == 4 ? "32" : "64");
- return build_project_blocking("Tools", godot_defines);
-}
-
-GodotSharpBuilds *GodotSharpBuilds::singleton = NULL;
-
-void GodotSharpBuilds::build_exit_callback(const MonoBuildInfo &p_build_info, int p_exit_code) {
-
- BuildProcess *match = builds.getptr(p_build_info);
- ERR_FAIL_NULL(match);
-
- BuildProcess &bp = *match;
- bp.on_exit(p_exit_code);
-}
-
-void GodotSharpBuilds::restart_build(MonoBuildTab *p_build_tab) {
-}
-
-void GodotSharpBuilds::stop_build(MonoBuildTab *p_build_tab) {
-}
-
-bool GodotSharpBuilds::build(const MonoBuildInfo &p_build_info) {
-
- BuildProcess *match = builds.getptr(p_build_info);
-
- if (match) {
- BuildProcess &bp = *match;
- bp.start(true);
- return bp.exit_code == 0;
- } else {
- BuildProcess bp = BuildProcess(p_build_info);
- bp.start(true);
- builds.set(p_build_info, bp);
- return bp.exit_code == 0;
- }
-}
-
-bool GodotSharpBuilds::build_async(const MonoBuildInfo &p_build_info, GodotSharpBuild_ExitCallback p_callback) {
-
- BuildProcess *match = builds.getptr(p_build_info);
-
- if (match) {
- BuildProcess &bp = *match;
- bp.start();
- return !bp.exited; // failed to start
- } else {
- BuildProcess bp = BuildProcess(p_build_info, p_callback);
- bp.start();
- builds.set(p_build_info, bp);
- return !bp.exited; // failed to start
- }
-}
-
-GodotSharpBuilds::GodotSharpBuilds() {
-
- singleton = this;
-
- EditorNode::get_singleton()->add_build_callback(&GodotSharpBuilds::editor_build_callback);
-
- // Build tool settings
- EditorSettings *ed_settings = EditorSettings::get_singleton();
-
-#ifdef WINDOWS_ENABLED
- EDITOR_DEF("mono/builds/build_tool", MSBUILD_VS);
-#else
- EDITOR_DEF("mono/builds/build_tool", MSBUILD_MONO);
-#endif
-
- ed_settings->add_property_hint(PropertyInfo(Variant::INT, "mono/builds/build_tool", PROPERTY_HINT_ENUM,
- PROP_NAME_MSBUILD_MONO
-#ifdef WINDOWS_ENABLED
- "," PROP_NAME_MSBUILD_VS
-#endif
- "," PROP_NAME_XBUILD));
-
- EDITOR_DEF("mono/builds/print_build_output", false);
-}
-
-GodotSharpBuilds::~GodotSharpBuilds() {
-
- singleton = NULL;
-}
-
-void GodotSharpBuilds::BuildProcess::on_exit(int p_exit_code) {
-
- exited = true;
- exit_code = p_exit_code;
- build_tab->on_build_exit(p_exit_code == 0 ? MonoBuildTab::RESULT_SUCCESS : MonoBuildTab::RESULT_ERROR);
- build_instance.unref();
-
- if (exit_callback)
- exit_callback(exit_code);
-}
-
-void GodotSharpBuilds::BuildProcess::start(bool p_blocking) {
-
- _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN)
-
- exit_code = -1;
-
- String log_dirpath = build_info.get_log_dirpath();
-
- if (build_tab) {
- build_tab->on_build_start();
- } else {
- build_tab = memnew(MonoBuildTab(build_info, log_dirpath));
- MonoBottomPanel::get_singleton()->add_build_tab(build_tab);
- }
-
- if (p_blocking) {
- // Required in order to update the build tasks list
- Main::iteration();
- }
-
- if (!exited) {
- exited = true;
- String message = "Tried to start build process, but it is already running";
- build_tab->on_build_exec_failed(message);
- ERR_EXPLAIN(message);
- ERR_FAIL();
- }
-
- exited = false;
-
- // Remove old issues file
-
- String issues_file = get_msbuild_issues_filename();
- DirAccessRef d = DirAccess::create_for_path(log_dirpath);
- if (d->file_exists(issues_file)) {
- Error err = d->remove(issues_file);
- if (err != OK) {
- exited = true;
- String file_path = ProjectSettings::get_singleton()->localize_path(log_dirpath).plus_file(issues_file);
- String message = "Cannot remove issues file: " + file_path;
- build_tab->on_build_exec_failed(message);
- ERR_EXPLAIN(message);
- ERR_FAIL();
- }
- }
-
- GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Build", "BuildInstance");
-
- MonoObject *mono_object = mono_object_new(mono_domain_get(), klass->get_mono_ptr());
-
- // Construct
-
- Variant solution = build_info.solution;
- Variant config = build_info.configuration;
-
- const Variant *ctor_args[2] = { &solution, &config };
-
- MonoException *exc = NULL;
- GDMonoMethod *ctor = klass->get_method(".ctor", 2);
- ctor->invoke(mono_object, ctor_args, &exc);
-
- if (exc) {
- exited = true;
- GDMonoUtils::debug_unhandled_exception(exc);
- String message = "The build constructor threw an exception.\n" + GDMonoUtils::get_exception_name_and_message(exc);
- build_tab->on_build_exec_failed(message);
- ERR_EXPLAIN(message);
- ERR_FAIL();
- }
-
- // Call Build
-
- String logger_assembly_path = GDMono::get_singleton()->get_editor_tools_assembly()->get_path();
- Variant logger_assembly = ProjectSettings::get_singleton()->globalize_path(logger_assembly_path);
- Variant logger_output_dir = log_dirpath;
- Variant custom_props = build_info.custom_props;
-
- const Variant *args[3] = { &logger_assembly, &logger_output_dir, &custom_props };
-
- exc = NULL;
- GDMonoMethod *build_method = klass->get_method(p_blocking ? "Build" : "BuildAsync", 3);
- build_method->invoke(mono_object, args, &exc);
-
- if (exc) {
- exited = true;
- GDMonoUtils::debug_unhandled_exception(exc);
- String message = "The build method threw an exception.\n" + GDMonoUtils::get_exception_name_and_message(exc);
- build_tab->on_build_exec_failed(message);
- ERR_EXPLAIN(message);
- ERR_FAIL();
- }
-
- // Build returned
-
- if (p_blocking) {
- exited = true;
- exit_code = klass->get_field("exitCode")->get_int_value(mono_object);
-
- if (exit_code != 0) {
- String log_filepath = build_info.get_log_dirpath().plus_file(get_msbuild_log_filename());
- print_verbose("MSBuild exited with code: " + itos(exit_code) + ". Log file: " + log_filepath);
- }
-
- build_tab->on_build_exit(exit_code == 0 ? MonoBuildTab::RESULT_SUCCESS : MonoBuildTab::RESULT_ERROR);
- } else {
- build_instance = MonoGCHandle::create_strong(mono_object);
- exited = false;
- }
-}
-
-GodotSharpBuilds::BuildProcess::BuildProcess(const MonoBuildInfo &p_build_info, GodotSharpBuild_ExitCallback p_callback) :
- build_info(p_build_info),
- build_tab(NULL),
- exit_callback(p_callback),
- exited(true),
- exit_code(-1) {
-}
diff --git a/modules/mono/editor/godotsharp_editor.cpp b/modules/mono/editor/godotsharp_editor.cpp
deleted file mode 100644
index 9d42528927..0000000000
--- a/modules/mono/editor/godotsharp_editor.cpp
+++ /dev/null
@@ -1,581 +0,0 @@
-/*************************************************************************/
-/* godotsharp_editor.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "godotsharp_editor.h"
-
-#include "core/message_queue.h"
-#include "core/os/os.h"
-#include "core/project_settings.h"
-#include "scene/gui/control.h"
-#include "scene/main/node.h"
-
-#include "../csharp_script.h"
-#include "../godotsharp_dirs.h"
-#include "../mono_gd/gd_mono.h"
-#include "../mono_gd/gd_mono_marshal.h"
-#include "../utils/path_utils.h"
-#include "bindings_generator.h"
-#include "csharp_project.h"
-#include "dotnet_solution.h"
-#include "godotsharp_export.h"
-
-#ifdef OSX_ENABLED
-#include "../utils/osx_utils.h"
-#endif
-
-#ifdef WINDOWS_ENABLED
-#include "../utils/mono_reg_utils.h"
-#endif
-
-GodotSharpEditor *GodotSharpEditor::singleton = NULL;
-
-bool GodotSharpEditor::_create_project_solution() {
-
- EditorProgress pr("create_csharp_solution", TTR("Generating solution..."), 2);
-
- pr.step(TTR("Generating C# project..."));
-
- String path = OS::get_singleton()->get_resource_dir();
- String name = ProjectSettings::get_singleton()->get("application/config/name");
- if (name.empty()) {
- name = "UnnamedProject";
- }
-
- String guid = CSharpProject::generate_game_project(path, name);
-
- if (guid.length()) {
-
- DotNetSolution solution(name);
-
- if (!solution.set_path(path)) {
- show_error_dialog(TTR("Failed to create solution."));
- return false;
- }
-
- DotNetSolution::ProjectInfo proj_info;
- proj_info.guid = guid;
- proj_info.relpath = name + ".csproj";
- proj_info.configs.push_back("Debug");
- proj_info.configs.push_back("Release");
- proj_info.configs.push_back("Tools");
-
- solution.add_new_project(name, proj_info);
-
- Error sln_error = solution.save();
-
- if (sln_error != OK) {
- show_error_dialog(TTR("Failed to save solution."));
- return false;
- }
-
- if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_CORE))
- return false;
-
- if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_EDITOR))
- return false;
-
- pr.step(TTR("Done"));
-
- // Here, after all calls to progress_task_step
- call_deferred("_remove_create_sln_menu_option");
-
- } else {
- show_error_dialog(TTR("Failed to create C# project."));
- }
-
- return true;
-}
-
-void GodotSharpEditor::_make_api_solutions_if_needed() {
- // I'm sick entirely of ProgressDialog
-
- static int attempts_left = 100;
-
- if (MessageQueue::get_singleton()->is_flushing() || !SceneTree::get_singleton()) {
- ERR_FAIL_COND(attempts_left == 0); // You've got to be kidding
-
- if (SceneTree::get_singleton()) {
- SceneTree::get_singleton()->connect("idle_frame", this, "_make_api_solutions_if_needed", Vector<Variant>());
- } else {
- call_deferred("_make_api_solutions_if_needed");
- }
-
- attempts_left--;
- return;
- }
-
- // Recursion guard needed because signals don't play well with ProgressDialog either, but unlike
- // the message queue, with signals the collateral damage should be minimal in the worst case.
- static bool recursion_guard = false;
- if (!recursion_guard) {
- recursion_guard = true;
-
- // Oneshot signals don't play well with ProgressDialog either, so we do it this way instead
- SceneTree::get_singleton()->disconnect("idle_frame", this, "_make_api_solutions_if_needed");
-
- _make_api_solutions_if_needed_impl();
-
- recursion_guard = false;
- }
-}
-
-void GodotSharpEditor::_make_api_solutions_if_needed_impl() {
- // If the project has a solution and C# project make sure the API assemblies are present and up to date
- String res_assemblies_dir = GodotSharpDirs::get_res_assemblies_dir();
-
- if (!FileAccess::exists(res_assemblies_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll")) ||
- GDMono::get_singleton()->metadata_is_api_assembly_invalidated(APIAssembly::API_CORE)) {
- if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_CORE))
- return;
- }
-
- if (!FileAccess::exists(res_assemblies_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll")) ||
- GDMono::get_singleton()->metadata_is_api_assembly_invalidated(APIAssembly::API_EDITOR)) {
- if (!GodotSharpBuilds::make_api_assembly(APIAssembly::API_EDITOR))
- return; // Redundant? I don't think so
- }
-}
-
-void GodotSharpEditor::_remove_create_sln_menu_option() {
-
- menu_popup->remove_item(menu_popup->get_item_index(MENU_CREATE_SLN));
-
- bottom_panel_btn->show();
-}
-
-void GodotSharpEditor::_show_about_dialog() {
-
- bool show_on_start = EDITOR_GET("mono/editor/show_info_on_start");
- about_dialog_checkbox->set_pressed(show_on_start);
- about_dialog->popup_centered_minsize();
-}
-
-void GodotSharpEditor::_toggle_about_dialog_on_start(bool p_enabled) {
-
- bool show_on_start = EDITOR_GET("mono/editor/show_info_on_start");
- if (show_on_start != p_enabled) {
- EditorSettings::get_singleton()->set_setting("mono/editor/show_info_on_start", p_enabled);
- }
-}
-
-void GodotSharpEditor::_build_solution_pressed() {
-
- if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path())) {
- if (!_create_project_solution())
- return; // Failed to create solution
- }
-
- MonoBottomPanel::get_singleton()->call("_build_project_pressed");
-}
-
-void GodotSharpEditor::_menu_option_pressed(int p_id) {
-
- switch (p_id) {
- case MENU_CREATE_SLN: {
-
- _create_project_solution();
- } break;
- case MENU_ABOUT_CSHARP: {
-
- _show_about_dialog();
- } break;
- default:
- ERR_FAIL();
- }
-}
-
-void GodotSharpEditor::_notification(int p_notification) {
-
- switch (p_notification) {
-
- case NOTIFICATION_READY: {
-
- bool show_info_dialog = EDITOR_GET("mono/editor/show_info_on_start");
- if (show_info_dialog) {
- about_dialog->set_exclusive(true);
- _show_about_dialog();
- // Once shown a first time, it can be seen again via the Mono menu - it doesn't have to be exclusive then.
- about_dialog->set_exclusive(false);
- }
- }
- }
-}
-
-void GodotSharpEditor::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("_build_solution_pressed"), &GodotSharpEditor::_build_solution_pressed);
- ClassDB::bind_method(D_METHOD("_create_project_solution"), &GodotSharpEditor::_create_project_solution);
- ClassDB::bind_method(D_METHOD("_make_api_solutions_if_needed"), &GodotSharpEditor::_make_api_solutions_if_needed);
- ClassDB::bind_method(D_METHOD("_remove_create_sln_menu_option"), &GodotSharpEditor::_remove_create_sln_menu_option);
- ClassDB::bind_method(D_METHOD("_toggle_about_dialog_on_start"), &GodotSharpEditor::_toggle_about_dialog_on_start);
- ClassDB::bind_method(D_METHOD("_menu_option_pressed", "id"), &GodotSharpEditor::_menu_option_pressed);
-}
-
-MonoBoolean godot_icall_MonoDevelopInstance_IsApplicationBundleInstalled(MonoString *p_bundle_id) {
-#ifdef OSX_ENABLED
- return (MonoBoolean)osx_is_app_bundle_installed(GDMonoMarshal::mono_string_to_godot(p_bundle_id));
-#else
- (void)p_bundle_id; // UNUSED
- ERR_FAIL_V(false);
-#endif
-}
-
-MonoString *godot_icall_Utils_OS_GetPlatformName() {
- return GDMonoMarshal::mono_string_from_godot(OS::get_singleton()->get_name());
-}
-
-void GodotSharpEditor::register_internal_calls() {
-
- static bool registered = false;
- ERR_FAIL_COND(registered);
- registered = true;
-
- mono_add_internal_call("GodotSharpTools.Editor.MonoDevelopInstance::IsApplicationBundleInstalled", (void *)godot_icall_MonoDevelopInstance_IsApplicationBundleInstalled);
- mono_add_internal_call("GodotSharpTools.Utils.OS::GetPlatformName", (void *)godot_icall_Utils_OS_GetPlatformName);
-
- GodotSharpBuilds::register_internal_calls();
- GodotSharpExport::register_internal_calls();
-}
-
-void GodotSharpEditor::show_error_dialog(const String &p_message, const String &p_title) {
-
- error_dialog->set_title(p_title);
- error_dialog->set_text(p_message);
- error_dialog->popup_centered_minsize();
-}
-
-Error GodotSharpEditor::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
-
- ExternalEditor editor = ExternalEditor(int(EditorSettings::get_singleton()->get("mono/editor/external_editor")));
-
- switch (editor) {
- case EDITOR_VSCODE: {
- static String vscode_path;
-
- if (vscode_path.empty() || !FileAccess::exists(vscode_path)) {
- // Try to search it again if it wasn't found last time or if it was removed from its location
- bool found = false;
-
- // TODO: Use initializer lists once C++11 is allowed
-
- static Vector<String> vscode_names;
- if (vscode_names.empty()) {
- vscode_names.push_back("code");
- vscode_names.push_back("code-oss");
- vscode_names.push_back("vscode");
- vscode_names.push_back("vscode-oss");
- vscode_names.push_back("visual-studio-code");
- vscode_names.push_back("visual-studio-code-oss");
- }
- for (int i = 0; i < vscode_names.size(); i++) {
- vscode_path = path_which(vscode_names[i]);
- if (!vscode_path.empty()) {
- found = true;
- break;
- }
- }
-
- if (!found)
- vscode_path.clear(); // Not found, clear so next time the empty() check is enough
- }
-
- List<String> args;
-
-#ifdef OSX_ENABLED
- // The package path is '/Applications/Visual Studio Code.app'
- static const String vscode_bundle_id = "com.microsoft.VSCode";
- static bool osx_app_bundle_installed = osx_is_app_bundle_installed(vscode_bundle_id);
-
- if (osx_app_bundle_installed) {
- args.push_back("-b");
- args.push_back(vscode_bundle_id);
-
- // The reusing of existing windows made by the 'open' command might not choose a wubdiw that is
- // editing our folder. It's better to ask for a new window and let VSCode do the window management.
- args.push_back("-n");
-
- // The open process must wait until the application finishes (which is instant in VSCode's case)
- args.push_back("--wait-apps");
-
- args.push_back("--args");
- }
-#endif
-
- args.push_back(ProjectSettings::get_singleton()->get_resource_path());
-
- String script_path = ProjectSettings::get_singleton()->globalize_path(p_script->get_path());
-
- if (p_line >= 0) {
- args.push_back("-g");
- args.push_back(script_path + ":" + itos(p_line + 1) + ":" + itos(p_col));
- } else {
- args.push_back(script_path);
- }
-
-#ifdef OSX_ENABLED
- ERR_EXPLAIN("Cannot find code editor: VSCode");
- ERR_FAIL_COND_V(!osx_app_bundle_installed && vscode_path.empty(), ERR_FILE_NOT_FOUND);
-
- String command = osx_app_bundle_installed ? "/usr/bin/open" : vscode_path;
-#else
- ERR_EXPLAIN("Cannot find code editor: VSCode");
- ERR_FAIL_COND_V(vscode_path.empty(), ERR_FILE_NOT_FOUND);
-
- String command = vscode_path;
-#endif
-
- Error err = OS::get_singleton()->execute(command, args, false);
-
- if (err != OK) {
- ERR_PRINT("Error when trying to execute code editor: VSCode");
- return err;
- }
- } break;
-#ifdef OSX_ENABLED
- case EDITOR_VISUALSTUDIO_MAC:
- // [[fallthrough]];
-#endif
- case EDITOR_MONODEVELOP: {
-#ifdef OSX_ENABLED
- bool is_visualstudio = editor == EDITOR_VISUALSTUDIO_MAC;
-
- MonoDevelopInstance **instance = is_visualstudio ?
- &visualstudio_mac_instance :
- &monodevelop_instance;
-
- MonoDevelopInstance::EditorId editor_id = is_visualstudio ?
- MonoDevelopInstance::VISUALSTUDIO_FOR_MAC :
- MonoDevelopInstance::MONODEVELOP;
-#else
- MonoDevelopInstance **instance = &monodevelop_instance;
- MonoDevelopInstance::EditorId editor_id = MonoDevelopInstance::MONODEVELOP;
-#endif
-
- if (!*instance)
- *instance = memnew(MonoDevelopInstance(GodotSharpDirs::get_project_sln_path(), editor_id));
-
- String script_path = ProjectSettings::get_singleton()->globalize_path(p_script->get_path());
-
- if (p_line >= 0) {
- script_path += ";" + itos(p_line + 1) + ";" + itos(p_col);
- }
-
- (*instance)->execute(script_path);
- } break;
- default:
- return ERR_UNAVAILABLE;
- }
-
- return OK;
-}
-
-bool GodotSharpEditor::overrides_external_editor() {
-
- return ExternalEditor(int(EditorSettings::get_singleton()->get("mono/editor/external_editor"))) != EDITOR_NONE;
-}
-
-GodotSharpEditor::GodotSharpEditor(EditorNode *p_editor) {
-
- singleton = this;
-
- monodevelop_instance = NULL;
-#ifdef OSX_ENABLED
- visualstudio_mac_instance = NULL;
-#endif
-
- editor = p_editor;
-
- error_dialog = memnew(AcceptDialog);
- editor->get_gui_base()->add_child(error_dialog);
-
- bottom_panel_btn = editor->add_bottom_panel_item(TTR("Mono"), memnew(MonoBottomPanel(editor)));
-
- godotsharp_builds = memnew(GodotSharpBuilds);
-
- editor->add_child(memnew(MonoReloadNode));
-
- menu_popup = memnew(PopupMenu);
- menu_popup->hide();
- menu_popup->set_as_toplevel(true);
- menu_popup->set_pass_on_modal_close_click(false);
-
- editor->add_tool_submenu_item("Mono", menu_popup);
-
- // TODO: Remove or edit this info dialog once Mono support is no longer in alpha
- {
- menu_popup->add_item(TTR("About C# support"), MENU_ABOUT_CSHARP);
- about_dialog = memnew(AcceptDialog);
- editor->get_gui_base()->add_child(about_dialog);
- about_dialog->set_title("Important: C# support is not feature-complete");
-
- // We don't use set_text() as the default AcceptDialog Label doesn't play well with the TextureRect and CheckBox
- // we'll add. Instead we add containers and a new autowrapped Label inside.
-
- // Main VBoxContainer (icon + label on top, checkbox at bottom)
- VBoxContainer *about_vbc = memnew(VBoxContainer);
- about_dialog->add_child(about_vbc);
-
- // HBoxContainer for icon + label
- HBoxContainer *about_hbc = memnew(HBoxContainer);
- about_vbc->add_child(about_hbc);
-
- TextureRect *about_icon = memnew(TextureRect);
- about_hbc->add_child(about_icon);
- Ref<Texture> about_icon_tex = about_icon->get_icon("NodeWarning", "EditorIcons");
- about_icon->set_texture(about_icon_tex);
-
- Label *about_label = memnew(Label);
- about_hbc->add_child(about_label);
- about_label->set_custom_minimum_size(Size2(600, 150) * EDSCALE);
- about_label->set_v_size_flags(Control::SIZE_EXPAND_FILL);
- about_label->set_autowrap(true);
- String about_text =
- String("C# support in Godot Engine is in late alpha stage and, while already usable, ") +
- "it is not meant for use in production.\n\n" +
- "Projects can be exported to Linux, macOS and Windows, but not yet to mobile or web platforms. " +
- "Bugs and usability issues will be addressed gradually over future releases, " +
- "potentially including compatibility breaking changes as new features are implemented for a better overall C# experience.\n\n" +
- "If you experience issues with this Mono build, please report them on Godot's issue tracker with details about your system, MSBuild version, IDE, etc.:\n\n" +
- " https://github.com/godotengine/godot/issues\n\n" +
- "Your critical feedback at this stage will play a great role in shaping the C# support in future releases, so thank you!";
- about_label->set_text(about_text);
-
- EDITOR_DEF("mono/editor/show_info_on_start", true);
-
- // CheckBox in main container
- about_dialog_checkbox = memnew(CheckBox);
- about_vbc->add_child(about_dialog_checkbox);
- about_dialog_checkbox->set_text("Show this warning when starting the editor");
- about_dialog_checkbox->connect("toggled", this, "_toggle_about_dialog_on_start");
- }
-
- String sln_path = GodotSharpDirs::get_project_sln_path();
- String csproj_path = GodotSharpDirs::get_project_csproj_path();
-
- if (FileAccess::exists(sln_path) && FileAccess::exists(csproj_path)) {
- // Defer this task because EditorProgress calls Main::iterarion() and the main loop is not yet initialized.
- call_deferred("_make_api_solutions_if_needed");
- } else {
- bottom_panel_btn->hide();
- menu_popup->add_item(TTR("Create C# solution"), MENU_CREATE_SLN);
- }
-
- menu_popup->connect("id_pressed", this, "_menu_option_pressed");
-
- ToolButton *build_button = memnew(ToolButton);
- build_button->set_text("Build");
- build_button->set_tooltip("Build solution");
- build_button->set_focus_mode(Control::FOCUS_NONE);
- build_button->connect("pressed", this, "_build_solution_pressed");
- editor->get_menu_hb()->add_child(build_button);
-
- // External editor settings
- EditorSettings *ed_settings = EditorSettings::get_singleton();
- EDITOR_DEF("mono/editor/external_editor", EDITOR_NONE);
-
- String settings_hint_str = "Disabled";
-
-#if defined(WINDOWS_ENABLED)
- settings_hint_str += ",MonoDevelop,Visual Studio Code";
-#elif defined(OSX_ENABLED)
- settings_hint_str += ",Visual Studio,MonoDevelop,Visual Studio Code";
-#elif defined(UNIX_ENABLED)
- settings_hint_str += ",MonoDevelop,Visual Studio Code";
-#endif
-
- ed_settings->add_property_hint(PropertyInfo(Variant::INT, "mono/editor/external_editor", PROPERTY_HINT_ENUM, settings_hint_str));
-
- // Export plugin
- Ref<GodotSharpExport> godotsharp_export;
- godotsharp_export.instance();
- EditorExport::get_singleton()->add_export_plugin(godotsharp_export);
-}
-
-GodotSharpEditor::~GodotSharpEditor() {
-
- singleton = NULL;
-
- memdelete(godotsharp_builds);
-
- if (monodevelop_instance) {
- memdelete(monodevelop_instance);
- monodevelop_instance = NULL;
- }
-}
-
-MonoReloadNode *MonoReloadNode::singleton = NULL;
-
-void MonoReloadNode::_reload_timer_timeout() {
-
- if (CSharpLanguage::get_singleton()->is_assembly_reloading_needed()) {
- CSharpLanguage::get_singleton()->reload_assemblies(false);
- }
-}
-
-void MonoReloadNode::restart_reload_timer() {
-
- reload_timer->stop();
- reload_timer->start();
-}
-
-void MonoReloadNode::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("_reload_timer_timeout"), &MonoReloadNode::_reload_timer_timeout);
-}
-
-void MonoReloadNode::_notification(int p_what) {
- switch (p_what) {
- case MainLoop::NOTIFICATION_WM_FOCUS_IN: {
- restart_reload_timer();
- if (CSharpLanguage::get_singleton()->is_assembly_reloading_needed()) {
- CSharpLanguage::get_singleton()->reload_assemblies(false);
- }
- } break;
- default: {
- } break;
- };
-}
-
-MonoReloadNode::MonoReloadNode() {
-
- singleton = this;
-
- reload_timer = memnew(Timer);
- add_child(reload_timer);
- reload_timer->set_one_shot(false);
- reload_timer->set_wait_time(EDITOR_DEF("mono/assembly_watch_interval_sec", 0.5));
- reload_timer->connect("timeout", this, "_reload_timer_timeout");
- reload_timer->start();
-}
-
-MonoReloadNode::~MonoReloadNode() {
-
- singleton = NULL;
-}
diff --git a/modules/mono/editor/godotsharp_editor.h b/modules/mono/editor/godotsharp_editor.h
deleted file mode 100644
index d9523c384c..0000000000
--- a/modules/mono/editor/godotsharp_editor.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/*************************************************************************/
-/* godotsharp_editor.h */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#ifndef GODOTSHARP_EDITOR_H
-#define GODOTSHARP_EDITOR_H
-
-#include "godotsharp_builds.h"
-#include "monodevelop_instance.h"
-
-class GodotSharpEditor : public Node {
- GDCLASS(GodotSharpEditor, Object)
-
- EditorNode *editor;
-
- MenuButton *menu_button;
- PopupMenu *menu_popup;
-
- AcceptDialog *error_dialog;
- AcceptDialog *about_dialog;
- CheckBox *about_dialog_checkbox;
-
- ToolButton *bottom_panel_btn;
-
- GodotSharpBuilds *godotsharp_builds;
-
- MonoDevelopInstance *monodevelop_instance;
-#ifdef OSX_ENABLED
- MonoDevelopInstance *visualstudio_mac_instance;
-#endif
-
- bool _create_project_solution();
- void _make_api_solutions_if_needed();
- void _make_api_solutions_if_needed_impl();
-
- void _remove_create_sln_menu_option();
- void _show_about_dialog();
- void _toggle_about_dialog_on_start(bool p_enabled);
-
- void _menu_option_pressed(int p_id);
-
- void _build_solution_pressed();
-
- static GodotSharpEditor *singleton;
-
-protected:
- void _notification(int p_notification);
- static void _bind_methods();
-
-public:
- enum MenuOptions {
- MENU_CREATE_SLN,
- MENU_ABOUT_CSHARP,
- };
-
- enum ExternalEditor {
- EDITOR_NONE,
-#if defined(WINDOWS_ENABLED)
- //EDITOR_VISUALSTUDIO, // TODO
- EDITOR_MONODEVELOP,
- EDITOR_VSCODE
-#elif defined(OSX_ENABLED)
- EDITOR_VISUALSTUDIO_MAC,
- EDITOR_MONODEVELOP,
- EDITOR_VSCODE
-#elif defined(UNIX_ENABLED)
- EDITOR_MONODEVELOP,
- EDITOR_VSCODE
-#endif
- };
-
- _FORCE_INLINE_ static GodotSharpEditor *get_singleton() { return singleton; }
-
- static void register_internal_calls();
-
- void show_error_dialog(const String &p_message, const String &p_title = "Error");
-
- Error open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col);
- bool overrides_external_editor();
-
- GodotSharpEditor(EditorNode *p_editor);
- ~GodotSharpEditor();
-};
-
-class MonoReloadNode : public Node {
- GDCLASS(MonoReloadNode, Node)
-
- Timer *reload_timer;
-
- void _reload_timer_timeout();
-
- static MonoReloadNode *singleton;
-
-protected:
- static void _bind_methods();
-
- void _notification(int p_what);
-
-public:
- _FORCE_INLINE_ static MonoReloadNode *get_singleton() { return singleton; }
-
- void restart_reload_timer();
-
- MonoReloadNode();
- ~MonoReloadNode();
-};
-
-#endif // GODOTSHARP_EDITOR_H
diff --git a/modules/mono/editor/godotsharp_export.cpp b/modules/mono/editor/godotsharp_export.cpp
index ae5b939b26..020bb70a08 100644
--- a/modules/mono/editor/godotsharp_export.cpp
+++ b/modules/mono/editor/godotsharp_export.cpp
@@ -30,169 +30,28 @@
#include "godotsharp_export.h"
-#include "core/version.h"
-
-#include "../csharp_script.h"
-#include "../godotsharp_defs.h"
-#include "../godotsharp_dirs.h"
-#include "../mono_gd/gd_mono_class.h"
-#include "../mono_gd/gd_mono_marshal.h"
-#include "csharp_project.h"
-#include "godotsharp_builds.h"
-
-static MonoString *godot_icall_GodotSharpExport_GetTemplatesDir() {
- String current_version = VERSION_FULL_CONFIG;
- String templates_dir = EditorSettings::get_singleton()->get_templates_dir().plus_file(current_version);
- return GDMonoMarshal::mono_string_from_godot(ProjectSettings::get_singleton()->globalize_path(templates_dir));
-}
-
-static MonoString *godot_icall_GodotSharpExport_GetDataDirName() {
- String appname = ProjectSettings::get_singleton()->get("application/config/name");
- String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
- return GDMonoMarshal::mono_string_from_godot("data_" + appname_safe);
-}
-
-void GodotSharpExport::register_internal_calls() {
- static bool registered = false;
- ERR_FAIL_COND(registered);
- registered = true;
-
- mono_add_internal_call("GodotSharpTools.Editor.GodotSharpExport::GetTemplatesDir", (void *)godot_icall_GodotSharpExport_GetTemplatesDir);
- mono_add_internal_call("GodotSharpTools.Editor.GodotSharpExport::GetDataDirName", (void *)godot_icall_GodotSharpExport_GetDataDirName);
-}
-
-void GodotSharpExport::_export_file(const String &p_path, const String &p_type, const Set<String> &) {
-
- if (p_type != CSharpLanguage::get_singleton()->get_type())
- return;
-
- ERR_FAIL_COND(p_path.get_extension() != CSharpLanguage::get_singleton()->get_extension());
-
- // TODO what if the source file is not part of the game's C# project
-
- if (!GLOBAL_GET("mono/export/include_scripts_content")) {
- // We don't want to include the source code on exported games
- add_file(p_path, Vector<uint8_t>(), false);
- skip();
- }
-}
-
-void GodotSharpExport::_export_begin(const Set<String> &p_features, bool p_debug, const String &p_path, int p_flags) {
-
- // TODO right now there is no way to stop the export process with an error
-
- ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized());
- ERR_FAIL_NULL(TOOLS_DOMAIN);
- ERR_FAIL_NULL(GDMono::get_singleton()->get_editor_tools_assembly());
-
- if (FileAccess::exists(GodotSharpDirs::get_project_sln_path())) {
- String build_config = p_debug ? "Debug" : "Release";
-
- String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata." + String(p_debug ? "debug" : "release"));
- Error metadata_err = CSharpProject::generate_scripts_metadata(GodotSharpDirs::get_project_csproj_path(), scripts_metadata_path);
- ERR_FAIL_COND(metadata_err != OK);
-
- ERR_FAIL_COND(!_add_file(scripts_metadata_path, scripts_metadata_path));
-
- // Turn export features into defines
- Vector<String> godot_defines;
- for (Set<String>::Element *E = p_features.front(); E; E = E->next()) {
- godot_defines.push_back(E->get());
- }
- ERR_FAIL_COND(!GodotSharpBuilds::build_project_blocking(build_config, godot_defines));
-
- // Add dependency assemblies
-
- Map<String, String> dependencies;
-
- String project_dll_name = ProjectSettings::get_singleton()->get("application/config/name");
- if (project_dll_name.empty()) {
- project_dll_name = "UnnamedProject";
- }
+#include <mono/metadata/image.h>
- String project_dll_src_dir = GodotSharpDirs::get_res_temp_assemblies_base_dir().plus_file(build_config);
- String project_dll_src_path = project_dll_src_dir.plus_file(project_dll_name + ".dll");
- dependencies.insert(project_dll_name, project_dll_src_path);
+#include "../mono_gd/gd_mono.h"
+#include "../mono_gd/gd_mono_assembly.h"
- {
- MonoDomain *export_domain = GDMonoUtils::create_domain("GodotEngine.ProjectExportDomain");
- ERR_FAIL_NULL(export_domain);
- _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(export_domain);
+String get_assemblyref_name(MonoImage *p_image, int index) {
+ const MonoTableInfo *table_info = mono_image_get_table_info(p_image, MONO_TABLE_ASSEMBLYREF);
- _GDMONO_SCOPE_DOMAIN_(export_domain);
+ uint32_t cols[MONO_ASSEMBLYREF_SIZE];
- GDMonoAssembly *scripts_assembly = NULL;
- bool load_success = GDMono::get_singleton()->load_assembly_from(project_dll_name,
- project_dll_src_path, &scripts_assembly, /* refonly: */ true);
+ mono_metadata_decode_row(table_info, index, cols, MONO_ASSEMBLYREF_SIZE);
- ERR_EXPLAIN("Cannot load refonly assembly: " + project_dll_name);
- ERR_FAIL_COND(!load_success);
-
- Vector<String> search_dirs;
- GDMonoAssembly::fill_search_dirs(search_dirs, build_config);
- Error depend_error = _get_assembly_dependencies(scripts_assembly, search_dirs, dependencies);
- ERR_FAIL_COND(depend_error != OK);
- }
-
- for (Map<String, String>::Element *E = dependencies.front(); E; E = E->next()) {
- String depend_src_path = E->value();
- String depend_dst_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(depend_src_path.get_file());
- ERR_FAIL_COND(!_add_file(depend_src_path, depend_dst_path));
- }
- }
-
- // Mono specific export template extras (data dir)
-
- GDMonoClass *export_class = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Editor", "GodotSharpExport");
- ERR_FAIL_NULL(export_class);
- GDMonoMethod *export_begin_method = export_class->get_method("_ExportBegin", 4);
- ERR_FAIL_NULL(export_begin_method);
-
- MonoArray *features = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(String), p_features.size());
- int i = 0;
- for (const Set<String>::Element *E = p_features.front(); E; E = E->next()) {
- MonoString *boxed = GDMonoMarshal::mono_string_from_godot(E->get());
- mono_array_set(features, MonoString *, i, boxed);
- i++;
- }
-
- MonoBoolean debug = p_debug;
- MonoString *path = GDMonoMarshal::mono_string_from_godot(p_path);
- uint32_t flags = p_flags;
- void *args[4] = { features, &debug, path, &flags };
- MonoException *exc = NULL;
- export_begin_method->invoke_raw(NULL, args, &exc);
-
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- ERR_FAIL();
- }
+ return String::utf8(mono_metadata_string_heap(p_image, cols[MONO_ASSEMBLYREF_NAME]));
}
-bool GodotSharpExport::_add_file(const String &p_src_path, const String &p_dst_path, bool p_remap) {
-
- FileAccessRef f = FileAccess::open(p_src_path, FileAccess::READ);
- ERR_FAIL_COND_V(!f, false);
-
- Vector<uint8_t> data;
- data.resize(f->get_len());
- f->get_buffer(data.ptrw(), data.size());
-
- add_file(p_dst_path, data, p_remap);
-
- return true;
-}
-
-Error GodotSharpExport::_get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Map<String, String> &r_dependencies) {
-
+Error GodotSharpExport::get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Dictionary &r_dependencies) {
MonoImage *image = p_assembly->get_image();
for (int i = 0; i < mono_image_get_table_rows(image, MONO_TABLE_ASSEMBLYREF); i++) {
- MonoAssemblyName *ref_aname = aname_prealloc;
- mono_assembly_get_assemblyref(image, i, ref_aname);
- String ref_name = mono_assembly_name_get_name(ref_aname);
+ String ref_name = get_assemblyref_name(image, i);
- if (r_dependencies.find(ref_name))
+ if (r_dependencies.has(ref_name))
continue;
GDMonoAssembly *ref_assembly = NULL;
@@ -231,24 +90,34 @@ Error GodotSharpExport::_get_assembly_dependencies(GDMonoAssembly *p_assembly, c
ERR_FAIL_V(ERR_CANT_RESOLVE);
}
- r_dependencies.insert(ref_name, ref_assembly->get_path());
+ r_dependencies[ref_name] = ref_assembly->get_path();
- Error err = _get_assembly_dependencies(ref_assembly, p_search_dirs, r_dependencies);
- if (err != OK)
- return err;
+ Error err = get_assembly_dependencies(ref_assembly, p_search_dirs, r_dependencies);
+ if (err != OK) {
+ ERR_EXPLAIN("Cannot load one of the dependencies for the assembly: " + ref_name);
+ ERR_FAIL_V(err);
+ }
}
return OK;
}
-GodotSharpExport::GodotSharpExport() {
- // MonoAssemblyName is an incomplete type (internal to mono), so we can't allocate it ourselves.
- // There isn't any api to allocate an empty one either, so we need to do it this way.
- aname_prealloc = mono_assembly_name_new("whatever");
- mono_assembly_name_free(aname_prealloc); // "it does not frees the object itself, only the name members" (typo included)
-}
+Error GodotSharpExport::get_exported_assembly_dependencies(const String &p_project_dll_name, const String &p_project_dll_src_path, const String &p_build_config, const String &p_custom_lib_dir, Dictionary &r_dependencies) {
+ MonoDomain *export_domain = GDMonoUtils::create_domain("GodotEngine.ProjectExportDomain");
+ ERR_FAIL_NULL_V(export_domain, FAILED);
+ _GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(export_domain);
+
+ _GDMONO_SCOPE_DOMAIN_(export_domain);
+
+ GDMonoAssembly *scripts_assembly = NULL;
+ bool load_success = GDMono::get_singleton()->load_assembly_from(p_project_dll_name,
+ p_project_dll_src_path, &scripts_assembly, /* refonly: */ true);
+
+ ERR_EXPLAIN("Cannot load assembly (refonly): " + p_project_dll_name);
+ ERR_FAIL_COND_V(!load_success, ERR_CANT_RESOLVE);
+
+ Vector<String> search_dirs;
+ GDMonoAssembly::fill_search_dirs(search_dirs, p_build_config, p_custom_lib_dir);
-GodotSharpExport::~GodotSharpExport() {
- if (aname_prealloc)
- mono_free(aname_prealloc);
+ return get_assembly_dependencies(scripts_assembly, search_dirs, r_dependencies);
}
diff --git a/modules/mono/editor/godotsharp_export.h b/modules/mono/editor/godotsharp_export.h
index 4dc8ea75d5..8d121a6bc3 100644
--- a/modules/mono/editor/godotsharp_export.h
+++ b/modules/mono/editor/godotsharp_export.h
@@ -31,29 +31,19 @@
#ifndef GODOTSHARP_EXPORT_H
#define GODOTSHARP_EXPORT_H
-#include <mono/metadata/image.h>
-
-#include "editor/editor_export.h"
+#include "core/dictionary.h"
+#include "core/error_list.h"
+#include "core/ustring.h"
#include "../mono_gd/gd_mono_header.h"
-class GodotSharpExport : public EditorExportPlugin {
-
- MonoAssemblyName *aname_prealloc;
-
- bool _add_file(const String &p_src_path, const String &p_dst_path, bool p_remap = false);
-
- Error _get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Map<String, String> &r_dependencies);
-
-protected:
- virtual void _export_file(const String &p_path, const String &p_type, const Set<String> &p_features);
- virtual void _export_begin(const Set<String> &p_features, bool p_debug, const String &p_path, int p_flags);
+namespace GodotSharpExport {
-public:
- static void register_internal_calls();
+Error get_exported_assembly_dependencies(const String &p_project_dll_name,
+ const String &p_project_dll_src_path, const String &p_build_config,
+ const String &p_custom_lib_dir, Dictionary &r_dependencies);
+Error get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Dictionary &r_dependencies);
- GodotSharpExport();
- ~GodotSharpExport();
-};
+} // namespace GodotSharpExport
#endif // GODOTSHARP_EXPORT_H
diff --git a/modules/mono/editor/mono_bottom_panel.cpp b/modules/mono/editor/mono_bottom_panel.cpp
deleted file mode 100644
index 5d9e39b6c2..0000000000
--- a/modules/mono/editor/mono_bottom_panel.cpp
+++ /dev/null
@@ -1,528 +0,0 @@
-/*************************************************************************/
-/* mono_bottom_panel.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "mono_bottom_panel.h"
-
-#include "editor/plugins/script_editor_plugin.h"
-#include "editor/script_editor_debugger.h"
-
-#include "../csharp_script.h"
-#include "../godotsharp_dirs.h"
-#include "csharp_project.h"
-#include "godotsharp_editor.h"
-
-MonoBottomPanel *MonoBottomPanel::singleton = NULL;
-
-void MonoBottomPanel::_update_build_tabs_list() {
-
- build_tabs_list->clear();
-
- int current_tab = build_tabs->get_current_tab();
-
- bool no_current_tab = current_tab < 0 || current_tab >= build_tabs->get_tab_count();
-
- for (int i = 0; i < build_tabs->get_child_count(); i++) {
-
- MonoBuildTab *tab = Object::cast_to<MonoBuildTab>(build_tabs->get_child(i));
-
- if (tab) {
- String item_name = tab->build_info.solution.get_file().get_basename();
- item_name += " [" + tab->build_info.configuration + "]";
-
- build_tabs_list->add_item(item_name, tab->get_icon_texture());
-
- String item_tooltip = "Solution: " + tab->build_info.solution;
- item_tooltip += "\nConfiguration: " + tab->build_info.configuration;
- item_tooltip += "\nStatus: ";
-
- if (tab->build_exited) {
- item_tooltip += tab->build_result == MonoBuildTab::RESULT_SUCCESS ? "Succeeded" : "Errored";
- } else {
- item_tooltip += "Running";
- }
-
- if (!tab->build_exited || tab->build_result == MonoBuildTab::RESULT_ERROR) {
- item_tooltip += "\nErrors: " + itos(tab->error_count);
- }
-
- item_tooltip += "\nWarnings: " + itos(tab->warning_count);
-
- build_tabs_list->set_item_tooltip(i, item_tooltip);
-
- if (no_current_tab || current_tab == i) {
- build_tabs_list->select(i);
- _build_tabs_item_selected(i);
- }
- }
- }
-}
-
-void MonoBottomPanel::add_build_tab(MonoBuildTab *p_build_tab) {
-
- build_tabs->add_child(p_build_tab);
- raise_build_tab(p_build_tab);
-}
-
-void MonoBottomPanel::raise_build_tab(MonoBuildTab *p_build_tab) {
-
- ERR_FAIL_COND(p_build_tab->get_parent() != build_tabs);
- build_tabs->move_child(p_build_tab, 0);
- _update_build_tabs_list();
-}
-
-void MonoBottomPanel::show_build_tab() {
-
- for (int i = 0; i < panel_tabs->get_tab_count(); i++) {
- if (panel_tabs->get_tab_control(i) == panel_builds_tab) {
- panel_tabs->set_current_tab(i);
- editor->make_bottom_panel_item_visible(this);
- return;
- }
- }
-
- ERR_PRINT("Builds tab not found");
-}
-
-void MonoBottomPanel::_build_tabs_item_selected(int p_idx) {
-
- ERR_FAIL_INDEX(p_idx, build_tabs->get_tab_count());
-
- build_tabs->set_current_tab(p_idx);
- if (!build_tabs->is_visible())
- build_tabs->set_visible(true);
-
- warnings_btn->set_visible(true);
- errors_btn->set_visible(true);
- view_log_btn->set_visible(true);
-}
-
-void MonoBottomPanel::_build_tabs_nothing_selected() {
-
- if (build_tabs->get_tab_count() != 0) { // just in case
- build_tabs->set_visible(false);
-
- // This callback is called when clicking on the empty space of the list.
- // ItemList won't deselect the items automatically, so we must do it ourselves.
- build_tabs_list->unselect_all();
- }
-
- warnings_btn->set_visible(false);
- errors_btn->set_visible(false);
- view_log_btn->set_visible(false);
-}
-
-void MonoBottomPanel::_warnings_toggled(bool p_pressed) {
-
- int current_tab = build_tabs->get_current_tab();
- ERR_FAIL_INDEX(current_tab, build_tabs->get_tab_count());
- MonoBuildTab *build_tab = Object::cast_to<MonoBuildTab>(build_tabs->get_child(current_tab));
- build_tab->warnings_visible = p_pressed;
- build_tab->_update_issues_list();
-}
-
-void MonoBottomPanel::_errors_toggled(bool p_pressed) {
-
- int current_tab = build_tabs->get_current_tab();
- ERR_FAIL_INDEX(current_tab, build_tabs->get_tab_count());
- MonoBuildTab *build_tab = Object::cast_to<MonoBuildTab>(build_tabs->get_child(current_tab));
- build_tab->errors_visible = p_pressed;
- build_tab->_update_issues_list();
-}
-
-void MonoBottomPanel::_build_project_pressed() {
-
- if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path()))
- return; // No solution to build
-
- String scripts_metadata_path_editor = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor");
- String scripts_metadata_path_player = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata.editor_player");
-
- Error metadata_err = CSharpProject::generate_scripts_metadata(GodotSharpDirs::get_project_csproj_path(), scripts_metadata_path_editor);
- ERR_FAIL_COND(metadata_err != OK);
-
- if (FileAccess::exists(scripts_metadata_path_editor)) {
- DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- Error copy_err = da->copy(scripts_metadata_path_editor, scripts_metadata_path_player);
-
- ERR_EXPLAIN("Failed to copy scripts metadata file");
- ERR_FAIL_COND(copy_err != OK);
- }
-
- Vector<String> godot_defines;
- godot_defines.push_back(OS::get_singleton()->get_name());
- godot_defines.push_back((sizeof(void *) == 4 ? "32" : "64"));
- bool build_success = GodotSharpBuilds::get_singleton()->build_project_blocking("Tools", godot_defines);
-
- if (build_success) {
- // Notify running game for hot-reload
- ScriptEditor::get_singleton()->get_debugger()->reload_scripts();
-
- // Hot-reload in the editor
- MonoReloadNode::get_singleton()->restart_reload_timer();
-
- if (CSharpLanguage::get_singleton()->is_assembly_reloading_needed()) {
- CSharpLanguage::get_singleton()->reload_assemblies(false);
- }
- }
-}
-
-void MonoBottomPanel::_view_log_pressed() {
-
- if (build_tabs_list->is_anything_selected()) {
- Vector<int> selected_items = build_tabs_list->get_selected_items();
- CRASH_COND(selected_items.size() != 1);
- int selected_item = selected_items[0];
-
- MonoBuildTab *build_tab = Object::cast_to<MonoBuildTab>(build_tabs->get_tab_control(selected_item));
- ERR_FAIL_NULL(build_tab);
-
- String log_dirpath = build_tab->get_build_info().get_log_dirpath();
-
- OS::get_singleton()->shell_open(log_dirpath.plus_file(GodotSharpBuilds::get_msbuild_log_filename()));
- }
-}
-
-void MonoBottomPanel::_notification(int p_what) {
-
- switch (p_what) {
-
- case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
- panel_tabs->add_style_override("panel", editor->get_gui_base()->get_stylebox("DebuggerPanel", "EditorStyles"));
- panel_tabs->add_style_override("tab_fg", editor->get_gui_base()->get_stylebox("DebuggerTabFG", "EditorStyles"));
- panel_tabs->add_style_override("tab_bg", editor->get_gui_base()->get_stylebox("DebuggerTabBG", "EditorStyles"));
- } break;
- }
-}
-
-void MonoBottomPanel::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("_build_project_pressed"), &MonoBottomPanel::_build_project_pressed);
- ClassDB::bind_method(D_METHOD("_view_log_pressed"), &MonoBottomPanel::_view_log_pressed);
- ClassDB::bind_method(D_METHOD("_warnings_toggled", "pressed"), &MonoBottomPanel::_warnings_toggled);
- ClassDB::bind_method(D_METHOD("_errors_toggled", "pressed"), &MonoBottomPanel::_errors_toggled);
- ClassDB::bind_method(D_METHOD("_build_tabs_item_selected", "idx"), &MonoBottomPanel::_build_tabs_item_selected);
- ClassDB::bind_method(D_METHOD("_build_tabs_nothing_selected"), &MonoBottomPanel::_build_tabs_nothing_selected);
-}
-
-MonoBottomPanel::MonoBottomPanel(EditorNode *p_editor) {
-
- singleton = this;
-
- editor = p_editor;
-
- set_v_size_flags(SIZE_EXPAND_FILL);
- set_anchors_and_margins_preset(Control::PRESET_WIDE);
-
- panel_tabs = memnew(TabContainer);
- panel_tabs->set_tab_align(TabContainer::ALIGN_LEFT);
- panel_tabs->add_style_override("panel", editor->get_gui_base()->get_stylebox("DebuggerPanel", "EditorStyles"));
- panel_tabs->add_style_override("tab_fg", editor->get_gui_base()->get_stylebox("DebuggerTabFG", "EditorStyles"));
- panel_tabs->add_style_override("tab_bg", editor->get_gui_base()->get_stylebox("DebuggerTabBG", "EditorStyles"));
- panel_tabs->set_custom_minimum_size(Size2(0, 228) * EDSCALE);
- panel_tabs->set_v_size_flags(SIZE_EXPAND_FILL);
- add_child(panel_tabs);
-
- { // Builds
- panel_builds_tab = memnew(VBoxContainer);
- panel_builds_tab->set_name(TTR("Builds"));
- panel_builds_tab->set_h_size_flags(SIZE_EXPAND_FILL);
- panel_tabs->add_child(panel_builds_tab);
-
- HBoxContainer *toolbar_hbc = memnew(HBoxContainer);
- toolbar_hbc->set_h_size_flags(SIZE_EXPAND_FILL);
- panel_builds_tab->add_child(toolbar_hbc);
-
- Button *build_project_btn = memnew(Button);
- build_project_btn->set_text(TTR("Build Project"));
- build_project_btn->set_focus_mode(FOCUS_NONE);
- build_project_btn->connect("pressed", this, "_build_project_pressed");
- toolbar_hbc->add_child(build_project_btn);
-
- toolbar_hbc->add_spacer();
-
- warnings_btn = memnew(ToolButton);
- warnings_btn->set_text(TTR("Warnings"));
- warnings_btn->set_toggle_mode(true);
- warnings_btn->set_pressed(true);
- warnings_btn->set_visible(false);
- warnings_btn->set_focus_mode(FOCUS_NONE);
- warnings_btn->connect("toggled", this, "_warnings_toggled");
- toolbar_hbc->add_child(warnings_btn);
-
- errors_btn = memnew(ToolButton);
- errors_btn->set_text(TTR("Errors"));
- errors_btn->set_toggle_mode(true);
- errors_btn->set_pressed(true);
- errors_btn->set_visible(false);
- errors_btn->set_focus_mode(FOCUS_NONE);
- errors_btn->connect("toggled", this, "_errors_toggled");
- toolbar_hbc->add_child(errors_btn);
-
- toolbar_hbc->add_spacer();
-
- view_log_btn = memnew(Button);
- view_log_btn->set_text(TTR("View log"));
- view_log_btn->set_focus_mode(FOCUS_NONE);
- view_log_btn->set_visible(false);
- view_log_btn->connect("pressed", this, "_view_log_pressed");
- toolbar_hbc->add_child(view_log_btn);
-
- HSplitContainer *hsc = memnew(HSplitContainer);
- hsc->set_h_size_flags(SIZE_EXPAND_FILL);
- hsc->set_v_size_flags(SIZE_EXPAND_FILL);
- panel_builds_tab->add_child(hsc);
-
- build_tabs_list = memnew(ItemList);
- build_tabs_list->set_h_size_flags(SIZE_EXPAND_FILL);
- build_tabs_list->connect("item_selected", this, "_build_tabs_item_selected");
- build_tabs_list->connect("nothing_selected", this, "_build_tabs_nothing_selected");
- hsc->add_child(build_tabs_list);
-
- build_tabs = memnew(TabContainer);
- build_tabs->set_tab_align(TabContainer::ALIGN_LEFT);
- build_tabs->set_h_size_flags(SIZE_EXPAND_FILL);
- build_tabs->set_tabs_visible(false);
- hsc->add_child(build_tabs);
- }
-}
-
-MonoBottomPanel::~MonoBottomPanel() {
-
- singleton = NULL;
-}
-
-void MonoBuildTab::_load_issues_from_file(const String &p_csv_file) {
-
- FileAccessRef f = FileAccess::open(p_csv_file, FileAccess::READ);
-
- if (!f)
- return;
-
- while (!f->eof_reached()) {
- Vector<String> csv_line = f->get_csv_line();
-
- if (csv_line.size() == 1 && csv_line[0].empty())
- return;
-
- ERR_CONTINUE(csv_line.size() != 7);
-
- BuildIssue issue;
- issue.warning = csv_line[0] == "warning";
- issue.file = csv_line[1];
- issue.line = csv_line[2].to_int();
- issue.column = csv_line[3].to_int();
- issue.code = csv_line[4];
- issue.message = csv_line[5];
- issue.project_file = csv_line[6];
-
- if (issue.warning)
- warning_count += 1;
- else
- error_count += 1;
-
- issues.push_back(issue);
- }
-}
-
-void MonoBuildTab::_update_issues_list() {
-
- issues_list->clear();
-
- Ref<Texture> warning_icon = get_icon("Warning", "EditorIcons");
- Ref<Texture> error_icon = get_icon("Error", "EditorIcons");
-
- for (int i = 0; i < issues.size(); i++) {
-
- const BuildIssue &issue = issues[i];
-
- if (!(issue.warning ? warnings_visible : errors_visible))
- continue;
-
- String tooltip;
- tooltip += String("Message: ") + issue.message;
-
- if (issue.code.length()) {
- tooltip += String("\nCode: ") + issue.code;
- }
-
- tooltip += String("\nType: ") + (issue.warning ? "warning" : "error");
-
- String text;
-
- if (issue.file.length()) {
- String sline = String::num_int64(issue.line);
- String scolumn = String::num_int64(issue.column);
-
- text += issue.file + "(";
- text += sline + ",";
- text += scolumn + "): ";
-
- tooltip += "\nFile: " + issue.file;
- tooltip += "\nLine: " + sline;
- tooltip += "\nColumn: " + scolumn;
- }
-
- if (issue.project_file.length()) {
- tooltip += "\nProject: " + issue.project_file;
- }
-
- text += issue.message;
-
- int line_break_idx = text.find("\n");
- issues_list->add_item(line_break_idx == -1 ? text : text.substr(0, line_break_idx),
- issue.warning ? warning_icon : error_icon);
- int index = issues_list->get_item_count() - 1;
- issues_list->set_item_tooltip(index, tooltip);
- issues_list->set_item_metadata(index, i);
- }
-}
-
-Ref<Texture> MonoBuildTab::get_icon_texture() const {
-
- if (build_exited) {
- if (build_result == RESULT_ERROR) {
- return get_icon("StatusError", "EditorIcons");
- } else {
- return get_icon("StatusSuccess", "EditorIcons");
- }
- } else {
- return get_icon("Stop", "EditorIcons");
- }
-}
-
-MonoBuildInfo MonoBuildTab::get_build_info() {
-
- return build_info;
-}
-
-void MonoBuildTab::on_build_start() {
-
- build_exited = false;
-
- issues.clear();
- warning_count = 0;
- error_count = 0;
- _update_issues_list();
-
- MonoBottomPanel::get_singleton()->raise_build_tab(this);
-}
-
-void MonoBuildTab::on_build_exit(BuildResult result) {
-
- build_exited = true;
- build_result = result;
-
- _load_issues_from_file(logs_dir.plus_file(GodotSharpBuilds::get_msbuild_issues_filename()));
- _update_issues_list();
-
- MonoBottomPanel::get_singleton()->raise_build_tab(this);
-}
-
-void MonoBuildTab::on_build_exec_failed(const String &p_cause) {
-
- build_exited = true;
- build_result = RESULT_ERROR;
-
- issues_list->clear();
-
- BuildIssue issue;
- issue.message = p_cause;
- issue.warning = false;
-
- error_count += 1;
- issues.push_back(issue);
-
- _update_issues_list();
-
- MonoBottomPanel::get_singleton()->raise_build_tab(this);
-}
-
-void MonoBuildTab::restart_build() {
-
- ERR_FAIL_COND(!build_exited);
- GodotSharpBuilds::get_singleton()->restart_build(this);
-}
-
-void MonoBuildTab::stop_build() {
-
- ERR_FAIL_COND(build_exited);
- GodotSharpBuilds::get_singleton()->stop_build(this);
-}
-
-void MonoBuildTab::_issue_activated(int p_idx) {
-
- ERR_FAIL_INDEX(p_idx, issues_list->get_item_count());
-
- // Get correct issue idx from issue list
- int issue_idx = this->issues_list->get_item_metadata(p_idx);
-
- ERR_FAIL_INDEX(issue_idx, issues.size());
-
- const BuildIssue &issue = issues[issue_idx];
-
- if (issue.project_file.empty() && issue.file.empty())
- return;
-
- String project_dir = issue.project_file.length() ? issue.project_file.get_base_dir() : build_info.solution.get_base_dir();
-
- String file = project_dir.simplify_path().plus_file(issue.file.simplify_path());
-
- if (!FileAccess::exists(file))
- return;
-
- file = ProjectSettings::get_singleton()->localize_path(file);
-
- if (file.begins_with("res://")) {
- Ref<Script> script = ResourceLoader::load(file, CSharpLanguage::get_singleton()->get_type());
-
- if (script.is_valid() && ScriptEditor::get_singleton()->edit(script, issue.line, issue.column)) {
- EditorNode::get_singleton()->call("_editor_select", EditorNode::EDITOR_SCRIPT);
- }
- }
-}
-
-void MonoBuildTab::_bind_methods() {
-
- ClassDB::bind_method("_issue_activated", &MonoBuildTab::_issue_activated);
-}
-
-MonoBuildTab::MonoBuildTab(const MonoBuildInfo &p_build_info, const String &p_logs_dir) :
- build_exited(false),
- issues_list(memnew(ItemList)),
- error_count(0),
- warning_count(0),
- errors_visible(true),
- warnings_visible(true),
- logs_dir(p_logs_dir),
- build_info(p_build_info) {
- issues_list->set_v_size_flags(SIZE_EXPAND_FILL);
- issues_list->connect("item_activated", this, "_issue_activated");
- add_child(issues_list);
-}
diff --git a/modules/mono/editor/mono_bottom_panel.h b/modules/mono/editor/mono_bottom_panel.h
deleted file mode 100644
index 406e46f7ce..0000000000
--- a/modules/mono/editor/mono_bottom_panel.h
+++ /dev/null
@@ -1,150 +0,0 @@
-/*************************************************************************/
-/* mono_bottom_panel.h */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#ifndef MONO_BOTTOM_PANEL_H
-#define MONO_BOTTOM_PANEL_H
-
-#include "editor/editor_node.h"
-#include "scene/gui/control.h"
-
-#include "mono_build_info.h"
-
-class MonoBuildTab;
-
-class MonoBottomPanel : public VBoxContainer {
-
- GDCLASS(MonoBottomPanel, VBoxContainer)
-
- EditorNode *editor;
-
- TabContainer *panel_tabs;
-
- VBoxContainer *panel_builds_tab;
-
- ItemList *build_tabs_list;
- TabContainer *build_tabs;
-
- ToolButton *warnings_btn;
- ToolButton *errors_btn;
- Button *view_log_btn;
-
- void _update_build_tabs_list();
-
- void _build_tabs_item_selected(int p_idx);
- void _build_tabs_nothing_selected();
-
- void _warnings_toggled(bool p_pressed);
- void _errors_toggled(bool p_pressed);
-
- void _build_project_pressed();
- void _view_log_pressed();
-
- static MonoBottomPanel *singleton;
-
-protected:
- void _notification(int p_what);
-
- static void _bind_methods();
-
-public:
- _FORCE_INLINE_ static MonoBottomPanel *get_singleton() { return singleton; }
-
- void add_build_tab(MonoBuildTab *p_build_tab);
- void raise_build_tab(MonoBuildTab *p_build_tab);
-
- void show_build_tab();
-
- MonoBottomPanel(EditorNode *p_editor = NULL);
- ~MonoBottomPanel();
-};
-
-class MonoBuildTab : public VBoxContainer {
-
- GDCLASS(MonoBuildTab, VBoxContainer)
-
-public:
- enum BuildResult {
- RESULT_ERROR,
- RESULT_SUCCESS
- };
-
- struct BuildIssue {
- bool warning;
- String file;
- int line;
- int column;
- String code;
- String message;
- String project_file;
- };
-
-private:
- friend class MonoBottomPanel;
-
- bool build_exited;
- BuildResult build_result;
-
- Vector<BuildIssue> issues;
- ItemList *issues_list;
-
- int error_count;
- int warning_count;
-
- bool errors_visible;
- bool warnings_visible;
-
- String logs_dir;
-
- MonoBuildInfo build_info;
-
- void _load_issues_from_file(const String &p_csv_file);
- void _update_issues_list();
-
- void _issue_activated(int p_idx);
-
-protected:
- static void _bind_methods();
-
-public:
- Ref<Texture> get_icon_texture() const;
-
- MonoBuildInfo get_build_info();
-
- void on_build_start();
- void on_build_exit(BuildResult result);
- void on_build_exec_failed(const String &p_cause);
-
- void restart_build();
- void stop_build();
-
- MonoBuildTab(const MonoBuildInfo &p_build_info, const String &p_logs_dir);
-};
-
-#endif // MONO_BOTTOM_PANEL_H
diff --git a/modules/mono/glue/Managed/.gitignore b/modules/mono/glue/Managed/.gitignore
new file mode 100644
index 0000000000..146421cac8
--- /dev/null
+++ b/modules/mono/glue/Managed/.gitignore
@@ -0,0 +1,2 @@
+# Generated Godot API solution folder
+Generated
diff --git a/modules/mono/glue/Managed/Files/Attributes/RPCAttributes.cs b/modules/mono/glue/Managed/Files/Attributes/RPCAttributes.cs
index 2398e10135..1bf6d5199a 100644
--- a/modules/mono/glue/Managed/Files/Attributes/RPCAttributes.cs
+++ b/modules/mono/glue/Managed/Files/Attributes/RPCAttributes.cs
@@ -2,27 +2,27 @@ using System;
namespace Godot
{
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
public class RemoteAttribute : Attribute {}
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
public class SyncAttribute : Attribute {}
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
public class MasterAttribute : Attribute {}
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
public class PuppetAttribute : Attribute {}
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
public class SlaveAttribute : Attribute {}
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
public class RemoteSyncAttribute : Attribute {}
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
public class MasterSyncAttribute : Attribute {}
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)]
public class PuppetSyncAttribute : Attribute {}
}
diff --git a/modules/mono/glue/Managed/Files/Interfaces/ISerializationListener.cs b/modules/mono/glue/Managed/Files/Interfaces/ISerializationListener.cs
new file mode 100644
index 0000000000..c3fa2f3e82
--- /dev/null
+++ b/modules/mono/glue/Managed/Files/Interfaces/ISerializationListener.cs
@@ -0,0 +1,8 @@
+namespace Godot
+{
+ public interface ISerializationListener
+ {
+ void OnBeforeSerialize();
+ void OnAfterDeserialize();
+ }
+}
diff --git a/modules/mono/glue/Managed/Files/Mathf.cs b/modules/mono/glue/Managed/Files/Mathf.cs
index 8fb8730b88..2d8c63fe7f 100644
--- a/modules/mono/glue/Managed/Files/Mathf.cs
+++ b/modules/mono/glue/Managed/Files/Mathf.cs
@@ -210,6 +210,11 @@ namespace Godot
return a < b ? a : b;
}
+ public static real_t MoveToward(real_t from, real_t to, real_t delta)
+ {
+ return Abs(to - from) <= delta ? to : from + Sign(to - from) * delta;
+ }
+
public static int NearestPo2(int value)
{
value--;
diff --git a/modules/mono/glue/Managed/Files/StringExtensions.cs b/modules/mono/glue/Managed/Files/StringExtensions.cs
index c194facd0b..b43034fbb5 100644
--- a/modules/mono/glue/Managed/Files/StringExtensions.cs
+++ b/modules/mono/glue/Managed/Files/StringExtensions.cs
@@ -299,14 +299,14 @@ namespace Godot
if (basepos != -1)
{
var end = basepos + 3;
- rs = instance.Substring(end, instance.Length);
+ rs = instance.Substring(end);
@base = instance.Substring(0, end);
}
else
{
if (instance.BeginsWith("/"))
{
- rs = instance.Substring(1, instance.Length);
+ rs = instance.Substring(1);
@base = "/";
}
else
@@ -333,7 +333,7 @@ namespace Godot
if (sep == -1)
return instance;
- return instance.Substring(sep + 1, instance.Length);
+ return instance.Substring(sep + 1);
}
// <summary>
@@ -911,7 +911,8 @@ namespace Godot
// </summary>
public static string Substr(this string instance, int from, int len)
{
- return instance.Substring(from, len);
+ int max = instance.Length - from;
+ return instance.Substring(from, len > max ? max : len);
}
// <summary>
diff --git a/modules/mono/glue/Managed/Files/Vector2.cs b/modules/mono/glue/Managed/Files/Vector2.cs
index bb1950e1a8..a7f26283a7 100644
--- a/modules/mono/glue/Managed/Files/Vector2.cs
+++ b/modules/mono/glue/Managed/Files/Vector2.cs
@@ -186,6 +186,14 @@ namespace Godot
return res;
}
+ public Vector2 MoveToward(Vector2 to, real_t delta)
+ {
+ var v = this;
+ var vd = to - v;
+ var len = vd.Length();
+ return len <= delta || len < Mathf.Epsilon ? to : v + vd / len * delta;
+ }
+
public Vector2 Normalized()
{
var v = this;
diff --git a/modules/mono/glue/Managed/Files/Vector3.cs b/modules/mono/glue/Managed/Files/Vector3.cs
index 283cb6341a..16803ae55c 100644
--- a/modules/mono/glue/Managed/Files/Vector3.cs
+++ b/modules/mono/glue/Managed/Files/Vector3.cs
@@ -190,6 +190,14 @@ namespace Godot
);
}
+ public Vector3 MoveToward(Vector3 to, real_t delta)
+ {
+ var v = this;
+ var vd = to - v;
+ var len = vd.Length();
+ return len <= delta || len < Mathf.Epsilon ? to : v + vd / len * delta;
+ }
+
public Axis MaxAxis()
{
return x < y ? (y < z ? Axis.Z : Axis.Y) : (x < z ? Axis.Z : Axis.X);
diff --git a/modules/mono/glue/base_object_glue.cpp b/modules/mono/glue/base_object_glue.cpp
index 7385014a53..6d85f55b97 100644
--- a/modules/mono/glue/base_object_glue.cpp
+++ b/modules/mono/glue/base_object_glue.cpp
@@ -166,7 +166,7 @@ MonoArray *godot_icall_DynamicGodotObject_SetMemberList(Object *p_ptr) {
int i = 0;
for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
MonoString *boxed = GDMonoMarshal::mono_string_from_godot(E->get().name);
- mono_array_set(result, MonoString *, i, boxed);
+ mono_array_setref(result, i, boxed);
i++;
}
@@ -219,7 +219,18 @@ MonoBoolean godot_icall_DynamicGodotObject_SetMember(Object *p_ptr, MonoString *
}
MonoString *godot_icall_Object_ToString(Object *p_ptr) {
- return GDMonoMarshal::mono_string_from_godot(Variant(p_ptr).operator String());
+#ifdef DEBUG_ENABLED
+ // Cannot happen in C#; would get an ObjectDisposedException instead.
+ CRASH_COND(p_ptr == NULL);
+
+ if (ScriptDebugger::get_singleton() && !Object::cast_to<Reference>(p_ptr)) { // Only if debugging!
+ // Cannot happen either in C#; the handle is nullified when the object is destroyed
+ CRASH_COND(!ObjectDB::instance_validate(p_ptr));
+ }
+#endif
+
+ String result = "[" + p_ptr->get_class() + ":" + itos(p_ptr->get_instance_id()) + "]";
+ return GDMonoMarshal::mono_string_from_godot(result);
}
void godot_register_object_icalls() {
diff --git a/modules/mono/glue/collections_glue.cpp b/modules/mono/glue/collections_glue.cpp
index 47239f1260..e67c8b9ad9 100644
--- a/modules/mono/glue/collections_glue.cpp
+++ b/modules/mono/glue/collections_glue.cpp
@@ -46,7 +46,7 @@ void godot_icall_Array_Dtor(Array *ptr) {
}
MonoObject *godot_icall_Array_At(Array *ptr, int index) {
- if (index < 0 || index > ptr->size()) {
+ if (index < 0 || index >= ptr->size()) {
GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
return NULL;
}
@@ -54,7 +54,7 @@ MonoObject *godot_icall_Array_At(Array *ptr, int index) {
}
MonoObject *godot_icall_Array_At_Generic(Array *ptr, int index, uint32_t type_encoding, GDMonoClass *type_class) {
- if (index < 0 || index > ptr->size()) {
+ if (index < 0 || index >= ptr->size()) {
GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
return NULL;
}
@@ -62,7 +62,7 @@ MonoObject *godot_icall_Array_At_Generic(Array *ptr, int index, uint32_t type_en
}
void godot_icall_Array_SetAt(Array *ptr, int index, MonoObject *value) {
- if (index < 0 || index > ptr->size()) {
+ if (index < 0 || index >= ptr->size()) {
GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
return;
}
@@ -124,7 +124,7 @@ MonoBoolean godot_icall_Array_Remove(Array *ptr, MonoObject *item) {
}
void godot_icall_Array_RemoveAt(Array *ptr, int index) {
- if (index < 0 || index > ptr->size()) {
+ if (index < 0 || index >= ptr->size()) {
GDMonoUtils::set_pending_exception(mono_get_exception_index_out_of_range());
return;
}
diff --git a/modules/mono/glue/string_glue.cpp b/modules/mono/glue/string_glue.cpp
index a5c72160d7..e9373fb486 100644
--- a/modules/mono/glue/string_glue.cpp
+++ b/modules/mono/glue/string_glue.cpp
@@ -68,12 +68,12 @@ MonoString *godot_icall_String_sha256_text(MonoString *p_str) {
}
void godot_register_string_icalls() {
- mono_add_internal_call("Godot.String::godot_icall_String_md5_buffer", (void *)godot_icall_String_md5_buffer);
- mono_add_internal_call("Godot.String::godot_icall_String_md5_text", (void *)godot_icall_String_md5_text);
- mono_add_internal_call("Godot.String::godot_icall_String_rfind", (void *)godot_icall_String_rfind);
- mono_add_internal_call("Godot.String::godot_icall_String_rfindn", (void *)godot_icall_String_rfindn);
- mono_add_internal_call("Godot.String::godot_icall_String_sha256_buffer", (void *)godot_icall_String_sha256_buffer);
- mono_add_internal_call("Godot.String::godot_icall_String_sha256_text", (void *)godot_icall_String_sha256_text);
+ mono_add_internal_call("Godot.StringExtensions::godot_icall_String_md5_buffer", (void *)godot_icall_String_md5_buffer);
+ mono_add_internal_call("Godot.StringExtensions::godot_icall_String_md5_text", (void *)godot_icall_String_md5_text);
+ mono_add_internal_call("Godot.StringExtensions::godot_icall_String_rfind", (void *)godot_icall_String_rfind);
+ mono_add_internal_call("Godot.StringExtensions::godot_icall_String_rfindn", (void *)godot_icall_String_rfindn);
+ mono_add_internal_call("Godot.StringExtensions::godot_icall_String_sha256_buffer", (void *)godot_icall_String_sha256_buffer);
+ mono_add_internal_call("Godot.StringExtensions::godot_icall_String_sha256_text", (void *)godot_icall_String_sha256_text);
}
#endif // MONO_GLUE_ENABLED
diff --git a/modules/mono/godotsharp_defs.h b/modules/mono/godotsharp_defs.h
index 0d3b96d789..4ad4088514 100644
--- a/modules/mono/godotsharp_defs.h
+++ b/modules/mono/godotsharp_defs.h
@@ -39,7 +39,8 @@
#define API_SOLUTION_NAME "GodotSharp"
#define CORE_API_ASSEMBLY_NAME "GodotSharp"
#define EDITOR_API_ASSEMBLY_NAME "GodotSharpEditor"
-#define EDITOR_TOOLS_ASSEMBLY_NAME "GodotSharpTools"
+#define TOOLS_ASSEMBLY_NAME "GodotTools"
+#define TOOLS_PROJECT_EDITOR_ASSEMBLY_NAME "GodotTools.ProjectEditor"
#define BINDINGS_CLASS_NATIVECALLS "NativeCalls"
#define BINDINGS_CLASS_NATIVECALLS_EDITOR "EditorNativeCalls"
diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp
index 09a1fc6fbc..4b2525c692 100644
--- a/modules/mono/godotsharp_dirs.cpp
+++ b/modules/mono/godotsharp_dirs.cpp
@@ -39,6 +39,10 @@
#include "editor/editor_settings.h"
#endif
+#ifdef __ANDROID__
+#include "utils/android_utils.h"
+#endif
+
namespace GodotSharpDirs {
String _get_expected_build_config() {
@@ -55,6 +59,20 @@ String _get_expected_build_config() {
#endif
}
+String _get_expected_api_build_config() {
+#ifdef TOOLS_ENABLED
+ return "Debug";
+#else
+
+#ifdef DEBUG_ENABLED
+ return "Debug";
+#else
+ return "Release";
+#endif
+
+#endif
+}
+
String _get_mono_user_dir() {
#ifdef TOOLS_ENABLED
if (EditorSettings::get_singleton()) {
@@ -84,6 +102,7 @@ class _GodotSharpDirs {
public:
String res_data_dir;
String res_metadata_dir;
+ String res_assemblies_base_dir;
String res_assemblies_dir;
String res_config_dir;
String res_temp_dir;
@@ -114,7 +133,8 @@ private:
_GodotSharpDirs() {
res_data_dir = "res://.mono";
res_metadata_dir = res_data_dir.plus_file("metadata");
- res_assemblies_dir = res_data_dir.plus_file("assemblies");
+ res_assemblies_base_dir = res_data_dir.plus_file("assemblies");
+ res_assemblies_dir = res_assemblies_base_dir.plus_file(_get_expected_api_build_config());
res_config_dir = res_data_dir.plus_file("etc").plus_file("mono");
// TODO use paths from csproj
@@ -129,15 +149,16 @@ private:
mono_solutions_dir = mono_user_dir.plus_file("solutions");
build_logs_dir = mono_user_dir.plus_file("build_logs");
- String name = ProjectSettings::get_singleton()->get("application/config/name");
- if (name.empty()) {
- name = "UnnamedProject";
+ String appname = ProjectSettings::get_singleton()->get("application/config/name");
+ String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
+ if (appname_safe.empty()) {
+ appname_safe = "UnnamedProject";
}
String base_path = ProjectSettings::get_singleton()->globalize_path("res://");
- sln_filepath = base_path.plus_file(name + ".sln");
- csproj_filepath = base_path.plus_file(name + ".csproj");
+ sln_filepath = base_path.plus_file(appname_safe + ".sln");
+ csproj_filepath = base_path.plus_file(appname_safe + ".csproj");
#endif
String exe_dir = OS::get_singleton()->get_executable_path().get_base_dir();
@@ -150,7 +171,12 @@ private:
String data_mono_root_dir = data_dir_root.plus_file("Mono");
data_mono_etc_dir = data_mono_root_dir.plus_file("etc");
+
+#if __ANDROID__
+ data_mono_lib_dir = GDMonoUtils::Android::get_app_native_lib_dir();
+#else
data_mono_lib_dir = data_mono_root_dir.plus_file("lib");
+#endif
#ifdef WINDOWS_ENABLED
data_mono_bin_dir = data_mono_root_dir.plus_file("bin");
@@ -173,15 +199,21 @@ private:
#else
- String appname = OS::get_singleton()->get_safe_dir_name(ProjectSettings::get_singleton()->get("application/config/name"));
- String data_dir_root = exe_dir.plus_file("data_" + appname);
+ String appname = ProjectSettings::get_singleton()->get("application/config/name");
+ String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
+ String data_dir_root = exe_dir.plus_file("data_" + appname_safe);
if (!DirAccess::exists(data_dir_root)) {
data_dir_root = exe_dir.plus_file("data_Godot");
}
String data_mono_root_dir = data_dir_root.plus_file("Mono");
data_mono_etc_dir = data_mono_root_dir.plus_file("etc");
+
+#if __ANDROID__
+ data_mono_lib_dir = GDMonoUtils::Android::get_app_native_lib_dir();
+#else
data_mono_lib_dir = data_mono_root_dir.plus_file("lib");
+#endif
#ifdef WINDOWS_ENABLED
data_mono_bin_dir = data_mono_root_dir.plus_file("bin");
@@ -215,6 +247,10 @@ String get_res_metadata_dir() {
return _GodotSharpDirs::get_singleton().res_metadata_dir;
}
+String get_res_assemblies_base_dir() {
+ return _GodotSharpDirs::get_singleton().res_assemblies_base_dir;
+}
+
String get_res_assemblies_dir() {
return _GodotSharpDirs::get_singleton().res_assemblies_dir;
}
diff --git a/modules/mono/godotsharp_dirs.h b/modules/mono/godotsharp_dirs.h
index 556df959e2..ff51888d1c 100644
--- a/modules/mono/godotsharp_dirs.h
+++ b/modules/mono/godotsharp_dirs.h
@@ -37,6 +37,7 @@ namespace GodotSharpDirs {
String get_res_data_dir();
String get_res_metadata_dir();
+String get_res_assemblies_base_dir();
String get_res_assemblies_dir();
String get_res_config_dir();
String get_res_temp_dir();
diff --git a/modules/mono/mono_gc_handle.h b/modules/mono/mono_gc_handle.h
index 63b61aff18..60a1eed212 100644
--- a/modules/mono/mono_gc_handle.h
+++ b/modules/mono/mono_gc_handle.h
@@ -37,7 +37,7 @@
class MonoGCHandle : public Reference {
- GDCLASS(MonoGCHandle, Reference)
+ GDCLASS(MonoGCHandle, Reference);
bool released;
bool weak;
diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp
index 19e49d29f9..096ad0f5e3 100644
--- a/modules/mono/mono_gd/gd_mono.cpp
+++ b/modules/mono/mono_gd/gd_mono.cpp
@@ -52,13 +52,12 @@
#include "gd_mono_utils.h"
#ifdef TOOLS_ENABLED
-#include "../editor/godotsharp_editor.h"
#include "main/main.h"
#endif
-#define OUT_OF_SYNC_ERR_MESSAGE(m_assembly_name) "The assembly '" m_assembly_name "' is out of sync. " \
- "This error is expected if you just upgraded to a newer Godot version. " \
- "Building the project will update the assembly to the correct version."
+#ifdef ANDROID_ENABLED
+#include "android_mono_config.gen.h"
+#endif
GDMono *GDMono::singleton = NULL;
@@ -95,7 +94,7 @@ void gdmono_profiler_init() {
#ifdef DEBUG_ENABLED
-static bool _wait_for_debugger_msecs(uint32_t p_msecs) {
+bool _wait_for_debugger_msecs(uint32_t p_msecs) {
do {
if (mono_is_debugger_attached())
@@ -125,16 +124,17 @@ void gdmono_debug_init() {
bool da_suspend = GLOBAL_DEF("mono/debugger_agent/wait_for_debugger", false);
int da_timeout = GLOBAL_DEF("mono/debugger_agent/wait_timeout", 3000);
+ CharString da_args = OS::get_singleton()->get_environment("GODOT_MONO_DEBUGGER_AGENT").utf8();
+
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint() ||
ProjectSettings::get_singleton()->get_resource_path().empty() ||
Main::is_project_manager()) {
- return;
+ if (da_args.size() == 0)
+ return;
}
#endif
- CharString da_args = OS::get_singleton()->get_environment("GODOT_MONO_DEBUGGER_AGENT").utf8();
-
if (da_args.length() == 0) {
da_args = String("--debugger-agent=transport=dt_socket,address=127.0.0.1:" + itos(da_port) +
",embedding=1,server=y,suspend=" + (da_suspend ? "y,timeout=" + itos(da_timeout) : "n"))
@@ -203,6 +203,10 @@ void GDMono::initialize() {
print_verbose("Mono: Initializing module...");
+ char *runtime_build_info = mono_get_runtime_build_info();
+ print_verbose("Mono JIT compiler version " + String(runtime_build_info));
+ mono_free(runtime_build_info);
+
#ifdef DEBUG_METHODS_ENABLED
_initialize_and_check_api_hashes();
#endif
@@ -233,9 +237,9 @@ void GDMono::initialize() {
locations.push_back("/usr/local/var/homebrew/linked/mono/");
for (int i = 0; i < locations.size(); i++) {
- String hint_assembly_rootdir = path_join(locations[i], "lib");
- String hint_mscorlib_path = path_join(hint_assembly_rootdir, "mono", "4.5", "mscorlib.dll");
- String hint_config_dir = path_join(locations[i], "etc");
+ String hint_assembly_rootdir = path::join(locations[i], "lib");
+ String hint_mscorlib_path = path::join(hint_assembly_rootdir, "mono", "4.5", "mscorlib.dll");
+ String hint_config_dir = path::join(locations[i], "etc");
if (FileAccess::exists(hint_mscorlib_path) && DirAccess::exists(hint_config_dir)) {
assembly_rootdir = hint_assembly_rootdir;
@@ -251,17 +255,19 @@ void GDMono::initialize() {
String bundled_config_dir = GodotSharpDirs::get_data_mono_etc_dir();
#ifdef TOOLS_ENABLED
- if (DirAccess::exists(bundled_assembly_rootdir) && DirAccess::exists(bundled_config_dir)) {
+ if (DirAccess::exists(bundled_assembly_rootdir)) {
assembly_rootdir = bundled_assembly_rootdir;
+ }
+
+ if (DirAccess::exists(bundled_config_dir)) {
config_dir = bundled_config_dir;
}
#ifdef WINDOWS_ENABLED
if (assembly_rootdir.empty() || config_dir.empty()) {
+ ERR_PRINT("Cannot find Mono in the registry");
// Assertion: if they are not set, then they weren't found in the registry
CRASH_COND(mono_reg_info.assembly_dir.length() > 0 || mono_reg_info.config_dir.length() > 0);
-
- ERR_PRINT("Cannot find Mono in the registry");
}
#endif // WINDOWS_ENABLED
@@ -285,31 +291,18 @@ void GDMono::initialize() {
gdmono_debug_init();
#endif
+#ifdef ANDROID_ENABLED
+ mono_config_parse_memory(get_godot_android_mono_config().utf8().get_data());
+#else
mono_config_parse(NULL);
+#endif
mono_install_unhandled_exception_hook(&unhandled_exception_hook, NULL);
#ifndef TOOLS_ENABLED
- if (!DirAccess::exists("res://.mono")) {
- // 'res://.mono/' is missing so there is nothing to load. We don't need to initialize mono, but
- // we still do so unless mscorlib is missing (which is the case for projects that don't use C#).
-
- String mscorlib_fname("mscorlib.dll");
-
- Vector<String> search_dirs;
- GDMonoAssembly::fill_search_dirs(search_dirs);
-
- bool found = false;
- for (int i = 0; i < search_dirs.size(); i++) {
- if (FileAccess::exists(search_dirs[i].plus_file(mscorlib_fname))) {
- found = true;
- break;
- }
- }
-
- if (!found)
- return; // mscorlib is missing, do not initialize mono
- }
+ // Export templates only load the Mono runtime if the project uses it
+ if (!DirAccess::exists("res://.mono"))
+ return;
#endif
root_domain = mono_jit_init_version("GodotEngine.RootDomain", "v4.0.30319");
@@ -329,18 +322,6 @@ void GDMono::initialize() {
ERR_EXPLAIN("Mono: Failed to load mscorlib assembly");
ERR_FAIL_COND(!_load_corlib_assembly());
-#ifdef TOOLS_ENABLED
- // The tools domain must be loaded here, before the scripts domain.
- // Otherwise domain unload on the scripts domain will hang indefinitely.
-
- ERR_EXPLAIN("Mono: Failed to load tools domain");
- ERR_FAIL_COND(_load_tools_domain() != OK);
-
- // TODO move to editor init callback, and do it lazily when required before editor init (e.g.: bindings generation)
- ERR_EXPLAIN("Mono: Failed to load Editor Tools assembly");
- ERR_FAIL_COND(!_load_editor_tools_assembly());
-#endif
-
ERR_EXPLAIN("Mono: Failed to load scripts domain");
ERR_FAIL_COND(_load_scripts_domain() != OK);
@@ -352,56 +333,48 @@ void GDMono::initialize() {
_register_internal_calls();
- // The following assemblies are not required at initialization
-#ifdef MONO_GLUE_ENABLED
- if (_load_api_assemblies()) {
- // Everything is fine with the api assemblies, load the project assembly
- _load_project_assembly();
- } else {
- if ((core_api_assembly && (core_api_assembly_out_of_sync || !GDMonoUtils::mono_cache.godot_api_cache_updated))
-#ifdef TOOLS_ENABLED
- || (editor_api_assembly && editor_api_assembly_out_of_sync)
+ print_verbose("Mono: INITIALIZED");
+}
+
+void GDMono::initialize_load_assemblies() {
+
+#ifndef MONO_GLUE_ENABLED
+ ERR_EXPLAIN("Mono: This binary was built with `mono_glue=no`; cannot load assemblies");
+ CRASH_NOW();
#endif
- ) {
-#ifdef TOOLS_ENABLED
- // The assembly was successfully loaded, but the full api could not be cached.
- // This is most likely an outdated assembly loaded because of an invalid version in the
- // metadata, so we invalidate the version in the metadata and unload the script domain.
-
- if (core_api_assembly_out_of_sync) {
- ERR_PRINT(OUT_OF_SYNC_ERR_MESSAGE(CORE_API_ASSEMBLY_NAME));
- metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true);
- } else if (!GDMonoUtils::mono_cache.godot_api_cache_updated) {
- ERR_PRINT("The loaded assembly '" CORE_API_ASSEMBLY_NAME "' is in sync, but the cache update failed");
- metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true);
- }
- if (editor_api_assembly_out_of_sync) {
- ERR_PRINT(OUT_OF_SYNC_ERR_MESSAGE(EDITOR_API_ASSEMBLY_NAME));
- metadata_set_api_assembly_invalidated(APIAssembly::API_EDITOR, true);
- }
+ // Load assemblies. The API and tools assemblies are required,
+ // the application is aborted if these assemblies cannot be loaded.
- print_line("Mono: Proceeding to unload scripts domain because of invalid API assemblies.");
+ _load_api_assemblies();
- Error err = _unload_scripts_domain();
- if (err != OK) {
- WARN_PRINT("Mono: Failed to unload scripts domain");
- }
-#else
- ERR_PRINT("The loaded API assembly is invalid");
- CRASH_NOW();
-#endif // TOOLS_ENABLED
- }
+#if defined(TOOLS_ENABLED)
+ if (!_load_tools_assemblies()) {
+ ERR_EXPLAIN("Mono: Failed to load GodotTools assemblies");
+ CRASH_NOW();
}
-#else
- print_verbose("Mono: Glue disabled, ignoring script assemblies.");
-#endif // MONO_GLUE_ENABLED
+#endif
- print_verbose("Mono: INITIALIZED");
+ // Load the project's main assembly. This doesn't necessarily need to succeed.
+ // The game may not be using .NET at all, or if the project does use .NET and
+ // we're running in the editor, it may just happen to be it wasn't built yet.
+ if (!_load_project_assembly()) {
+ if (OS::get_singleton()->is_stdout_verbose())
+ print_error("Mono: Failed to load project assembly");
+ }
+}
+
+bool GDMono::_are_api_assemblies_out_of_sync() {
+ bool out_of_sync = core_api_assembly && (core_api_assembly_out_of_sync || !GDMonoUtils::mono_cache.godot_api_cache_updated);
+#ifdef TOOLS_ENABLED
+ if (!out_of_sync)
+ out_of_sync = editor_api_assembly && editor_api_assembly_out_of_sync;
+#endif
+ return out_of_sync;
}
-#ifdef MONO_GLUE_ENABLED
namespace GodotSharpBindings {
+#ifdef MONO_GLUE_ENABLED
uint64_t get_core_api_hash();
#ifdef TOOLS_ENABLED
@@ -410,17 +383,33 @@ uint64_t get_editor_api_hash();
uint32_t get_bindings_version();
void register_generated_icalls();
-} // namespace GodotSharpBindings
-#endif
-void GDMono::_register_internal_calls() {
-#ifdef MONO_GLUE_ENABLED
- GodotSharpBindings::register_generated_icalls();
-#endif
+#else
+uint64_t get_core_api_hash() {
+ CRASH_NOW();
+ GD_UNREACHABLE();
+}
#ifdef TOOLS_ENABLED
- GodotSharpEditor::register_internal_calls();
+uint64_t get_editor_api_hash() {
+ CRASH_NOW();
+ GD_UNREACHABLE();
+}
#endif
+uint32_t get_bindings_version() {
+ CRASH_NOW();
+ GD_UNREACHABLE();
+}
+
+void register_generated_icalls() {
+ /* Fine, just do nothing */
+}
+
+#endif // MONO_GLUE_ENABLED
+} // namespace GodotSharpBindings
+
+void GDMono::_register_internal_calls() {
+ GodotSharpBindings::register_generated_icalls();
}
void GDMono::_initialize_and_check_api_hashes() {
@@ -559,29 +548,109 @@ bool GDMono::_load_corlib_assembly() {
return success;
}
-bool GDMono::_load_core_api_assembly() {
+#ifdef TOOLS_ENABLED
+bool GDMono::copy_prebuilt_api_assembly(APIAssembly::Type p_api_type) {
- if (core_api_assembly)
- return true;
+ bool &api_assembly_out_of_sync = (p_api_type == APIAssembly::API_CORE) ?
+ GDMono::get_singleton()->core_api_assembly_out_of_sync :
+ GDMono::get_singleton()->editor_api_assembly_out_of_sync;
-#ifdef TOOLS_ENABLED
- if (metadata_is_api_assembly_invalidated(APIAssembly::API_CORE)) {
- print_verbose("Mono: Skipping loading of Core API assembly because it was invalidated");
- return false;
+ String src_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file("Debug");
+ String dst_dir = GodotSharpDirs::get_res_assemblies_dir();
+
+ String assembly_name = p_api_type == APIAssembly::API_CORE ? CORE_API_ASSEMBLY_NAME : EDITOR_API_ASSEMBLY_NAME;
+
+ // Create destination directory if needed
+ if (!DirAccess::exists(dst_dir)) {
+ DirAccess *da = DirAccess::create_for_path(dst_dir);
+ Error err = da->make_dir_recursive(dst_dir);
+ memdelete(da);
+
+ if (err != OK) {
+ ERR_PRINTS("Failed to create destination directory for the API assemblies. Error: " + itos(err));
+ return false;
+ }
}
+
+ String assembly_file = assembly_name + ".dll";
+ String assembly_src = src_dir.plus_file(assembly_file);
+ String assembly_dst = dst_dir.plus_file(assembly_file);
+
+ if (!FileAccess::exists(assembly_dst) || api_assembly_out_of_sync) {
+ DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
+
+ String xml_file = assembly_name + ".xml";
+ if (da->copy(src_dir.plus_file(xml_file), dst_dir.plus_file(xml_file)) != OK)
+ WARN_PRINTS("Failed to copy " + xml_file);
+
+ String pdb_file = assembly_name + ".pdb";
+ if (da->copy(src_dir.plus_file(pdb_file), dst_dir.plus_file(pdb_file)) != OK)
+ WARN_PRINTS("Failed to copy " + pdb_file);
+
+ Error err = da->copy(assembly_src, assembly_dst);
+
+ if (err != OK) {
+ ERR_PRINTS("Failed to copy " + assembly_file);
+ return false;
+ }
+
+ api_assembly_out_of_sync = false;
+ }
+
+ return true;
+}
+
+String GDMono::update_api_assemblies_from_prebuilt() {
+
+#define FAIL_REASON(m_out_of_sync, m_prebuilt_exist) \
+ ( \
+ (m_out_of_sync ? \
+ String("The assembly is invalidated") : \
+ String("The assembly was not found")) + \
+ (m_prebuilt_exist ? \
+ String(" and the prebuilt assemblies are missing") : \
+ String(" and we failed to copy the prebuilt assemblies")))
+
+ bool api_assembly_out_of_sync = core_api_assembly_out_of_sync || editor_api_assembly_out_of_sync;
+
+ String core_assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(CORE_API_ASSEMBLY_NAME ".dll");
+ String editor_assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
+
+ if (!api_assembly_out_of_sync && FileAccess::exists(core_assembly_path) && FileAccess::exists(editor_assembly_path))
+ return String(); // No update needed
+
+ String prebuilt_api_dir = GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file("Debug");
+ String prebuilt_core_dll_path = prebuilt_api_dir.plus_file(CORE_API_ASSEMBLY_NAME ".dll");
+ String prebuilt_editor_dll_path = prebuilt_api_dir.plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
+
+ if (!FileAccess::exists(prebuilt_core_dll_path) || !FileAccess::exists(prebuilt_editor_dll_path))
+ return FAIL_REASON(api_assembly_out_of_sync, /* prebuilt_exist: */ false);
+
+ // Copy the prebuilt Api
+ if (!copy_prebuilt_api_assembly(APIAssembly::API_CORE) || !copy_prebuilt_api_assembly(APIAssembly::API_EDITOR))
+ return FAIL_REASON(api_assembly_out_of_sync, /* prebuilt_exist: */ true);
+
+ return String(); // Updated successfully
+
+#undef FAIL_REASON
+}
#endif
- String assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(CORE_API_ASSEMBLY_NAME ".dll");
+bool GDMono::_load_core_api_assembly() {
- if (!FileAccess::exists(assembly_path))
- return false;
+ if (core_api_assembly)
+ return true;
- bool success = load_assembly_from(CORE_API_ASSEMBLY_NAME,
- assembly_path,
- &core_api_assembly);
+#ifdef TOOLS_ENABLED
+ // For the editor and the editor player we want to load it from a specific path to make sure we can keep it up to date
+ String assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(CORE_API_ASSEMBLY_NAME ".dll");
+ bool success = FileAccess::exists(assembly_path) &&
+ load_assembly_from(CORE_API_ASSEMBLY_NAME, assembly_path, &core_api_assembly);
+#else
+ bool success = load_assembly(CORE_API_ASSEMBLY_NAME, &core_api_assembly);
+#endif
if (success) {
-#ifdef MONO_GLUE_ENABLED
APIAssembly::Version api_assembly_ver = APIAssembly::Version::get_from_loaded_assembly(core_api_assembly, APIAssembly::API_CORE);
core_api_assembly_out_of_sync = GodotSharpBindings::get_core_api_hash() != api_assembly_ver.godot_api_hash ||
GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version ||
@@ -591,9 +660,8 @@ bool GDMono::_load_core_api_assembly() {
_install_trace_listener();
}
-#else
- GDMonoUtils::update_godot_api_cache();
-#endif
+ } else {
+ core_api_assembly_out_of_sync = false;
}
return success;
@@ -605,68 +673,25 @@ bool GDMono::_load_editor_api_assembly() {
if (editor_api_assembly)
return true;
- if (metadata_is_api_assembly_invalidated(APIAssembly::API_EDITOR)) {
- print_verbose("Mono: Skipping loading of Editor API assembly because it was invalidated");
- return false;
- }
-
+ // For the editor and the editor player we want to load it from a specific path to make sure we can keep it up to date
String assembly_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(EDITOR_API_ASSEMBLY_NAME ".dll");
-
- if (!FileAccess::exists(assembly_path))
- return false;
-
- bool success = load_assembly_from(EDITOR_API_ASSEMBLY_NAME,
- assembly_path,
- &editor_api_assembly);
+ bool success = FileAccess::exists(assembly_path) &&
+ load_assembly_from(EDITOR_API_ASSEMBLY_NAME, assembly_path, &editor_api_assembly);
if (success) {
-#ifdef MONO_GLUE_ENABLED
APIAssembly::Version api_assembly_ver = APIAssembly::Version::get_from_loaded_assembly(editor_api_assembly, APIAssembly::API_EDITOR);
editor_api_assembly_out_of_sync = GodotSharpBindings::get_editor_api_hash() != api_assembly_ver.godot_api_hash ||
GodotSharpBindings::get_bindings_version() != api_assembly_ver.bindings_version ||
CS_GLUE_VERSION != api_assembly_ver.cs_glue_version;
-#endif
- }
-
- return success;
-}
-#endif
-
-#ifdef TOOLS_ENABLED
-bool GDMono::_load_editor_tools_assembly() {
-
- if (editor_tools_assembly)
- return true;
-
- _GDMONO_SCOPE_DOMAIN_(tools_domain)
-
- return load_assembly(EDITOR_TOOLS_ASSEMBLY_NAME, &editor_tools_assembly);
-}
-#endif
-
-bool GDMono::_load_project_assembly() {
-
- if (project_assembly)
- return true;
-
- String name = ProjectSettings::get_singleton()->get("application/config/name");
- if (name.empty()) {
- name = "UnnamedProject";
- }
-
- bool success = load_assembly(name, &project_assembly);
-
- if (success) {
- mono_assembly_set_main(project_assembly->get_assembly());
} else {
- if (OS::get_singleton()->is_stdout_verbose())
- print_error("Mono: Failed to load project assembly");
+ editor_api_assembly_out_of_sync = false;
}
return success;
}
+#endif
-bool GDMono::_load_api_assemblies() {
+bool GDMono::_try_load_api_assemblies() {
if (!_load_core_api_assembly()) {
if (OS::get_singleton()->is_stdout_verbose())
@@ -691,86 +716,106 @@ bool GDMono::_load_api_assemblies() {
return true;
}
-void GDMono::_install_trace_listener() {
-
-#ifdef DEBUG_ENABLED
- // Install the trace listener now before the project assembly is loaded
- typedef void (*DebuggingUtils_InstallTraceListener)(MonoObject **);
- MonoException *exc = NULL;
- GDMonoClass *debug_utils = core_api_assembly->get_class(BINDINGS_NAMESPACE, "DebuggingUtils");
- DebuggingUtils_InstallTraceListener install_func =
- (DebuggingUtils_InstallTraceListener)debug_utils->get_method_thunk("InstallTraceListener");
- install_func((MonoObject **)&exc);
- if (exc) {
- ERR_PRINT("Failed to install System.Diagnostics.Trace listener");
- GDMonoUtils::debug_print_unhandled_exception(exc);
- }
-#endif
-}
+void GDMono::_load_api_assemblies() {
-#ifdef TOOLS_ENABLED
-String GDMono::_get_api_assembly_metadata_path() {
+ if (!_try_load_api_assemblies()) {
+ // The API assemblies are out of sync. Fine, try one more time, but this time
+ // update them from the prebuilt assemblies directory before trying to load them.
- return GodotSharpDirs::get_res_metadata_dir().plus_file("api_assemblies.cfg");
-}
+ // 1. Unload the scripts domain
+ if (_unload_scripts_domain() != OK) {
+ ERR_EXPLAIN("Mono: Failed to unload scripts domain");
+ CRASH_NOW();
+ }
-void GDMono::metadata_set_api_assembly_invalidated(APIAssembly::Type p_api_type, bool p_invalidated) {
+ // 2. Update the API assemblies
+ String update_error = update_api_assemblies_from_prebuilt();
+ if (!update_error.empty()) {
+ ERR_EXPLAIN(update_error);
+ CRASH_NOW();
+ }
- String section = APIAssembly::to_string(p_api_type);
- String path = _get_api_assembly_metadata_path();
+ // 3. Load the scripts domain again
+ if (_load_scripts_domain() != OK) {
+ ERR_EXPLAIN("Mono: Failed to load scripts domain");
+ CRASH_NOW();
+ }
- Ref<ConfigFile> metadata;
- metadata.instance();
- metadata->load(path);
+ // 4. Try loading the updated assemblies
+ if (!_try_load_api_assemblies()) {
+ // welp... too bad
- metadata->set_value(section, "invalidated", p_invalidated);
+ if (_are_api_assemblies_out_of_sync()) {
+ if (core_api_assembly_out_of_sync) {
+ ERR_PRINT("The assembly '" CORE_API_ASSEMBLY_NAME "' is out of sync");
+ } else if (!GDMonoUtils::mono_cache.godot_api_cache_updated) {
+ ERR_PRINT("The loaded assembly '" CORE_API_ASSEMBLY_NAME "' is in sync, but the cache update failed");
+ }
- String assembly_path = GodotSharpDirs::get_res_assemblies_dir()
- .plus_file(p_api_type == APIAssembly::API_CORE ?
- CORE_API_ASSEMBLY_NAME ".dll" :
- EDITOR_API_ASSEMBLY_NAME ".dll");
+#ifdef TOOLS_ENABLED
+ if (editor_api_assembly_out_of_sync) {
+ ERR_PRINT("The assembly '" EDITOR_API_ASSEMBLY_NAME "' is out of sync");
+ }
+#endif
- ERR_FAIL_COND(!FileAccess::exists(assembly_path));
+ CRASH_NOW();
+ } else {
+ ERR_EXPLAIN("Failed to load one of the API assemblies");
+ CRASH_NOW();
+ }
+ }
+ }
+}
- uint64_t modified_time = FileAccess::get_modified_time(assembly_path);
+#ifdef TOOLS_ENABLED
+bool GDMono::_load_tools_assemblies() {
- metadata->set_value(section, "invalidated_asm_modified_time", String::num_uint64(modified_time));
+ if (tools_assembly && tools_project_editor_assembly)
+ return true;
- String dir = path.get_base_dir();
- if (!DirAccess::exists(dir)) {
- DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
- ERR_FAIL_COND(!da);
- Error err = da->make_dir_recursive(ProjectSettings::get_singleton()->globalize_path(dir));
- ERR_FAIL_COND(err != OK);
- }
+ bool success = load_assembly(TOOLS_ASSEMBLY_NAME, &tools_assembly) &&
+ load_assembly(TOOLS_PROJECT_EDITOR_ASSEMBLY_NAME, &tools_project_editor_assembly);
- Error save_err = metadata->save(path);
- ERR_FAIL_COND(save_err != OK);
+ return success;
}
+#endif
-bool GDMono::metadata_is_api_assembly_invalidated(APIAssembly::Type p_api_type) {
+bool GDMono::_load_project_assembly() {
- String section = APIAssembly::to_string(p_api_type);
+ if (project_assembly)
+ return true;
- Ref<ConfigFile> metadata;
- metadata.instance();
- metadata->load(_get_api_assembly_metadata_path());
+ String appname = ProjectSettings::get_singleton()->get("application/config/name");
+ String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
+ if (appname_safe.empty()) {
+ appname_safe = "UnnamedProject";
+ }
- String assembly_path = GodotSharpDirs::get_res_assemblies_dir()
- .plus_file(p_api_type == APIAssembly::API_CORE ?
- CORE_API_ASSEMBLY_NAME ".dll" :
- EDITOR_API_ASSEMBLY_NAME ".dll");
+ bool success = load_assembly(appname_safe, &project_assembly);
- if (!FileAccess::exists(assembly_path))
- return false;
+ if (success) {
+ mono_assembly_set_main(project_assembly->get_assembly());
+ }
- uint64_t modified_time = FileAccess::get_modified_time(assembly_path);
+ return success;
+}
- uint64_t stored_modified_time = metadata->get_value(section, "invalidated_asm_modified_time", 0);
+void GDMono::_install_trace_listener() {
- return metadata->get_value(section, "invalidated", false) && modified_time <= stored_modified_time;
-}
+#ifdef DEBUG_ENABLED
+ // Install the trace listener now before the project assembly is loaded
+ typedef void (*DebuggingUtils_InstallTraceListener)(MonoObject **);
+ MonoException *exc = NULL;
+ GDMonoClass *debug_utils = core_api_assembly->get_class(BINDINGS_NAMESPACE, "DebuggingUtils");
+ DebuggingUtils_InstallTraceListener install_func =
+ (DebuggingUtils_InstallTraceListener)debug_utils->get_method_thunk("InstallTraceListener");
+ install_func((MonoObject **)&exc);
+ if (exc) {
+ ERR_PRINT("Failed to install System.Diagnostics.Trace listener");
+ GDMonoUtils::debug_print_unhandled_exception(exc);
+ }
#endif
+}
Error GDMono::_load_scripts_domain() {
@@ -807,17 +852,16 @@ Error GDMono::_unload_scripts_domain() {
mono_gc_collect(mono_gc_max_generation());
+ GDMonoUtils::clear_godot_api_cache();
+
_domain_assemblies_cleanup(mono_domain_get_id(scripts_domain));
core_api_assembly = NULL;
project_assembly = NULL;
#ifdef TOOLS_ENABLED
editor_api_assembly = NULL;
-#endif
-
- core_api_assembly_out_of_sync = false;
-#ifdef TOOLS_ENABLED
- editor_api_assembly_out_of_sync = false;
+ tools_assembly = NULL;
+ tools_project_editor_assembly = NULL;
#endif
MonoDomain *domain = scripts_domain;
@@ -835,22 +879,6 @@ Error GDMono::_unload_scripts_domain() {
return OK;
}
-#ifdef TOOLS_ENABLED
-Error GDMono::_load_tools_domain() {
-
- ERR_FAIL_COND_V(tools_domain != NULL, ERR_BUG);
-
- print_verbose("Mono: Loading tools domain...");
-
- tools_domain = GDMonoUtils::create_domain("GodotEngine.ToolsDomain");
-
- ERR_EXPLAIN("Mono: Could not create tools app domain");
- ERR_FAIL_NULL_V(tools_domain, ERR_CANT_CREATE);
-
- return OK;
-}
-#endif
-
#ifdef GD_MONO_HOT_RELOAD
Error GDMono::reload_scripts_domain() {
@@ -872,52 +900,25 @@ Error GDMono::reload_scripts_domain() {
return err;
}
-#ifdef MONO_GLUE_ENABLED
- if (!_load_api_assemblies()) {
- if ((core_api_assembly && (core_api_assembly_out_of_sync || !GDMonoUtils::mono_cache.godot_api_cache_updated))
-#ifdef TOOLS_ENABLED
- || (editor_api_assembly && editor_api_assembly_out_of_sync)
-#endif
- ) {
-#ifdef TOOLS_ENABLED
- // The assembly was successfully loaded, but the full api could not be cached.
- // This is most likely an outdated assembly loaded because of an invalid version in the
- // metadata, so we invalidate the version in the metadata and unload the script domain.
-
- if (core_api_assembly_out_of_sync) {
- ERR_PRINT(OUT_OF_SYNC_ERR_MESSAGE(CORE_API_ASSEMBLY_NAME));
- metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true);
- } else if (!GDMonoUtils::mono_cache.godot_api_cache_updated) {
- ERR_PRINT("The loaded Core API assembly is in sync, but the cache update failed");
- metadata_set_api_assembly_invalidated(APIAssembly::API_CORE, true);
- }
-
- if (editor_api_assembly_out_of_sync) {
- ERR_PRINT(OUT_OF_SYNC_ERR_MESSAGE(EDITOR_API_ASSEMBLY_NAME));
- metadata_set_api_assembly_invalidated(APIAssembly::API_EDITOR, true);
- }
+ // Load assemblies. The API and tools assemblies are required,
+ // the application is aborted if these assemblies cannot be loaded.
- err = _unload_scripts_domain();
- if (err != OK) {
- WARN_PRINT("Mono: Failed to unload scripts domain");
- }
+ _load_api_assemblies();
- return ERR_CANT_RESOLVE;
-#else
- ERR_PRINT("The loaded API assembly is invalid");
- CRASH_NOW();
-#endif
- } else {
- return ERR_CANT_OPEN;
- }
+#if defined(TOOLS_ENABLED)
+ if (!_load_tools_assemblies()) {
+ ERR_EXPLAIN("Mono: Failed to load GodotTools assemblies");
+ CRASH_NOW();
}
+#endif
+ // Load the project's main assembly. Here, during hot-reloading, we do
+ // consider failing to load the project's main assembly to be an error.
+ // However, unlike the API and tools assemblies, the application can continue working.
if (!_load_project_assembly()) {
+ print_error("Mono: Failed to load project assembly");
return ERR_CANT_OPEN;
}
-#else
- print_verbose("Mono: Glue disabled, ignoring script assemblies.");
-#endif // MONO_GLUE_ENABLED
return OK;
}
@@ -926,6 +927,7 @@ Error GDMono::reload_scripts_domain() {
Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) {
CRASH_COND(p_domain == NULL);
+ CRASH_COND(p_domain == GDMono::get_singleton()->get_scripts_domain()); // Should use _unload_scripts_domain() instead
String domain_name = mono_domain_get_friendly_name(p_domain);
@@ -942,18 +944,12 @@ Error GDMono::finalize_and_unload_domain(MonoDomain *p_domain) {
_domain_assemblies_cleanup(mono_domain_get_id(p_domain));
-#ifdef TOOLS_ENABLED
- if (p_domain == tools_domain) {
- editor_tools_assembly = NULL;
- }
-#endif
-
MonoException *exc = NULL;
mono_domain_try_unload(p_domain, (MonoObject **)&exc);
if (exc) {
ERR_PRINTS("Exception thrown when unloading domain `" + domain_name + "`");
- GDMonoUtils::debug_unhandled_exception(exc);
+ GDMonoUtils::debug_print_unhandled_exception(exc);
return FAILED;
}
@@ -984,6 +980,22 @@ GDMonoClass *GDMono::get_class(MonoClass *p_raw_class) {
return NULL;
}
+GDMonoClass *GDMono::get_class(const StringName &p_namespace, const StringName &p_name) {
+
+ uint32_t domain_id = mono_domain_get_id(mono_domain_get());
+ HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[domain_id];
+
+ const String *k = NULL;
+ while ((k = domain_assemblies.next(k))) {
+ GDMonoAssembly *assembly = domain_assemblies.get(*k);
+ GDMonoClass *klass = assembly->get_class(p_namespace, p_name);
+ if (klass)
+ return klass;
+ }
+
+ return NULL;
+}
+
void GDMono::_domain_assemblies_cleanup(uint32_t p_domain_id) {
HashMap<String, GDMonoAssembly *> &domain_assemblies = assemblies[p_domain_id];
@@ -1024,9 +1036,6 @@ GDMono::GDMono() {
root_domain = NULL;
scripts_domain = NULL;
-#ifdef TOOLS_ENABLED
- tools_domain = NULL;
-#endif
core_api_assembly_out_of_sync = false;
#ifdef TOOLS_ENABLED
@@ -1038,7 +1047,8 @@ GDMono::GDMono() {
project_assembly = NULL;
#ifdef TOOLS_ENABLED
editor_api_assembly = NULL;
- editor_tools_assembly = NULL;
+ tools_assembly = NULL;
+ tools_project_editor_assembly = NULL;
#endif
api_core_hash = 0;
@@ -1050,16 +1060,6 @@ GDMono::GDMono() {
GDMono::~GDMono() {
if (is_runtime_initialized()) {
-
-#ifdef TOOLS_ENABLED
- if (tools_domain) {
- Error err = finalize_and_unload_domain(tools_domain);
- if (err != OK) {
- ERR_PRINT("Mono: Failed to unload tools domain");
- }
- }
-#endif
-
if (scripts_domain) {
Error err = _unload_scripts_domain();
if (err != OK) {
@@ -1078,8 +1078,6 @@ GDMono::~GDMono() {
}
assemblies.clear();
- GDMonoUtils::clear_cache();
-
print_verbose("Mono: Runtime cleanup...");
mono_jit_cleanup(root_domain);
@@ -1116,14 +1114,14 @@ int32_t _GodotSharp::get_domain_id() {
int32_t _GodotSharp::get_scripts_domain_id() {
- MonoDomain *domain = SCRIPTS_DOMAIN;
+ MonoDomain *domain = GDMono::get_singleton()->get_scripts_domain();
CRASH_COND(!domain); // User must check if scripts domain is loaded before calling this method
return mono_domain_get_id(domain);
}
bool _GodotSharp::is_scripts_domain_loaded() {
- return GDMono::get_singleton()->is_runtime_initialized() && SCRIPTS_DOMAIN != NULL;
+ return GDMono::get_singleton()->is_runtime_initialized() && GDMono::get_singleton()->get_scripts_domain() != NULL;
}
bool _GodotSharp::_is_domain_finalizing_for_unload(int32_t p_domain_id) {
@@ -1145,7 +1143,7 @@ bool _GodotSharp::is_domain_finalizing_for_unload(MonoDomain *p_domain) {
if (!p_domain)
return true;
- if (p_domain == SCRIPTS_DOMAIN && GDMono::get_singleton()->is_finalizing_scripts_domain())
+ if (p_domain == GDMono::get_singleton()->get_scripts_domain() && GDMono::get_singleton()->is_finalizing_scripts_domain())
return true;
return mono_domain_is_unloading(p_domain);
}
@@ -1160,6 +1158,12 @@ bool _GodotSharp::is_runtime_initialized() {
return GDMono::get_singleton()->is_runtime_initialized();
}
+void _GodotSharp::_reload_assemblies(bool p_soft_reload) {
+#ifdef GD_MONO_HOT_RELOAD
+ CSharpLanguage::get_singleton()->reload_assemblies(p_soft_reload);
+#endif
+}
+
void _GodotSharp::_bind_methods() {
ClassDB::bind_method(D_METHOD("attach_thread"), &_GodotSharp::attach_thread);
@@ -1172,6 +1176,7 @@ void _GodotSharp::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_runtime_shutting_down"), &_GodotSharp::is_runtime_shutting_down);
ClassDB::bind_method(D_METHOD("is_runtime_initialized"), &_GodotSharp::is_runtime_initialized);
+ ClassDB::bind_method(D_METHOD("_reload_assemblies"), &_GodotSharp::_reload_assemblies);
}
_GodotSharp::_GodotSharp() {
diff --git a/modules/mono/mono_gd/gd_mono.h b/modules/mono/mono_gd/gd_mono.h
index 216c96a612..deebe5fd50 100644
--- a/modules/mono/mono_gd/gd_mono.h
+++ b/modules/mono/mono_gd/gd_mono.h
@@ -78,11 +78,6 @@ struct Version {
String to_string(Type p_type);
} // namespace APIAssembly
-#define SCRIPTS_DOMAIN GDMono::get_singleton()->get_scripts_domain()
-#ifdef TOOLS_ENABLED
-#define TOOLS_DOMAIN GDMono::get_singleton()->get_tools_domain()
-#endif
-
class GDMono {
bool runtime_initialized;
@@ -90,9 +85,6 @@ class GDMono {
MonoDomain *root_domain;
MonoDomain *scripts_domain;
-#ifdef TOOLS_ENABLED
- MonoDomain *tools_domain;
-#endif
bool core_api_assembly_out_of_sync;
#ifdef TOOLS_ENABLED
@@ -104,26 +96,26 @@ class GDMono {
GDMonoAssembly *project_assembly;
#ifdef TOOLS_ENABLED
GDMonoAssembly *editor_api_assembly;
- GDMonoAssembly *editor_tools_assembly;
+ GDMonoAssembly *tools_assembly;
+ GDMonoAssembly *tools_project_editor_assembly;
#endif
HashMap<uint32_t, HashMap<String, GDMonoAssembly *> > assemblies;
void _domain_assemblies_cleanup(uint32_t p_domain_id);
+ bool _are_api_assemblies_out_of_sync();
+
bool _load_corlib_assembly();
bool _load_core_api_assembly();
#ifdef TOOLS_ENABLED
bool _load_editor_api_assembly();
- bool _load_editor_tools_assembly();
+ bool _load_tools_assemblies();
#endif
bool _load_project_assembly();
- bool _load_api_assemblies();
-
-#ifdef TOOLS_ENABLED
- String _get_api_assembly_metadata_path();
-#endif
+ bool _try_load_api_assemblies();
+ void _load_api_assemblies();
void _install_trace_listener();
@@ -132,10 +124,6 @@ class GDMono {
Error _load_scripts_domain();
Error _unload_scripts_domain();
-#ifdef TOOLS_ENABLED
- Error _load_tools_domain();
-#endif
-
uint64_t api_core_hash;
#ifdef TOOLS_ENABLED
uint64_t api_editor_hash;
@@ -168,8 +156,8 @@ public:
#endif
#ifdef TOOLS_ENABLED
- void metadata_set_api_assembly_invalidated(APIAssembly::Type p_api_type, bool p_invalidated);
- bool metadata_is_api_assembly_invalidated(APIAssembly::Type p_api_type);
+ bool copy_prebuilt_api_assembly(APIAssembly::Type p_api_type);
+ String update_api_assemblies_from_prebuilt();
#endif
static GDMono *get_singleton() { return singleton; }
@@ -185,16 +173,14 @@ public:
_FORCE_INLINE_ bool is_finalizing_scripts_domain() { return finalizing_scripts_domain; }
_FORCE_INLINE_ MonoDomain *get_scripts_domain() { return scripts_domain; }
-#ifdef TOOLS_ENABLED
- _FORCE_INLINE_ MonoDomain *get_tools_domain() { return tools_domain; }
-#endif
_FORCE_INLINE_ GDMonoAssembly *get_corlib_assembly() const { return corlib_assembly; }
_FORCE_INLINE_ GDMonoAssembly *get_core_api_assembly() const { return core_api_assembly; }
_FORCE_INLINE_ GDMonoAssembly *get_project_assembly() const { return project_assembly; }
#ifdef TOOLS_ENABLED
_FORCE_INLINE_ GDMonoAssembly *get_editor_api_assembly() const { return editor_api_assembly; }
- _FORCE_INLINE_ GDMonoAssembly *get_editor_tools_assembly() const { return editor_tools_assembly; }
+ _FORCE_INLINE_ GDMonoAssembly *get_tools_assembly() const { return tools_assembly; }
+ _FORCE_INLINE_ GDMonoAssembly *get_tools_project_editor_assembly() const { return tools_project_editor_assembly; }
#endif
#if defined(WINDOWS_ENABLED) && defined(TOOLS_ENABLED)
@@ -202,6 +188,7 @@ public:
#endif
GDMonoClass *get_class(MonoClass *p_raw_class);
+ GDMonoClass *get_class(const StringName &p_namespace, const StringName &p_name);
#ifdef GD_MONO_HOT_RELOAD
Error reload_scripts_domain();
@@ -214,6 +201,7 @@ public:
Error finalize_and_unload_domain(MonoDomain *p_domain);
void initialize();
+ void initialize_load_assemblies();
GDMono();
~GDMono();
@@ -267,7 +255,7 @@ public:
(void)__gdmono__scope__exit__domain__unload__;
class _GodotSharp : public Object {
- GDCLASS(_GodotSharp, Object)
+ GDCLASS(_GodotSharp, Object);
friend class GDMono;
@@ -276,6 +264,8 @@ class _GodotSharp : public Object {
List<NodePath *> np_delete_queue;
List<RID *> rid_delete_queue;
+ void _reload_assemblies(bool p_soft_reload);
+
protected:
static _GodotSharp *singleton;
static void _bind_methods();
diff --git a/modules/mono/mono_gd/gd_mono_assembly.cpp b/modules/mono/mono_gd/gd_mono_assembly.cpp
index 8fec28b186..761c7f6fcb 100644
--- a/modules/mono/mono_gd/gd_mono_assembly.cpp
+++ b/modules/mono/mono_gd/gd_mono_assembly.cpp
@@ -46,11 +46,17 @@ bool GDMonoAssembly::in_preload = false;
Vector<String> GDMonoAssembly::search_dirs;
-void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config) {
+void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config, const String &p_custom_bcl_dir) {
- const char *rootdir = mono_assembly_getrootdir();
- if (rootdir) {
- String framework_dir = String::utf8(rootdir).plus_file("mono").plus_file("4.5");
+ String framework_dir;
+
+ if (!p_custom_bcl_dir.empty()) {
+ framework_dir = p_custom_bcl_dir;
+ } else if (mono_assembly_getrootdir()) {
+ framework_dir = String::utf8(mono_assembly_getrootdir()).plus_file("mono").plus_file("4.5");
+ }
+
+ if (!framework_dir.empty()) {
r_search_dirs.push_back(framework_dir);
r_search_dirs.push_back(framework_dir.plus_file("Facades"));
}
@@ -61,11 +67,22 @@ void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const Strin
r_search_dirs.push_back(GodotSharpDirs::get_res_temp_assemblies_dir());
}
- r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_dir());
+ if (p_custom_config.empty()) {
+ r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_dir());
+ } else {
+ String api_config = p_custom_config == "Release" ? "Release" : "Debug";
+ r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir().plus_file(api_config));
+ }
+
+ r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir());
r_search_dirs.push_back(OS::get_singleton()->get_resource_dir());
r_search_dirs.push_back(OS::get_singleton()->get_executable_path().get_base_dir());
+
#ifdef TOOLS_ENABLED
r_search_dirs.push_back(GodotSharpDirs::get_data_editor_tools_dir());
+
+ // For GodotTools to find the api assemblies
+ r_search_dirs.push_back(GodotSharpDirs::get_data_editor_prebuilt_api_dir().plus_file("Debug"));
#endif
}
@@ -264,7 +281,18 @@ Error GDMonoAssembly::load(bool p_refonly) {
Vector<uint8_t> data = FileAccess::get_file_as_array(path);
ERR_FAIL_COND_V(data.empty(), ERR_FILE_CANT_READ);
- String image_filename = ProjectSettings::get_singleton()->globalize_path(path);
+ String image_filename;
+
+#ifdef ANDROID_ENABLED
+ if (path.begins_with("res://")) {
+ image_filename = path.substr(6, path.length());
+ } else {
+ image_filename = ProjectSettings::get_singleton()->globalize_path(path);
+ }
+#else
+ // FIXME: globalize_path does not work on exported games
+ image_filename = ProjectSettings::get_singleton()->globalize_path(path);
+#endif
MonoImageOpenStatus status = MONO_IMAGE_OK;
diff --git a/modules/mono/mono_gd/gd_mono_assembly.h b/modules/mono/mono_gd/gd_mono_assembly.h
index 32432af37d..39749dfc1d 100644
--- a/modules/mono/mono_gd/gd_mono_assembly.h
+++ b/modules/mono/mono_gd/gd_mono_assembly.h
@@ -122,7 +122,7 @@ public:
GDMonoClass *get_object_derived_class(const StringName &p_class);
- static void fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config = String());
+ static void fill_search_dirs(Vector<String> &r_search_dirs, const String &p_custom_config = String(), const String &p_custom_bcl_dir = String());
static GDMonoAssembly *load_from(const String &p_name, const String &p_path, bool p_refonly);
diff --git a/modules/mono/mono_gd/gd_mono_class.cpp b/modules/mono/mono_gd/gd_mono_class.cpp
index 4342f46109..1c10d3c8eb 100644
--- a/modules/mono/mono_gd/gd_mono_class.cpp
+++ b/modules/mono/mono_gd/gd_mono_class.cpp
@@ -41,7 +41,7 @@ String GDMonoClass::get_full_name(MonoClass *p_mono_class) {
MonoException *exc = NULL;
MonoString *str = GDMonoUtils::object_to_string((MonoObject *)type_obj, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return GDMonoMarshal::mono_string_to_godot(str);
}
@@ -74,16 +74,13 @@ bool GDMonoClass::is_assignable_from(GDMonoClass *p_from) const {
}
GDMonoClass *GDMonoClass::get_parent_class() {
+ MonoClass *parent_mono_class = mono_class_get_parent(mono_class);
+ return parent_mono_class ? GDMono::get_singleton()->get_class(parent_mono_class) : NULL;
+}
- if (assembly) {
- MonoClass *parent_mono_class = mono_class_get_parent(mono_class);
-
- if (parent_mono_class) {
- return GDMono::get_singleton()->get_class(parent_mono_class);
- }
- }
-
- return NULL;
+GDMonoClass *GDMonoClass::get_nesting_class() {
+ MonoClass *nesting_type = mono_class_get_nesting_type(mono_class);
+ return nesting_type ? GDMono::get_singleton()->get_class(nesting_type) : NULL;
}
#ifdef TOOLS_ENABLED
diff --git a/modules/mono/mono_gd/gd_mono_class.h b/modules/mono/mono_gd/gd_mono_class.h
index 249422b844..40e1574927 100644
--- a/modules/mono/mono_gd/gd_mono_class.h
+++ b/modules/mono/mono_gd/gd_mono_class.h
@@ -121,6 +121,7 @@ public:
_FORCE_INLINE_ const GDMonoAssembly *get_assembly() const { return assembly; }
GDMonoClass *get_parent_class();
+ GDMonoClass *get_nesting_class();
#ifdef TOOLS_ENABLED
Vector<MonoClassField *> get_enum_fields();
diff --git a/modules/mono/mono_gd/gd_mono_field.cpp b/modules/mono/mono_gd/gd_mono_field.cpp
index 2e79f87625..3999658f93 100644
--- a/modules/mono/mono_gd/gd_mono_field.cpp
+++ b/modules/mono/mono_gd/gd_mono_field.cpp
@@ -315,7 +315,7 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_
// The order in which we check the following interfaces is very important (dictionaries and generics first)
- MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, type_class->get_mono_type());
+ MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type_class->get_mono_type());
MonoReflectionType *key_reftype, *value_reftype;
if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype, &key_reftype, &value_reftype)) {
@@ -340,9 +340,15 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_
}
if (type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array));
- mono_field_set_value(p_object, mono_field, managed);
- break;
+ if (GDMonoUtils::tools_godot_api_check()) {
+ MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array));
+ mono_field_set_value(p_object, mono_field, managed);
+ break;
+ } else {
+ MonoObject *managed = (MonoObject *)GDMonoMarshal::Array_to_mono_array(p_value.operator Array());
+ mono_field_set_value(p_object, mono_field, managed);
+ break;
+ }
}
ERR_EXPLAIN(String() + "Attempted to set the value of a field of unmarshallable type: " + type_class->get_name());
@@ -450,7 +456,7 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_
} break;
case MONO_TYPE_GENERICINST: {
- MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, type.type_class->get_mono_type());
+ MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type.type_class->get_mono_type());
if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Dictionary(), type.type_class);
@@ -489,9 +495,15 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_
}
if (type.type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) {
- MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array));
- mono_field_set_value(p_object, mono_field, managed);
- break;
+ if (GDMonoUtils::tools_godot_api_check()) {
+ MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator Array(), CACHED_CLASS(Array));
+ mono_field_set_value(p_object, mono_field, managed);
+ break;
+ } else {
+ MonoObject *managed = (MonoObject *)GDMonoMarshal::Array_to_mono_array(p_value.operator Array());
+ mono_field_set_value(p_object, mono_field, managed);
+ break;
+ }
}
} break;
diff --git a/modules/mono/mono_gd/gd_mono_internals.cpp b/modules/mono/mono_gd/gd_mono_internals.cpp
index 63bcfe053c..a84332d4cd 100644
--- a/modules/mono/mono_gd/gd_mono_internals.cpp
+++ b/modules/mono/mono_gd/gd_mono_internals.cpp
@@ -74,15 +74,14 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) {
script_binding.type_name = NATIVE_GDMONOCLASS_NAME(klass);
script_binding.wrapper_class = klass;
script_binding.gchandle = MonoGCHandle::create_strong(managed);
+ script_binding.owner = unmanaged;
- Reference *kref = Object::cast_to<Reference>(unmanaged);
- if (kref) {
+ if (ref) {
// Unsafe refcount increment. The managed instance also counts as a reference.
// This way if the unmanaged world has no references to our owner
// but the managed instance is alive, the refcount will be 1 instead of 0.
// See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr)
-
- kref->reference();
+ ref->reference();
}
// The object was just created, no script instance binding should have been attached
@@ -105,8 +104,6 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) {
ScriptInstance *si = CSharpInstance::create_for_managed_type(unmanaged, script.ptr(), gchandle);
unmanaged->set_script_and_instance(script.get_ref_ptr(), si);
-
- return;
}
void unhandled_exception(MonoException *p_exc) {
diff --git a/modules/mono/mono_gd/gd_mono_marshal.cpp b/modules/mono/mono_gd/gd_mono_marshal.cpp
index c462b8f71d..42102ed835 100644
--- a/modules/mono/mono_gd/gd_mono_marshal.cpp
+++ b/modules/mono/mono_gd/gd_mono_marshal.cpp
@@ -159,7 +159,7 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type) {
// The order in which we check the following interfaces is very important (dictionaries and generics first)
- MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, type_class->get_mono_type());
+ MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type_class->get_mono_type());
if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype)) {
return Variant::DICTIONARY;
@@ -179,7 +179,7 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type) {
} break;
case MONO_TYPE_GENERICINST: {
- MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, p_type.type_class->get_mono_type());
+ MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type());
if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
return Variant::DICTIONARY;
@@ -217,7 +217,7 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type) {
bool try_get_array_element_type(const ManagedType &p_array_type, ManagedType &r_elem_type) {
switch (p_array_type.type_encoding) {
case MONO_TYPE_GENERICINST: {
- MonoReflectionType *array_reftype = mono_type_get_object(SCRIPTS_DOMAIN, p_array_type.type_class->get_mono_type());
+ MonoReflectionType *array_reftype = mono_type_get_object(mono_domain_get(), p_array_type.type_class->get_mono_type());
if (GDMonoUtils::Marshal::type_is_generic_array(array_reftype)) {
MonoReflectionType *elem_reftype;
@@ -244,7 +244,7 @@ bool try_get_array_element_type(const ManagedType &p_array_type, ManagedType &r_
bool try_get_dictionary_key_value_types(const ManagedType &p_dictionary_type, ManagedType &r_key_type, ManagedType &r_value_type) {
switch (p_dictionary_type.type_encoding) {
case MONO_TYPE_GENERICINST: {
- MonoReflectionType *dict_reftype = mono_type_get_object(SCRIPTS_DOMAIN, p_dictionary_type.type_class->get_mono_type());
+ MonoReflectionType *dict_reftype = mono_type_get_object(mono_domain_get(), p_dictionary_type.type_class->get_mono_type());
if (GDMonoUtils::Marshal::type_is_generic_dictionary(dict_reftype)) {
MonoReflectionType *key_reftype;
@@ -539,7 +539,7 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty
// The order in which we check the following interfaces is very important (dictionaries and generics first)
- MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, type_class->get_mono_type());
+ MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type_class->get_mono_type());
MonoReflectionType *key_reftype, *value_reftype;
if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype, &key_reftype, &value_reftype)) {
@@ -558,7 +558,11 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty
}
if (type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) {
- return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array));
+ if (GDMonoUtils::tools_godot_api_check()) {
+ return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array));
+ } else {
+ return (MonoObject *)GDMonoMarshal::Array_to_mono_array(p_var->operator Array());
+ }
}
} break;
case MONO_TYPE_OBJECT: {
@@ -652,7 +656,7 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty
}
break;
case MONO_TYPE_GENERICINST: {
- MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, p_type.type_class->get_mono_type());
+ MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), p_type.type_class->get_mono_type());
if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
return GDMonoUtils::create_managed_from(p_var->operator Dictionary(), p_type.type_class);
@@ -681,7 +685,11 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty
}
if (p_type.type_class->implements_interface(CACHED_CLASS(System_Collections_IEnumerable))) {
- return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array));
+ if (GDMonoUtils::tools_godot_api_check()) {
+ return GDMonoUtils::create_managed_from(p_var->operator Array(), CACHED_CLASS(Array));
+ } else {
+ return (MonoObject *)GDMonoMarshal::Array_to_mono_array(p_var->operator Array());
+ }
}
} break;
} break;
@@ -831,20 +839,20 @@ Variant mono_object_to_variant(MonoObject *p_obj) {
if (CACHED_CLASS(Array) == type_class) {
MonoException *exc = NULL;
Array *ptr = invoke_method_thunk(CACHED_METHOD_THUNK(Array, GetPtr), p_obj, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return ptr ? Variant(*ptr) : Variant();
}
if (CACHED_CLASS(Dictionary) == type_class) {
MonoException *exc = NULL;
Dictionary *ptr = invoke_method_thunk(CACHED_METHOD_THUNK(Dictionary, GetPtr), p_obj, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return ptr ? Variant(*ptr) : Variant();
}
// The order in which we check the following interfaces is very important (dictionaries and generics first)
- MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, type_class->get_mono_type());
+ MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type_class->get_mono_type());
if (GDMonoUtils::Marshal::generic_idictionary_is_assignable_from(reftype)) {
return GDMonoUtils::Marshal::generic_idictionary_to_dictionary(p_obj);
@@ -864,19 +872,19 @@ Variant mono_object_to_variant(MonoObject *p_obj) {
} break;
case MONO_TYPE_GENERICINST: {
- MonoReflectionType *reftype = mono_type_get_object(SCRIPTS_DOMAIN, type.type_class->get_mono_type());
+ MonoReflectionType *reftype = mono_type_get_object(mono_domain_get(), type.type_class->get_mono_type());
if (GDMonoUtils::Marshal::type_is_generic_dictionary(reftype)) {
MonoException *exc = NULL;
MonoObject *ret = type.type_class->get_method("GetPtr")->invoke(p_obj, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return *unbox<Dictionary *>(ret);
}
if (GDMonoUtils::Marshal::type_is_generic_array(reftype)) {
MonoException *exc = NULL;
MonoObject *ret = type.type_class->get_method("GetPtr")->invoke(p_obj, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return *unbox<Array *>(ret);
}
@@ -1019,7 +1027,7 @@ MonoArray *PoolStringArray_to_mono_array(const PoolStringArray &p_array) {
for (int i = 0; i < p_array.size(); i++) {
MonoString *boxed = mono_string_from_godot(r[i]);
- mono_array_set(ret, MonoString *, i, boxed);
+ mono_array_setref(ret, i, boxed);
}
return ret;
diff --git a/modules/mono/mono_gd/gd_mono_method.cpp b/modules/mono/mono_gd/gd_mono_method.cpp
index f290c6c8ac..968b316a3e 100644
--- a/modules/mono/mono_gd/gd_mono_method.cpp
+++ b/modules/mono/mono_gd/gd_mono_method.cpp
@@ -109,7 +109,7 @@ MonoObject *GDMonoMethod::invoke(MonoObject *p_object, const Variant **p_params,
for (int i = 0; i < params_count; i++) {
MonoObject *boxed_param = GDMonoMarshal::variant_to_mono_object(p_params[i], param_types[i]);
- mono_array_set(params, MonoObject *, i, boxed_param);
+ mono_array_setref(params, i, boxed_param);
}
MonoException *exc = NULL;
diff --git a/modules/mono/mono_gd/gd_mono_property.cpp b/modules/mono/mono_gd/gd_mono_property.cpp
index 5842e26241..f1da00638f 100644
--- a/modules/mono/mono_gd/gd_mono_property.cpp
+++ b/modules/mono/mono_gd/gd_mono_property.cpp
@@ -142,7 +142,7 @@ bool GDMonoProperty::has_setter() {
void GDMonoProperty::set_value(MonoObject *p_object, MonoObject *p_value, MonoException **r_exc) {
MonoMethod *prop_method = mono_property_get_set_method(mono_property);
MonoArray *params = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), 1);
- mono_array_set(params, MonoObject *, 0, p_value);
+ mono_array_setref(params, 0, p_value);
MonoException *exc = NULL;
GDMonoUtils::runtime_invoke_array(prop_method, p_object, params, &exc);
if (exc) {
diff --git a/modules/mono/mono_gd/gd_mono_utils.cpp b/modules/mono/mono_gd/gd_mono_utils.cpp
index 413c8cba85..5987fa8ebb 100644
--- a/modules/mono/mono_gd/gd_mono_utils.cpp
+++ b/modules/mono/mono_gd/gd_mono_utils.cpp
@@ -50,6 +50,7 @@ MonoCache mono_cache;
#define CACHE_AND_CHECK(m_var, m_val) \
{ \
+ CRASH_COND(m_var != NULL); \
m_var = m_val; \
if (!m_var) { \
ERR_EXPLAIN("Mono Cache: Member " #m_var " is null"); \
@@ -65,7 +66,9 @@ MonoCache mono_cache;
#define CACHE_METHOD_THUNK_AND_CHECK(m_class, m_method, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.methodthunk_##m_class##_##m_method, m_val)
#define CACHE_PROPERTY_AND_CHECK(m_class, m_property, m_val) CACHE_AND_CHECK(GDMonoUtils::mono_cache.property_##m_class##_##m_property, m_val)
-void MonoCache::clear_members() {
+void MonoCache::clear_corlib_cache() {
+
+ corlib_cache_updated = false;
class_MonoObject = NULL;
class_bool = NULL;
@@ -93,6 +96,11 @@ void MonoCache::clear_members() {
#endif
class_KeyNotFoundException = NULL;
+}
+
+void MonoCache::clear_godot_api_cache() {
+
+ godot_api_cache_updated = false;
rawclass_Dictionary = NULL;
@@ -117,6 +125,7 @@ void MonoCache::clear_members() {
class_Array = NULL;
class_Dictionary = NULL;
class_MarshalUtils = NULL;
+ class_ISerializationListener = NULL;
#ifdef DEBUG_ENABLED
class_DebuggingUtils = NULL;
@@ -176,12 +185,6 @@ void MonoCache::clear_members() {
task_scheduler_handle = Ref<MonoGCHandle>();
}
-void MonoCache::cleanup() {
-
- corlib_cache_updated = false;
- godot_api_cache_updated = false;
-}
-
#define GODOT_API_CLASS(m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, #m_class))
#define GODOT_API_NS_CLAS(m_ns, m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(m_ns, #m_class))
@@ -240,6 +243,7 @@ void update_godot_api_cache() {
CACHE_CLASS_AND_CHECK(Array, GODOT_API_NS_CLAS(BINDINGS_NAMESPACE_COLLECTIONS, Array));
CACHE_CLASS_AND_CHECK(Dictionary, GODOT_API_NS_CLAS(BINDINGS_NAMESPACE_COLLECTIONS, Dictionary));
CACHE_CLASS_AND_CHECK(MarshalUtils, GODOT_API_CLASS(MarshalUtils));
+ CACHE_CLASS_AND_CHECK(ISerializationListener, GODOT_API_CLASS(ISerializationListener));
#ifdef DEBUG_ENABLED
CACHE_CLASS_AND_CHECK(DebuggingUtils, GODOT_API_CLASS(DebuggingUtils));
@@ -281,13 +285,10 @@ void update_godot_api_cache() {
CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, ArrayGetElementType, (ArrayGetElementType)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("ArrayGetElementType", 2));
CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, DictionaryGetKeyValueTypes, (DictionaryGetKeyValueTypes)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("DictionaryGetKeyValueTypes", 3));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, ArrayGetElementType, (ArrayGetElementType)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("ArrayGetElementType", 2));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, DictionaryGetKeyValueTypes, (DictionaryGetKeyValueTypes)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("DictionaryGetKeyValueTypes", 3));
-
CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GenericIEnumerableIsAssignableFromType, (GenericIEnumerableIsAssignableFromType)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("GenericIEnumerableIsAssignableFromType", 1));
CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GenericIDictionaryIsAssignableFromType, (GenericIDictionaryIsAssignableFromType)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("GenericIDictionaryIsAssignableFromType", 1));
CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GenericIEnumerableIsAssignableFromType_with_info, (GenericIEnumerableIsAssignableFromType_with_info)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("GenericIEnumerableIsAssignableFromType", 2));
- CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GenericIEnumerableIsAssignableFromType_with_info, (GenericIEnumerableIsAssignableFromType_with_info)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("GenericIDictionaryIsAssignableFromType", 3));
+ CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, GenericIDictionaryIsAssignableFromType_with_info, (GenericIDictionaryIsAssignableFromType_with_info)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("GenericIDictionaryIsAssignableFromType", 3));
CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, MakeGenericArrayType, (MakeGenericArrayType)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("MakeGenericArrayType", 1));
CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, MakeGenericDictionaryType, (MakeGenericDictionaryType)GODOT_API_CLASS(MarshalUtils)->get_method_thunk("MakeGenericDictionaryType", 2));
@@ -303,18 +304,13 @@ void update_godot_api_cache() {
#endif
// TODO Move to CSharpLanguage::init() and do handle disposal
- MonoObject *task_scheduler = mono_object_new(SCRIPTS_DOMAIN, GODOT_API_CLASS(GodotTaskScheduler)->get_mono_ptr());
+ MonoObject *task_scheduler = mono_object_new(mono_domain_get(), GODOT_API_CLASS(GodotTaskScheduler)->get_mono_ptr());
GDMonoUtils::runtime_object_init(task_scheduler, GODOT_API_CLASS(GodotTaskScheduler));
mono_cache.task_scheduler_handle = MonoGCHandle::create_strong(task_scheduler);
mono_cache.godot_api_cache_updated = true;
}
-void clear_cache() {
- mono_cache.cleanup();
- mono_cache.clear_members();
-}
-
MonoObject *unmanaged_get_managed(Object *unmanaged) {
if (!unmanaged)
@@ -377,7 +373,6 @@ MonoObject *unmanaged_get_managed(Object *unmanaged) {
// This way if the unmanaged world has no references to our owner
// but the managed instance is alive, the refcount will be 1 instead of 0.
// See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr)
-
ref->reference();
}
@@ -390,7 +385,7 @@ void set_main_thread(MonoThread *p_thread) {
void attach_current_thread() {
ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized());
- MonoThread *mono_thread = mono_thread_attach(SCRIPTS_DOMAIN);
+ MonoThread *mono_thread = mono_thread_attach(mono_domain_get());
ERR_FAIL_NULL(mono_thread);
}
@@ -454,17 +449,12 @@ GDMonoClass *get_class_native_base(GDMonoClass *p_class) {
}
MonoObject *create_managed_for_godot_object(GDMonoClass *p_class, const StringName &p_native, Object *p_object) {
- String object_type = p_object->get_class_name();
-
- if (object_type[0] == '_')
- object_type = object_type.substr(1, object_type.length());
-
- if (!ClassDB::is_parent_class(object_type, p_native)) {
+ if (!ClassDB::is_parent_class(p_object->get_class_name(), p_native)) {
ERR_EXPLAIN("Type inherits from native type '" + p_native + "', so it can't be instanced in object of type: '" + p_object->get_class() + "'");
ERR_FAIL_V(NULL);
}
- MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, p_class->get_mono_ptr());
+ MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr());
ERR_FAIL_NULL_V(mono_object, NULL);
CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, p_object);
@@ -476,7 +466,7 @@ MonoObject *create_managed_for_godot_object(GDMonoClass *p_class, const StringNa
}
MonoObject *create_managed_from(const NodePath &p_from) {
- MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, CACHED_CLASS_RAW(NodePath));
+ MonoObject *mono_object = mono_object_new(mono_domain_get(), CACHED_CLASS_RAW(NodePath));
ERR_FAIL_NULL_V(mono_object, NULL);
// Construct
@@ -488,7 +478,7 @@ MonoObject *create_managed_from(const NodePath &p_from) {
}
MonoObject *create_managed_from(const RID &p_from) {
- MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, CACHED_CLASS_RAW(RID));
+ MonoObject *mono_object = mono_object_new(mono_domain_get(), CACHED_CLASS_RAW(RID));
ERR_FAIL_NULL_V(mono_object, NULL);
// Construct
@@ -500,7 +490,7 @@ MonoObject *create_managed_from(const RID &p_from) {
}
MonoObject *create_managed_from(const Array &p_from, GDMonoClass *p_class) {
- MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, p_class->get_mono_ptr());
+ MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr());
ERR_FAIL_NULL_V(mono_object, NULL);
// Search constructor that takes a pointer as parameter
@@ -524,13 +514,13 @@ MonoObject *create_managed_from(const Array &p_from, GDMonoClass *p_class) {
MonoException *exc = NULL;
GDMonoUtils::runtime_invoke(m, mono_object, args, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return mono_object;
}
MonoObject *create_managed_from(const Dictionary &p_from, GDMonoClass *p_class) {
- MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, p_class->get_mono_ptr());
+ MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr());
ERR_FAIL_NULL_V(mono_object, NULL);
// Search constructor that takes a pointer as parameter
@@ -554,7 +544,7 @@ MonoObject *create_managed_from(const Dictionary &p_from, GDMonoClass *p_class)
MonoException *exc = NULL;
GDMonoUtils::runtime_invoke(m, mono_object, args, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return mono_object;
}
@@ -673,7 +663,10 @@ void print_unhandled_exception(MonoException *p_exc) {
}
void set_pending_exception(MonoException *p_exc) {
-#ifdef HAS_PENDING_EXCEPTIONS
+#ifdef NO_PENDING_EXCEPTIONS
+ debug_unhandled_exception(p_exc);
+ GD_UNREACHABLE();
+#else
if (get_runtime_invoke_count() == 0) {
debug_unhandled_exception(p_exc);
GD_UNREACHABLE();
@@ -683,9 +676,6 @@ void set_pending_exception(MonoException *p_exc) {
ERR_PRINTS("Exception thrown from managed code, but it could not be set as pending:");
GDMonoUtils::debug_print_unhandled_exception(p_exc);
}
-#else
- debug_unhandled_exception(p_exc);
- GD_UNREACHABLE();
#endif
}
@@ -761,113 +751,137 @@ void dispose(MonoObject *p_mono_object, MonoException **r_exc) {
namespace Marshal {
-MonoBoolean type_is_generic_array(MonoReflectionType *p_reftype) {
+#ifdef MONO_GLUE_ENABLED
+#ifdef TOOLS_ENABLED
+#define NO_GLUE_RET(m_ret) \
+ { \
+ if (!mono_cache.godot_api_cache_updated) return m_ret; \
+ }
+#else
+#define NO_GLUE_RET(m_ret) \
+ {}
+#endif
+#else
+#define NO_GLUE_RET(m_ret) \
+ { return m_ret; }
+#endif
+
+bool type_is_generic_array(MonoReflectionType *p_reftype) {
+ NO_GLUE_RET(false);
TypeIsGenericArray thunk = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericArray);
MonoException *exc = NULL;
MonoBoolean res = invoke_method_thunk(thunk, p_reftype, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
- return res;
+ UNHANDLED_EXCEPTION(exc);
+ return (bool)res;
}
-MonoBoolean type_is_generic_dictionary(MonoReflectionType *p_reftype) {
+bool type_is_generic_dictionary(MonoReflectionType *p_reftype) {
+ NO_GLUE_RET(false);
TypeIsGenericDictionary thunk = CACHED_METHOD_THUNK(MarshalUtils, TypeIsGenericDictionary);
MonoException *exc = NULL;
MonoBoolean res = invoke_method_thunk(thunk, p_reftype, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
- return res;
+ UNHANDLED_EXCEPTION(exc);
+ return (bool)res;
}
void array_get_element_type(MonoReflectionType *p_array_reftype, MonoReflectionType **r_elem_reftype) {
ArrayGetElementType thunk = CACHED_METHOD_THUNK(MarshalUtils, ArrayGetElementType);
MonoException *exc = NULL;
invoke_method_thunk(thunk, p_array_reftype, r_elem_reftype, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
}
void dictionary_get_key_value_types(MonoReflectionType *p_dict_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype) {
DictionaryGetKeyValueTypes thunk = CACHED_METHOD_THUNK(MarshalUtils, DictionaryGetKeyValueTypes);
MonoException *exc = NULL;
invoke_method_thunk(thunk, p_dict_reftype, r_key_reftype, r_value_reftype, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
}
-MonoBoolean generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype) {
+bool generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype) {
+ NO_GLUE_RET(false);
GenericIEnumerableIsAssignableFromType thunk = CACHED_METHOD_THUNK(MarshalUtils, GenericIEnumerableIsAssignableFromType);
MonoException *exc = NULL;
MonoBoolean res = invoke_method_thunk(thunk, p_reftype, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
- return res;
+ UNHANDLED_EXCEPTION(exc);
+ return (bool)res;
}
-MonoBoolean generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype) {
+bool generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype) {
+ NO_GLUE_RET(false);
GenericIDictionaryIsAssignableFromType thunk = CACHED_METHOD_THUNK(MarshalUtils, GenericIDictionaryIsAssignableFromType);
MonoException *exc = NULL;
MonoBoolean res = invoke_method_thunk(thunk, p_reftype, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
- return res;
+ UNHANDLED_EXCEPTION(exc);
+ return (bool)res;
}
-MonoBoolean generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_elem_reftype) {
+bool generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_elem_reftype) {
+ NO_GLUE_RET(false);
GenericIEnumerableIsAssignableFromType_with_info thunk = CACHED_METHOD_THUNK(MarshalUtils, GenericIEnumerableIsAssignableFromType_with_info);
MonoException *exc = NULL;
MonoBoolean res = invoke_method_thunk(thunk, p_reftype, r_elem_reftype, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
- return res;
+ UNHANDLED_EXCEPTION(exc);
+ return (bool)res;
}
-MonoBoolean generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype) {
+bool generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype) {
+ NO_GLUE_RET(false);
GenericIDictionaryIsAssignableFromType_with_info thunk = CACHED_METHOD_THUNK(MarshalUtils, GenericIDictionaryIsAssignableFromType_with_info);
MonoException *exc = NULL;
MonoBoolean res = invoke_method_thunk(thunk, p_reftype, r_key_reftype, r_value_reftype, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
- return res;
+ UNHANDLED_EXCEPTION(exc);
+ return (bool)res;
}
Array enumerable_to_array(MonoObject *p_enumerable) {
+ NO_GLUE_RET(Array());
Array result;
EnumerableToArray thunk = CACHED_METHOD_THUNK(MarshalUtils, EnumerableToArray);
MonoException *exc = NULL;
invoke_method_thunk(thunk, p_enumerable, &result, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return result;
}
Dictionary idictionary_to_dictionary(MonoObject *p_idictionary) {
+ NO_GLUE_RET(Dictionary());
Dictionary result;
IDictionaryToDictionary thunk = CACHED_METHOD_THUNK(MarshalUtils, IDictionaryToDictionary);
MonoException *exc = NULL;
invoke_method_thunk(thunk, p_idictionary, &result, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return result;
}
Dictionary generic_idictionary_to_dictionary(MonoObject *p_generic_idictionary) {
+ NO_GLUE_RET(Dictionary());
Dictionary result;
GenericIDictionaryToDictionary thunk = CACHED_METHOD_THUNK(MarshalUtils, GenericIDictionaryToDictionary);
MonoException *exc = NULL;
invoke_method_thunk(thunk, p_generic_idictionary, &result, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return result;
}
GDMonoClass *make_generic_array_type(MonoReflectionType *p_elem_reftype) {
+ NO_GLUE_RET(NULL);
MakeGenericArrayType thunk = CACHED_METHOD_THUNK(MarshalUtils, MakeGenericArrayType);
MonoException *exc = NULL;
MonoReflectionType *reftype = invoke_method_thunk(thunk, p_elem_reftype, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return GDMono::get_singleton()->get_class(mono_class_from_mono_type(mono_reflection_type_get_type(reftype)));
}
GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype) {
+ NO_GLUE_RET(NULL);
MakeGenericDictionaryType thunk = CACHED_METHOD_THUNK(MarshalUtils, MakeGenericDictionaryType);
MonoException *exc = NULL;
MonoReflectionType *reftype = invoke_method_thunk(thunk, p_key_reftype, p_value_reftype, &exc);
- UNLIKELY_UNHANDLED_EXCEPTION(exc);
+ UNHANDLED_EXCEPTION(exc);
return GDMono::get_singleton()->get_class(mono_class_from_mono_type(mono_reflection_type_get_type(reftype)));
}
} // namespace Marshal
-// namespace Marshal
-
} // namespace GDMonoUtils
diff --git a/modules/mono/mono_gd/gd_mono_utils.h b/modules/mono/mono_gd/gd_mono_utils.h
index ee239be959..f535fbb6d0 100644
--- a/modules/mono/mono_gd/gd_mono_utils.h
+++ b/modules/mono/mono_gd/gd_mono_utils.h
@@ -41,7 +41,7 @@
#include "core/object.h"
#include "core/reference.h"
-#define UNLIKELY_UNHANDLED_EXCEPTION(m_exc) \
+#define UNHANDLED_EXCEPTION(m_exc) \
if (unlikely(m_exc != NULL)) { \
GDMonoUtils::debug_unhandled_exception(m_exc); \
GD_UNREACHABLE(); \
@@ -78,16 +78,16 @@ typedef void (*GenericIDictionaryToDictionary)(MonoObject *, Dictionary *, MonoE
namespace Marshal {
-MonoBoolean type_is_generic_array(MonoReflectionType *p_reftype);
-MonoBoolean type_is_generic_dictionary(MonoReflectionType *p_reftype);
+bool type_is_generic_array(MonoReflectionType *p_reftype);
+bool type_is_generic_dictionary(MonoReflectionType *p_reftype);
void array_get_element_type(MonoReflectionType *p_array_reftype, MonoReflectionType **r_elem_reftype);
void dictionary_get_key_value_types(MonoReflectionType *p_dict_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype);
-MonoBoolean generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype);
-MonoBoolean generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype);
-MonoBoolean generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_elem_reftype);
-MonoBoolean generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype);
+bool generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype);
+bool generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype);
+bool generic_ienumerable_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_elem_reftype);
+bool generic_idictionary_is_assignable_from(MonoReflectionType *p_reftype, MonoReflectionType **r_key_reftype, MonoReflectionType **r_value_reftype);
GDMonoClass *make_generic_array_type(MonoReflectionType *p_elem_reftype);
GDMonoClass *make_generic_dictionary_type(MonoReflectionType *p_key_reftype, MonoReflectionType *p_value_reftype);
@@ -157,6 +157,7 @@ struct MonoCache {
GDMonoClass *class_Array;
GDMonoClass *class_Dictionary;
GDMonoClass *class_MarshalUtils;
+ GDMonoClass *class_ISerializationListener;
#ifdef DEBUG_ENABLED
GDMonoClass *class_DebuggingUtils;
@@ -218,14 +219,12 @@ struct MonoCache {
bool corlib_cache_updated;
bool godot_api_cache_updated;
- void clear_members();
- void cleanup();
+ void clear_corlib_cache();
+ void clear_godot_api_cache();
MonoCache() {
- corlib_cache_updated = false;
- godot_api_cache_updated = false;
-
- clear_members();
+ clear_corlib_cache();
+ clear_godot_api_cache();
}
};
@@ -233,7 +232,22 @@ extern MonoCache mono_cache;
void update_corlib_cache();
void update_godot_api_cache();
-void clear_cache();
+
+inline void clear_corlib_cache() {
+ mono_cache.clear_corlib_cache();
+}
+
+inline void clear_godot_api_cache() {
+ mono_cache.clear_godot_api_cache();
+}
+
+_FORCE_INLINE_ bool tools_godot_api_check() {
+#ifdef TOOLS_ENABLED
+ return mono_cache.godot_api_cache_updated;
+#else
+ return true; // Assume it's updated if this was called, otherwise it's a bug
+#endif
+}
_FORCE_INLINE_ void hash_combine(uint32_t &p_hash, const uint32_t &p_with_hash) {
p_hash ^= p_with_hash + 0x9e3779b9 + (p_hash << 6) + (p_hash >> 2);
diff --git a/modules/mono/signal_awaiter_utils.cpp b/modules/mono/signal_awaiter_utils.cpp
index 5d37e8212f..54d73c971f 100644
--- a/modules/mono/signal_awaiter_utils.cpp
+++ b/modules/mono/signal_awaiter_utils.cpp
@@ -91,11 +91,11 @@ Variant SignalAwaiterHandle::_signal_callback(const Variant **p_args, int p_argc
set_completed(true);
int signal_argc = p_argcount - 1;
- MonoArray *signal_args = mono_array_new(SCRIPTS_DOMAIN, CACHED_CLASS_RAW(MonoObject), signal_argc);
+ MonoArray *signal_args = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(MonoObject), signal_argc);
for (int i = 0; i < signal_argc; i++) {
MonoObject *boxed = GDMonoMarshal::variant_to_mono_object(*p_args[i]);
- mono_array_set(signal_args, MonoObject *, i, boxed);
+ mono_array_setref(signal_args, i, boxed);
}
MonoException *exc = NULL;
diff --git a/modules/mono/signal_awaiter_utils.h b/modules/mono/signal_awaiter_utils.h
index 098008ded7..4fb3cdb56d 100644
--- a/modules/mono/signal_awaiter_utils.h
+++ b/modules/mono/signal_awaiter_utils.h
@@ -41,7 +41,7 @@ Error connect_signal_awaiter(Object *p_source, const String &p_signal, Object *p
class SignalAwaiterHandle : public MonoGCHandle {
- GDCLASS(SignalAwaiterHandle, MonoGCHandle)
+ GDCLASS(SignalAwaiterHandle, MonoGCHandle);
bool completed;
diff --git a/modules/mono/editor/monodevelop_instance.cpp b/modules/mono/utils/android_utils.cpp
index 3caa56d1d0..7dd67e3b8e 100644
--- a/modules/mono/editor/monodevelop_instance.cpp
+++ b/modules/mono/utils/android_utils.cpp
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* monodevelop_instance.cpp */
+/* android_utils.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,58 +28,41 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "monodevelop_instance.h"
+#include "android_utils.h"
-#include "../mono_gd/gd_mono.h"
-#include "../mono_gd/gd_mono_class.h"
+#ifdef __ANDROID__
-void MonoDevelopInstance::execute(const Vector<String> &p_files) {
+#include "platform/android/thread_jandroid.h"
- _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN)
+namespace GDMonoUtils {
+namespace Android {
- ERR_FAIL_NULL(execute_method);
- ERR_FAIL_COND(gc_handle.is_null());
+String get_app_native_lib_dir() {
+ JNIEnv *env = ThreadAndroid::get_env();
- MonoException *exc = NULL;
+ jclass activityThreadClass = env->FindClass("android/app/ActivityThread");
+ jmethodID currentActivityThread = env->GetStaticMethodID(activityThreadClass, "currentActivityThread", "()Landroid/app/ActivityThread;");
+ jobject activityThread = env->CallStaticObjectMethod(activityThreadClass, currentActivityThread);
+ jmethodID getApplication = env->GetMethodID(activityThreadClass, "getApplication", "()Landroid/app/Application;");
+ jobject ctx = env->CallObjectMethod(activityThread, getApplication);
- Variant files = p_files;
- const Variant *args[1] = { &files };
- execute_method->invoke(gc_handle->get_target(), args, &exc);
+ jmethodID getApplicationInfo = env->GetMethodID(env->GetObjectClass(ctx), "getApplicationInfo", "()Landroid/content/pm/ApplicationInfo;");
+ jobject applicationInfo = env->CallObjectMethod(ctx, getApplicationInfo);
+ jfieldID nativeLibraryDirField = env->GetFieldID(env->GetObjectClass(applicationInfo), "nativeLibraryDir", "Ljava/lang/String;");
+ jstring nativeLibraryDir = (jstring)env->GetObjectField(applicationInfo, nativeLibraryDirField);
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- ERR_FAIL();
- }
-}
+ String result;
-void MonoDevelopInstance::execute(const String &p_file) {
+ const char *const nativeLibraryDir_utf8 = env->GetStringUTFChars(nativeLibraryDir, NULL);
+ if (nativeLibraryDir_utf8) {
+ result.parse_utf8(nativeLibraryDir_utf8);
+ env->ReleaseStringUTFChars(nativeLibraryDir, nativeLibraryDir_utf8);
+ }
- Vector<String> files;
- files.push_back(p_file);
- execute(files);
+ return result;
}
-MonoDevelopInstance::MonoDevelopInstance(const String &p_solution, EditorId p_editor_id) {
-
- _GDMONO_SCOPE_DOMAIN_(TOOLS_DOMAIN)
-
- GDMonoClass *klass = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Editor", "MonoDevelopInstance");
-
- MonoObject *obj = mono_object_new(TOOLS_DOMAIN, klass->get_mono_ptr());
+} // namespace Android
+} // namespace GDMonoUtils
- GDMonoMethod *ctor = klass->get_method(".ctor", 2);
- MonoException *exc = NULL;
-
- Variant solution = p_solution;
- Variant editor_id = p_editor_id;
- const Variant *args[2] = { &solution, &editor_id };
- ctor->invoke(obj, args, &exc);
-
- if (exc) {
- GDMonoUtils::debug_print_unhandled_exception(exc);
- ERR_FAIL();
- }
-
- gc_handle = MonoGCHandle::create_strong(obj);
- execute_method = klass->get_method("Execute", 1);
-}
+#endif // __ANDROID__
diff --git a/modules/mono/editor/mono_build_info.h b/modules/mono/utils/android_utils.h
index b0ae2ed52e..f911c3fdfe 100644
--- a/modules/mono/editor/mono_build_info.h
+++ b/modules/mono/utils/android_utils.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* mono_build_info.h */
+/* android_utils.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,28 +28,21 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef MONO_BUILD_INFO_H
-#define MONO_BUILD_INFO_H
+#ifndef ANDROID_UTILS_H
+#define ANDROID_UTILS_H
-#include "core/ustring.h"
-#include "core/vector.h"
-
-struct MonoBuildInfo {
+#ifdef __ANDROID__
- struct Hasher {
- static uint32_t hash(const MonoBuildInfo &p_key);
- };
+#include "core/ustring.h"
- String solution;
- String configuration;
- Vector<String> custom_props;
+namespace GDMonoUtils {
+namespace Android {
- bool operator==(const MonoBuildInfo &p_b) const;
+String get_app_native_lib_dir();
- String get_log_dirpath();
+} // namespace Android
+} // namespace GDMonoUtils
- MonoBuildInfo();
- MonoBuildInfo(const String &p_solution, const String &p_config);
-};
+#endif // __ANDROID__
-#endif // MONO_BUILD_INFO_H
+#endif // ANDROID_UTILS_H
diff --git a/modules/mono/utils/path_utils.cpp b/modules/mono/utils/path_utils.cpp
index 6e431f51e7..20863b1afe 100644
--- a/modules/mono/utils/path_utils.cpp
+++ b/modules/mono/utils/path_utils.cpp
@@ -36,16 +36,21 @@
#include "core/project_settings.h"
#ifdef WINDOWS_ENABLED
+#include <windows.h>
+
#define ENV_PATH_SEP ";"
#else
-#define ENV_PATH_SEP ":"
#include <limits.h>
+#include <unistd.h>
+
+#define ENV_PATH_SEP ":"
#endif
#include <stdlib.h>
-String path_which(const String &p_name) {
+namespace path {
+String find_executable(const String &p_name) {
#ifdef WINDOWS_ENABLED
Vector<String> exts = OS::get_singleton()->get_environment("PATHEXT").split(ENV_PATH_SEP, false);
#endif
@@ -55,7 +60,7 @@ String path_which(const String &p_name) {
return String();
for (int i = 0; i < env_path.size(); i++) {
- String p = path_join(env_path[i], p_name);
+ String p = path::join(env_path[i], p_name);
#ifdef WINDOWS_ENABLED
for (int j = 0; j < exts.size(); j++) {
@@ -73,42 +78,96 @@ String path_which(const String &p_name) {
return String();
}
-void fix_path(const String &p_path, String &r_out) {
- r_out = p_path.replace("\\", "/");
+String cwd() {
+#ifdef WINDOWS_ENABLED
+ const DWORD expected_size = ::GetCurrentDirectoryW(0, NULL);
+
+ String buffer;
+ buffer.resize((int)expected_size);
+ if (::GetCurrentDirectoryW(expected_size, buffer.ptrw()) == 0)
+ return ".";
+
+ return buffer.simplify_path();
+#else
+ char buffer[PATH_MAX];
+ if (::getcwd(buffer, sizeof(buffer)) == NULL)
+ return ".";
+
+ String result;
+ if (result.parse_utf8(buffer))
+ return ".";
- while (true) { // in case of using 2 or more slash
- String compare = r_out.replace("//", "/");
- if (r_out == compare)
- break;
- else
- r_out = compare;
+ return result.simplify_path();
+#endif
+}
+
+String abspath(const String &p_path) {
+ if (p_path.is_abs_path()) {
+ return p_path.simplify_path();
+ } else {
+ return path::join(path::cwd(), p_path).simplify_path();
}
}
-bool rel_path_to_abs(const String &p_existing_path, String &r_abs_path) {
+String realpath(const String &p_path) {
#ifdef WINDOWS_ENABLED
- CharType ret[_MAX_PATH];
- if (::_wfullpath(ret, p_existing_path.c_str(), _MAX_PATH)) {
- String abspath = String(ret).replace("\\", "/");
- int pos = abspath.find(":/");
- if (pos != -1) {
- r_abs_path = abspath.substr(pos - 1, abspath.length());
- } else {
- r_abs_path = abspath;
- }
- return true;
- }
-#else
- char *resolved_path = ::realpath(p_existing_path.utf8().get_data(), NULL);
- if (resolved_path) {
- String retstr;
- bool success = !retstr.parse_utf8(resolved_path);
- ::free(resolved_path);
- if (success) {
- r_abs_path = retstr;
- return true;
- }
+ // Open file without read/write access
+ HANDLE hFile = ::CreateFileW(p_path.c_str(), 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+
+ if (hFile == INVALID_HANDLE_VALUE)
+ return p_path;
+
+ const DWORD expected_size = ::GetFinalPathNameByHandleW(hFile, NULL, 0, FILE_NAME_NORMALIZED);
+
+ if (expected_size == 0) {
+ ::CloseHandle(hFile);
+ return p_path;
}
+
+ String buffer;
+ buffer.resize((int)expected_size);
+ ::GetFinalPathNameByHandleW(hFile, buffer.ptrw(), expected_size, FILE_NAME_NORMALIZED);
+
+ ::CloseHandle(hFile);
+ return buffer.simplify_path();
+#elif UNIX_ENABLED
+ char *resolved_path = ::realpath(p_path.utf8().get_data(), NULL);
+
+ if (!resolved_path)
+ return p_path;
+
+ String result;
+ bool parse_ok = result.parse_utf8(resolved_path);
+ ::free(resolved_path);
+
+ if (parse_ok)
+ return p_path;
+
+ return result.simplify_path();
#endif
- return false;
}
+
+String join(const String &p_a, const String &p_b) {
+ if (p_a.empty())
+ return p_b;
+
+ const CharType a_last = p_a[p_a.length() - 1];
+ if ((a_last == '/' || a_last == '\\') ||
+ (p_b.size() > 0 && (p_b[0] == '/' || p_b[0] == '\\'))) {
+ return p_a + p_b;
+ }
+
+ return p_a + "/" + p_b;
+}
+
+String join(const String &p_a, const String &p_b, const String &p_c) {
+ return path::join(path::join(p_a, p_b), p_c);
+}
+
+String join(const String &p_a, const String &p_b, const String &p_c, const String &p_d) {
+ return path::join(path::join(path::join(p_a, p_b), p_c), p_d);
+}
+
+} // namespace path
diff --git a/modules/mono/utils/path_utils.h b/modules/mono/utils/path_utils.h
index 69edf4deb7..ca25bc09f7 100644
--- a/modules/mono/utils/path_utils.h
+++ b/modules/mono/utils/path_utils.h
@@ -31,24 +31,32 @@
#ifndef PATH_UTILS_H
#define PATH_UTILS_H
+#include "core/string_builder.h"
#include "core/ustring.h"
-_FORCE_INLINE_ String path_join(const String &e1, const String &e2) {
- return e1.plus_file(e2);
-}
+namespace path {
-_FORCE_INLINE_ String path_join(const String &e1, const String &e2, const String &e3) {
- return e1.plus_file(e2).plus_file(e3);
-}
+String join(const String &p_a, const String &p_b);
+String join(const String &p_a, const String &p_b, const String &p_c);
+String join(const String &p_a, const String &p_b, const String &p_c, const String &p_d);
-_FORCE_INLINE_ String path_join(const String &e1, const String &e2, const String &e3, const String &e4) {
- return e1.plus_file(e2).plus_file(e3).plus_file(e4);
-}
+String find_executable(const String &p_name);
-String path_which(const String &p_name);
+/// Returns a normalized absolute path to the current working directory
+String cwd();
-void fix_path(const String &p_path, String &r_out);
+/**
+ * Obtains a normalized absolute path to p_path. Symbolic links are
+ * not resolved. The path p_path might not exist in the file system.
+ */
+String abspath(const String &p_path);
-bool rel_path_to_abs(const String &p_existing_path, String &r_abs_path);
+/**
+ * Obtains a normalized path to p_path with symbolic links resolved.
+ * The resulting path might be either a relative or an absolute path.
+ */
+String realpath(const String &p_path);
+
+} // namespace path
#endif // PATH_UTILS_H
diff --git a/modules/mono/utils/string_utils.cpp b/modules/mono/utils/string_utils.cpp
index 877122985d..2b014c2a45 100644
--- a/modules/mono/utils/string_utils.cpp
+++ b/modules/mono/utils/string_utils.cpp
@@ -44,7 +44,7 @@ int sfind(const String &p_text, int p_from) {
int src_len = 2;
int len = p_text.length();
- if (src_len == 0 || len == 0)
+ if (len == 0)
return -1;
const CharType *src = p_text.c_str();
diff --git a/modules/mono/utils/thread_local.h b/modules/mono/utils/thread_local.h
index 488cc2619a..e52b6e73ef 100644
--- a/modules/mono/utils/thread_local.h
+++ b/modules/mono/utils/thread_local.h
@@ -76,7 +76,7 @@ struct ThreadLocalStorage {
void *get_value() const;
void set_value(void *p_value) const;
- void alloc(void(_CALLBACK_FUNC_ *p_dest_callback)(void *));
+ void alloc(void(_CALLBACK_FUNC_ *p_destr_callback)(void *));
void free();
private:
diff --git a/modules/opensimplex/doc_classes/NoiseTexture.xml b/modules/opensimplex/doc_classes/NoiseTexture.xml
index c789724fc4..4b59a380f5 100644
--- a/modules/opensimplex/doc_classes/NoiseTexture.xml
+++ b/modules/opensimplex/doc_classes/NoiseTexture.xml
@@ -12,21 +12,21 @@
<methods>
</methods>
<members>
- <member name="as_normalmap" type="bool" setter="set_as_normalmap" getter="is_normalmap">
+ <member name="as_normalmap" type="bool" setter="set_as_normalmap" getter="is_normalmap" default="false">
If [code]true[/code], the resulting texture contains a normal map created from the original noise interpreted as a bump map.
</member>
- <member name="bump_strength" type="float" setter="set_bump_strength" getter="get_bump_strength">
+ <member name="bump_strength" type="float" setter="set_bump_strength" getter="get_bump_strength" default="8.0">
</member>
- <member name="height" type="int" setter="set_height" getter="get_height">
+ <member name="height" type="int" setter="set_height" getter="get_height" default="512">
Height of the generated texture.
</member>
<member name="noise" type="OpenSimplexNoise" setter="set_noise" getter="get_noise">
The [OpenSimplexNoise] instance used to generate the noise.
</member>
- <member name="seamless" type="bool" setter="set_seamless" getter="get_seamless">
+ <member name="seamless" type="bool" setter="set_seamless" getter="get_seamless" default="false">
Whether the texture can be tiled without visible seams or not. Seamless textures take longer to generate.
</member>
- <member name="width" type="int" setter="set_width" getter="get_width">
+ <member name="width" type="int" setter="set_width" getter="get_width" default="512">
Width of the generated texture.
</member>
</members>
diff --git a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml
index dc7fc7fe31..f3fbbab3da 100644
--- a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml
+++ b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml
@@ -41,6 +41,8 @@
<argument index="0" name="x" type="float">
</argument>
<description>
+ Returns the 1D noise value [code][-1,1][/code] at the given x-coordinate.
+ [b]Note:[/b] This method actually returns the 2D noise value [code][-1,1][/code] with fixed y-coordinate value 0.0.
</description>
</method>
<method name="get_noise_2d">
@@ -106,24 +108,24 @@
<argument index="0" name="size" type="int">
</argument>
<description>
- Generate a tileable noise image, based on the current noise parameters. Generated seamless images are always square ([code]size[/code] x [code]size[/code]).
+ Generate a tileable noise image, based on the current noise parameters. Generated seamless images are always square ([code]size[/code] × [code]size[/code]).
</description>
</method>
</methods>
<members>
- <member name="lacunarity" type="float" setter="set_lacunarity" getter="get_lacunarity">
+ <member name="lacunarity" type="float" setter="set_lacunarity" getter="get_lacunarity" default="2.0">
Difference in period between [member octaves].
</member>
- <member name="octaves" type="int" setter="set_octaves" getter="get_octaves">
+ <member name="octaves" type="int" setter="set_octaves" getter="get_octaves" default="3">
Number of OpenSimplex noise layers that are sampled to get the fractal noise.
</member>
- <member name="period" type="float" setter="set_period" getter="get_period">
+ <member name="period" type="float" setter="set_period" getter="get_period" default="64.0">
Period of the base octave. A lower period results in a higher-frequency noise (more value changes across the same distance).
</member>
- <member name="persistence" type="float" setter="set_persistence" getter="get_persistence">
+ <member name="persistence" type="float" setter="set_persistence" getter="get_persistence" default="0.5">
Contribution factor of the different octaves. A [code]persistence[/code] value of 1 means all the octaves have the same contribution, a value of 0.5 means each octave contributes half as much as the previous one.
</member>
- <member name="seed" type="int" setter="set_seed" getter="get_seed">
+ <member name="seed" type="int" setter="set_seed" getter="get_seed" default="0">
Seed used to generate random values, different seeds will generate different noise maps.
</member>
</members>
diff --git a/modules/opensimplex/icons/icon_noise_texture.svg b/modules/opensimplex/icons/icon_noise_texture.svg
new file mode 100644
index 0000000000..5908c2b2d4
--- /dev/null
+++ b/modules/opensimplex/icons/icon_noise_texture.svg
@@ -0,0 +1,3 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<path d="m2 1c-0.55228 0-1 0.44772-1 1v12c0 0.55228 0.44772 1 1 1h12c0.55228 0 1-0.44772 1-1v-12c0-0.55228-0.44772-1-1-1zm1 2h10v8h-10zm3 1v2h2v-2zm2 2v2h2v2h2v-6h-2v2zm0 2h-2v-2h-2v4h4z" fill="#e0e0e0" fill-opacity=".99608"/>
+</svg>
diff --git a/modules/opensimplex/noise_texture.h b/modules/opensimplex/noise_texture.h
index 0d00ee154d..5e4a02fcee 100644
--- a/modules/opensimplex/noise_texture.h
+++ b/modules/opensimplex/noise_texture.h
@@ -40,7 +40,7 @@
#include "editor/property_editor.h"
class NoiseTexture : public Texture {
- GDCLASS(NoiseTexture, Texture)
+ GDCLASS(NoiseTexture, Texture);
private:
Ref<Image> data;
@@ -77,12 +77,12 @@ public:
Ref<OpenSimplexNoise> get_noise();
void set_width(int p_width);
- void set_height(int p_hieght);
+ void set_height(int p_height);
void set_seamless(bool p_seamless);
bool get_seamless();
- void set_as_normalmap(bool p_seamless);
+ void set_as_normalmap(bool p_as_normalmap);
bool is_normalmap();
void set_bump_strength(float p_bump_strength);
diff --git a/modules/opensimplex/open_simplex_noise.h b/modules/opensimplex/open_simplex_noise.h
index 96885f5893..c31cbf68c3 100644
--- a/modules/opensimplex/open_simplex_noise.h
+++ b/modules/opensimplex/open_simplex_noise.h
@@ -38,7 +38,7 @@
#include "thirdparty/misc/open-simplex-noise.h"
class OpenSimplexNoise : public Resource {
- GDCLASS(OpenSimplexNoise, Resource)
+ GDCLASS(OpenSimplexNoise, Resource);
OBJ_SAVE_TYPE(OpenSimplexNoise);
osn_context contexts[6];
diff --git a/modules/opus/SCsub b/modules/opus/SCsub
index f3c981dd45..1db5b0987e 100644
--- a/modules/opus/SCsub
+++ b/modules/opus/SCsub
@@ -139,7 +139,7 @@ if env['builtin_opus']:
opus_sources_silk = []
if env["platform"] in ["android", "iphone", "javascript"]:
- env_opus.Append(CPPFLAGS=["-DFIXED_POINT"])
+ env_opus.Append(CPPDEFINES=["FIXED_POINT"])
opus_sources_silk = [
"silk/fixed/LTP_analysis_filter_FIX.c",
"silk/fixed/LTP_scale_ctrl_FIX.c",
@@ -208,7 +208,7 @@ if env['builtin_opus']:
if env['builtin_libogg']:
env_opus.Prepend(CPPPATH=["#thirdparty/libogg"])
- env_opus.Append(CPPFLAGS=["-DHAVE_CONFIG_H"])
+ env_opus.Append(CPPDEFINES=["HAVE_CONFIG_H"])
thirdparty_include_paths = [
"",
@@ -221,15 +221,15 @@ if env['builtin_opus']:
env_opus.Prepend(CPPPATH=[thirdparty_dir + "/" + dir for dir in thirdparty_include_paths])
if env["platform"] == "android":
- if ("android_arch" in env and env["android_arch"] in ["armv6", "armv7"]):
- env_opus.Append(CPPFLAGS=["-DOPUS_ARM_OPT"])
+ if ("android_arch" in env and env["android_arch"] == "armv7"):
+ env_opus.Append(CPPDEFINES=["OPUS_ARM_OPT"])
elif ("android_arch" in env and env["android_arch"] == "arm64v8"):
- env_opus.Append(CPPFLAGS=["-DOPUS_ARM64_OPT"])
+ env_opus.Append(CPPDEFINES=["OPUS_ARM64_OPT"])
elif env["platform"] == "iphone":
if ("arch" in env and env["arch"] == "arm"):
- env_opus.Append(CPPFLAGS=["-DOPUS_ARM_OPT"])
+ env_opus.Append(CPPDEFINES=["OPUS_ARM_OPT"])
elif ("arch" in env and env["arch"] == "arm64"):
- env_opus.Append(CPPFLAGS=["-DOPUS_ARM64_OPT"])
+ env_opus.Append(CPPDEFINES=["OPUS_ARM64_OPT"])
env_thirdparty = env_opus.Clone()
env_thirdparty.disable_warnings()
diff --git a/modules/opus/audio_stream_opus.cpp b/modules/opus/audio_stream_opus.cpp
index fda82295de..615081d818 100644
--- a/modules/opus/audio_stream_opus.cpp
+++ b/modules/opus/audio_stream_opus.cpp
@@ -280,7 +280,7 @@ int AudioStreamPlaybackOpus::mix(int16_t *p_buffer, int p_frames) {
int todo = p_frames;
- if (todo == 0 || todo < MIN_MIX) {
+ if (todo < MIN_MIX) {
break;
}
@@ -313,7 +313,7 @@ int AudioStreamPlaybackOpus::mix(int16_t *p_buffer, int p_frames) {
bool ok = op_pcm_seek(opus_file, (loop_restart_time * osrate) + pre_skip) == 0;
if (!ok) {
playing = false;
- ERR_PRINT("loop restart time rejected")
+ ERR_PRINT("Loop restart time rejected");
}
frames_mixed = (loop_restart_time * osrate) + pre_skip;
diff --git a/modules/opus/audio_stream_opus.h b/modules/opus/audio_stream_opus.h
index f53bff0288..04c2e9d9f0 100644
--- a/modules/opus/audio_stream_opus.h
+++ b/modules/opus/audio_stream_opus.h
@@ -43,7 +43,7 @@
class AudioStreamPlaybackOpus : public AudioStreamPlayback {
- GDCLASS(AudioStreamPlaybackOpus, AudioStreamPlayback)
+ GDCLASS(AudioStreamPlaybackOpus, AudioStreamPlayback);
enum {
MIN_MIX = 1024
@@ -117,7 +117,7 @@ public:
class AudioStreamOpus : public AudioStream {
- GDCLASS(AudioStreamOpus, AudioStream)
+ GDCLASS(AudioStreamOpus, AudioStream);
String file;
@@ -132,7 +132,6 @@ public:
};
class ResourceFormatLoaderAudioStreamOpus : public ResourceFormatLoader {
- GDCLASS(ResourceFormatLoaderAudioStreamOpus, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/pvr/texture_loader_pvr.cpp b/modules/pvr/texture_loader_pvr.cpp
index 8f6ffcc83f..8b1f21d95d 100644
--- a/modules/pvr/texture_loader_pvr.cpp
+++ b/modules/pvr/texture_loader_pvr.cpp
@@ -153,7 +153,7 @@ RES ResourceFormatPVR::load(const String &p_path, const String &p_original_path,
ERR_FAIL_V(RES());
}
- w = PoolVector<uint8_t>::Write();
+ w.release();
int tex_flags = Texture::FLAG_FILTER | Texture::FLAG_REPEAT;
@@ -655,8 +655,8 @@ static void _pvrtc_decompress(Image *p_img) {
decompress_pvrtc((PVRTCBlock *)r.ptr(), _2bit, p_img->get_width(), p_img->get_height(), 0, (unsigned char *)w.ptr());
- w = PoolVector<uint8_t>::Write();
- r = PoolVector<uint8_t>::Read();
+ w.release();
+ r.release();
bool make_mipmaps = p_img->has_mipmaps();
p_img->create(p_img->get_width(), p_img->get_height(), false, Image::FORMAT_RGBA8, newdata);
diff --git a/modules/pvr/texture_loader_pvr.h b/modules/pvr/texture_loader_pvr.h
index 2808b4ff03..606268e447 100644
--- a/modules/pvr/texture_loader_pvr.h
+++ b/modules/pvr/texture_loader_pvr.h
@@ -35,7 +35,6 @@
#include "scene/resources/texture.h"
class ResourceFormatPVR : public ResourceFormatLoader {
- GDCLASS(ResourceFormatPVR, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path, Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/recast/navigation_mesh_editor_plugin.cpp b/modules/recast/navigation_mesh_editor_plugin.cpp
index eadc11fcee..9f30806925 100644
--- a/modules/recast/navigation_mesh_editor_plugin.cpp
+++ b/modules/recast/navigation_mesh_editor_plugin.cpp
@@ -67,9 +67,7 @@ void NavigationMeshEditor::_bake_pressed() {
EditorNavigationMeshGenerator::get_singleton()->clear(node->get_navigation_mesh());
EditorNavigationMeshGenerator::get_singleton()->bake(node->get_navigation_mesh(), node);
- if (node) {
- node->update_gizmo();
- }
+ node->update_gizmo();
}
void NavigationMeshEditor::_clear_pressed() {
diff --git a/modules/recast/navigation_mesh_generator.cpp b/modules/recast/navigation_mesh_generator.cpp
index 0cac07e3e7..14467dc5c7 100644
--- a/modules/recast/navigation_mesh_generator.cpp
+++ b/modules/recast/navigation_mesh_generator.cpp
@@ -45,6 +45,10 @@
#include "scene/resources/shape.h"
#include "scene/resources/sphere_shape.h"
+#ifdef MODULE_CSG_ENABLED
+#include "modules/csg/csg_shape.h"
+#endif
+
EditorNavigationMeshGenerator *EditorNavigationMeshGenerator::singleton = NULL;
void EditorNavigationMeshGenerator::_add_vertex(const Vector3 &p_vec3, Vector<float> &p_verticies) {
@@ -134,6 +138,20 @@ void EditorNavigationMeshGenerator::_parse_geometry(Transform p_accumulated_tran
}
}
+#ifdef MODULE_CSG_ENABLED
+ if (Object::cast_to<CSGShape>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
+
+ CSGShape *csg_shape = Object::cast_to<CSGShape>(p_node);
+ Array meshes = csg_shape->get_meshes();
+ if (!meshes.empty()) {
+ Ref<Mesh> mesh = meshes[1];
+ if (mesh.is_valid()) {
+ _add_mesh(mesh, p_accumulated_transform * csg_shape->get_transform(), p_verticies, p_indices);
+ }
+ }
+ }
+#endif
+
if (Object::cast_to<StaticBody>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES) {
StaticBody *static_body = Object::cast_to<StaticBody>(p_node);
diff --git a/modules/recast/register_types.cpp b/modules/recast/register_types.cpp
index 247d7f6144..44129fbb61 100644
--- a/modules/recast/register_types.cpp
+++ b/modules/recast/register_types.cpp
@@ -40,7 +40,14 @@ void register_recast_types() {
#ifdef TOOLS_ENABLED
EditorPlugins::add_by_type<NavigationMeshEditorPlugin>();
_nav_mesh_generator = memnew(EditorNavigationMeshGenerator);
+
+ ClassDB::APIType prev_api = ClassDB::get_current_api();
+ ClassDB::set_current_api(ClassDB::API_EDITOR);
+
ClassDB::register_class<EditorNavigationMeshGenerator>();
+
+ ClassDB::set_current_api(prev_api);
+
Engine::get_singleton()->add_singleton(Engine::Singleton("NavigationMeshGenerator", EditorNavigationMeshGenerator::get_singleton()));
#endif
}
diff --git a/modules/regex/SCsub b/modules/regex/SCsub
index 65f354ffa7..1be5af02a5 100644
--- a/modules/regex/SCsub
+++ b/modules/regex/SCsub
@@ -9,10 +9,10 @@ if env['builtin_pcre2']:
jit_blacklist = ['javascript', 'uwp']
thirdparty_dir = '#thirdparty/pcre2/src/'
- thirdparty_flags = ['-DPCRE2_STATIC', '-DHAVE_CONFIG_H']
+ thirdparty_flags = ['PCRE2_STATIC', 'HAVE_CONFIG_H']
if 'platform' in env and env['platform'] not in jit_blacklist:
- thirdparty_flags.append('-DSUPPORT_JIT')
+ thirdparty_flags.append('SUPPORT_JIT')
thirdparty_sources = [
"pcre2_auto_possess.c",
@@ -33,6 +33,7 @@ if env['builtin_pcre2']:
"pcre2_newline.c",
"pcre2_ord2utf.c",
"pcre2_pattern_info.c",
+ "pcre2_script_run.c",
"pcre2_serialize.c",
"pcre2_string_utils.c",
"pcre2_study.c",
@@ -47,17 +48,17 @@ if env['builtin_pcre2']:
thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
env_regex.Prepend(CPPPATH=[thirdparty_dir])
- env_regex.Append(CPPFLAGS=thirdparty_flags)
+ env_regex.Append(CPPDEFINES=thirdparty_flags)
def pcre2_builtin(width):
env_pcre2 = env_regex.Clone()
env_pcre2.disable_warnings()
env_pcre2["OBJSUFFIX"] = "_" + width + env_pcre2["OBJSUFFIX"]
env_pcre2.add_source_files(env.modules_sources, thirdparty_sources)
- env_pcre2.Append(CPPFLAGS=["-DPCRE2_CODE_UNIT_WIDTH=" + width])
+ env_pcre2.Append(CPPDEFINES=[("PCRE2_CODE_UNIT_WIDTH", width)])
pcre2_builtin("16")
pcre2_builtin("32")
-env_regex.Append(CPPFLAGS=["-DPCRE2_CODE_UNIT_WIDTH=0"])
+env_regex.Append(CPPDEFINES=[("PCRE2_CODE_UNIT_WIDTH", 0)])
env_regex.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/regex/doc_classes/RegEx.xml b/modules/regex/doc_classes/RegEx.xml
index cc8205e400..74b06039d4 100644
--- a/modules/regex/doc_classes/RegEx.xml
+++ b/modules/regex/doc_classes/RegEx.xml
@@ -4,7 +4,7 @@
Class for searching text for patterns using regular expressions.
</brief_description>
<description>
- Regular Expression (or regex) is a compact programming language that can be used to recognise strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For instance, a regex of [code]ab[0-9][/code] would find any string that is [code]ab[/code] followed by any number from [code]0[/code] to [code]9[/code]. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet.
+ A regular expression (or regex) is a compact language that can be used to recognise strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For instance, a regex of [code]ab[0-9][/code] would find any string that is [code]ab[/code] followed by any number from [code]0[/code] to [code]9[/code]. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet.
To begin, the RegEx object needs to be compiled with the search pattern using [method compile] before it can be used.
[codeblock]
var regex = RegEx.new()
@@ -19,7 +19,7 @@
if result:
print(result.get_string()) # Would print n-0123
[/codeblock]
- The results of capturing groups [code]()[/code] can be retrieved by passing the group number to the various functions in [RegExMatch]. Group 0 is the default and would always refer to the entire pattern. In the above example, calling [code]result.get_string(1)[/code] would give you [code]0123[/code].
+ The results of capturing groups [code]()[/code] can be retrieved by passing the group number to the various functions in [RegExMatch]. Group 0 is the default and will always refer to the entire pattern. In the above example, calling [code]result.get_string(1)[/code] would give you [code]0123[/code].
This version of RegEx also supports named capturing groups, and the names can be used to retrieve the results. If two or more groups have the same name, the name would only refer to the first one with a match.
[codeblock]
var regex = RegEx.new()
@@ -28,7 +28,7 @@
if result:
print(result.get_string("digit")) # Would print 2f
[/codeblock]
- If you need to process multiple results, [method search_all] generates a list of all non-overlapping results. This can be combined with a for-loop for convenience.
+ If you need to process multiple results, [method search_all] generates a list of all non-overlapping results. This can be combined with a [code]for[/code] loop for convenience.
[codeblock]
for result in regex.search_all("d01, d03, d0c, x3f and x42"):
print(result.get_string("digit"))
@@ -43,7 +43,7 @@
<return type="void">
</return>
<description>
- This method resets the state of the object, as it was freshly created. Namely, it unassigns the regular expression of this object.
+ This method resets the state of the object, as if it was freshly created. Namely, it unassigns the regular expression of this object.
</description>
</method>
<method name="compile">
@@ -52,7 +52,7 @@
<argument index="0" name="pattern" type="String">
</argument>
<description>
- Compiles and assign the search pattern to use. Returns OK if the compilation is successful. If an error is encountered the details are printed to STDOUT and FAILED is returned.
+ Compiles and assign the search pattern to use. Returns [constant OK] if the compilation is successful. If an error is encountered, details are printed to standard output and an error is returned.
</description>
</method>
<method name="get_group_count" qualifiers="const">
@@ -93,7 +93,7 @@
<argument index="2" name="end" type="int" default="-1">
</argument>
<description>
- Searches the text for the compiled pattern. Returns a [RegExMatch] container of the first matching result if found, otherwise null. The region to search within can be specified without modifying where the start and end anchor would be.
+ Searches the text for the compiled pattern. Returns a [RegExMatch] container of the first matching result if found, otherwise [code]null[/code]. The region to search within can be specified without modifying where the start and end anchor would be.
</description>
</method>
<method name="search_all" qualifiers="const">
@@ -106,7 +106,7 @@
<argument index="2" name="end" type="int" default="-1">
</argument>
<description>
- Searches the text for the compiled pattern. Returns an array of [RegExMatch] containers for each non-overlapping result. If no results were found an empty array is returned instead. The region to search within can be specified without modifying where the start and end anchor would be.
+ Searches the text for the compiled pattern. Returns an array of [RegExMatch] containers for each non-overlapping result. If no results were found, an empty array is returned instead. The region to search within can be specified without modifying where the start and end anchor would be.
</description>
</method>
<method name="sub" qualifiers="const">
@@ -123,7 +123,7 @@
<argument index="4" name="end" type="int" default="-1">
</argument>
<description>
- Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as [code]$1[/code] and [code]$name[/code] are expanded and resolved. By default only the first instance is replaced but it can be changed for all instances (global replacement). The region to search within can be specified without modifying where the start and end anchor would be.
+ Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as [code]$1[/code] and [code]$name[/code] are expanded and resolved. By default, only the first instance is replaced, but it can be changed for all instances (global replacement). The region to search within can be specified without modifying where the start and end anchor would be.
</description>
</method>
</methods>
diff --git a/modules/regex/doc_classes/RegExMatch.xml b/modules/regex/doc_classes/RegExMatch.xml
index 245201006d..6dec9fc516 100644
--- a/modules/regex/doc_classes/RegExMatch.xml
+++ b/modules/regex/doc_classes/RegExMatch.xml
@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="RegExMatch" inherits="Reference" category="Core" version="3.2">
<brief_description>
- Contains the results of a regex search.
+ Contains the results of a [RegEx] search.
</brief_description>
<description>
- Contains the results of a single regex match returned by [method RegEx.search] and [method RegEx.search_all]. It can be used to find the position and range of the match and its capturing groups, and it can extract its sub-string for you.
+ Contains the results of a single [RegEx] match returned by [method RegEx.search] and [method RegEx.search_all]. It can be used to find the position and range of the match and its capturing groups, and it can extract its substring for you.
</description>
<tutorials>
</tutorials>
@@ -48,13 +48,13 @@
</method>
</methods>
<members>
- <member name="names" type="Dictionary" setter="" getter="get_names">
+ <member name="names" type="Dictionary" setter="" getter="get_names" default="{}">
A dictionary of named groups and its corresponding group number. Only groups with that were matched are included. If multiple groups have the same name, that name would refer to the first matching one.
</member>
- <member name="strings" type="Array" setter="" getter="get_strings">
+ <member name="strings" type="Array" setter="" getter="get_strings" default="[ ]">
An [Array] of the match and its capturing groups.
</member>
- <member name="subject" type="String" setter="" getter="get_subject">
+ <member name="subject" type="String" setter="" getter="get_subject" default="&quot;&quot;">
The source string used with the search pattern to find this matching result.
</member>
</members>
diff --git a/modules/squish/image_compress_squish.cpp b/modules/squish/image_compress_squish.cpp
index 4f38357aa1..64f4c169cb 100644
--- a/modules/squish/image_compress_squish.cpp
+++ b/modules/squish/image_compress_squish.cpp
@@ -198,8 +198,8 @@ void image_compress_squish(Image *p_image, float p_lossy_quality, Image::Compres
h = MAX(h / 2, 1);
}
- rb = PoolVector<uint8_t>::Read();
- wb = PoolVector<uint8_t>::Write();
+ rb.release();
+ wb.release();
p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data);
}
diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
index 292ac5e97e..0922471500 100644
--- a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
+++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
@@ -188,7 +188,7 @@ void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t> &p_data) {
ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar.ptr(), src_data_len, &error, &ogg_alloc);
if (!ogg_stream && error == VORBIS_outofmem) {
- w = PoolVector<char>::Write();
+ w.release();
alloc_try *= 2;
} else {
@@ -273,6 +273,7 @@ void AudioStreamOGGVorbis::_bind_methods() {
AudioStreamOGGVorbis::AudioStreamOGGVorbis() {
data = NULL;
+ data_len = 0;
length = 0;
sample_rate = 1;
channels = 1;
diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.h b/modules/stb_vorbis/audio_stream_ogg_vorbis.h
index cbff9d47bb..c8c179554a 100644
--- a/modules/stb_vorbis/audio_stream_ogg_vorbis.h
+++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.h
@@ -40,7 +40,7 @@ class AudioStreamOGGVorbis;
class AudioStreamPlaybackOGGVorbis : public AudioStreamPlaybackResampled {
- GDCLASS(AudioStreamPlaybackOGGVorbis, AudioStreamPlaybackResampled)
+ GDCLASS(AudioStreamPlaybackOGGVorbis, AudioStreamPlaybackResampled);
stb_vorbis *ogg_stream;
stb_vorbis_alloc ogg_alloc;
@@ -72,7 +72,7 @@ public:
class AudioStreamOGGVorbis : public AudioStream {
- GDCLASS(AudioStreamOGGVorbis, AudioStream)
+ GDCLASS(AudioStreamOGGVorbis, AudioStream);
OBJ_SAVE_TYPE(AudioStream) //children are all saved as AudioStream, so they can be exchanged
RES_BASE_EXTENSION("oggstr");
diff --git a/modules/stb_vorbis/config.py b/modules/stb_vorbis/config.py
index d75e41797a..200b8dfd50 100644
--- a/modules/stb_vorbis/config.py
+++ b/modules/stb_vorbis/config.py
@@ -7,7 +7,6 @@ def configure(env):
def get_doc_classes():
return [
"AudioStreamOGGVorbis",
- "ResourceImporterOGGVorbis",
]
def get_doc_path():
diff --git a/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml b/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml
index 388c5e81ed..9403199398 100644
--- a/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml
+++ b/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml
@@ -11,12 +11,12 @@
<methods>
</methods>
<members>
- <member name="data" type="PoolByteArray" setter="set_data" getter="get_data">
+ <member name="data" type="PoolByteArray" setter="set_data" getter="get_data" default="PoolByteArray( )">
Contains the audio data in bytes.
</member>
- <member name="loop" type="bool" setter="set_loop" getter="has_loop">
+ <member name="loop" type="bool" setter="set_loop" getter="has_loop" default="false">
</member>
- <member name="loop_offset" type="float" setter="set_loop_offset" getter="get_loop_offset">
+ <member name="loop_offset" type="float" setter="set_loop_offset" getter="get_loop_offset" default="0.0">
</member>
</members>
<constants>
diff --git a/modules/stb_vorbis/register_types.cpp b/modules/stb_vorbis/register_types.cpp
index 88a1766e47..ce64626e4b 100644
--- a/modules/stb_vorbis/register_types.cpp
+++ b/modules/stb_vorbis/register_types.cpp
@@ -29,15 +29,22 @@
/*************************************************************************/
#include "register_types.h"
+
#include "audio_stream_ogg_vorbis.h"
+
+#ifdef TOOLS_ENABLED
+#include "core/engine.h"
#include "resource_importer_ogg_vorbis.h"
+#endif
void register_stb_vorbis_types() {
#ifdef TOOLS_ENABLED
- Ref<ResourceImporterOGGVorbis> ogg_import;
- ogg_import.instance();
- ResourceFormatImporter::get_singleton()->add_importer(ogg_import);
+ if (Engine::get_singleton()->is_editor_hint()) {
+ Ref<ResourceImporterOGGVorbis> ogg_import;
+ ogg_import.instance();
+ ResourceFormatImporter::get_singleton()->add_importer(ogg_import);
+ }
#endif
ClassDB::register_class<AudioStreamOGGVorbis>();
}
diff --git a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp b/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp
index 7254f57672..e10f29e310 100644
--- a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp
+++ b/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp
@@ -82,9 +82,8 @@ Error ResourceImporterOGGVorbis::import(const String &p_source_file, const Strin
float loop_offset = p_options["loop_offset"];
FileAccess *f = FileAccess::open(p_source_file, FileAccess::READ);
- if (!f) {
- ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
- }
+
+ ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
size_t len = f->get_len();
diff --git a/modules/stb_vorbis/resource_importer_ogg_vorbis.h b/modules/stb_vorbis/resource_importer_ogg_vorbis.h
index d3d0574d56..8e4fbde916 100644
--- a/modules/stb_vorbis/resource_importer_ogg_vorbis.h
+++ b/modules/stb_vorbis/resource_importer_ogg_vorbis.h
@@ -35,7 +35,8 @@
#include "core/io/resource_importer.h"
class ResourceImporterOGGVorbis : public ResourceImporter {
- GDCLASS(ResourceImporterOGGVorbis, ResourceImporter)
+ GDCLASS(ResourceImporterOGGVorbis, ResourceImporter);
+
public:
virtual String get_importer_name() const;
virtual String get_visible_name() const;
diff --git a/modules/svg/SCsub b/modules/svg/SCsub
index 90bfe22abb..9324c1634b 100644
--- a/modules/svg/SCsub
+++ b/modules/svg/SCsub
@@ -16,7 +16,7 @@ env_svg.Prepend(CPPPATH=[thirdparty_dir])
# FIXME: Needed in editor/editor_themes.cpp for now, but ideally there
# shouldn't be a dependency on modules/ and its own 3rd party deps.
env.Prepend(CPPPATH=[thirdparty_dir])
-env.Append(CPPFLAGS=["-DSVG_ENABLED"])
+env.Append(CPPDEFINES=["SVG_ENABLED"])
env_thirdparty = env_svg.Clone()
env_thirdparty.disable_warnings()
diff --git a/modules/svg/image_loader_svg.cpp b/modules/svg/image_loader_svg.cpp
index e36844a1bc..b0cd648734 100644
--- a/modules/svg/image_loader_svg.cpp
+++ b/modules/svg/image_loader_svg.cpp
@@ -123,7 +123,7 @@ Error ImageLoaderSVG::_create_image(Ref<Image> p_image, const PoolVector<uint8_t
rasterizer.rasterize(svg_image, 0, 0, p_scale * upscale, (unsigned char *)dw.ptr(), w, h, w * 4);
- dw = PoolVector<uint8_t>::Write();
+ dw.release();
p_image->create(w, h, false, Image::FORMAT_RGBA8, dst_image);
if (upsample)
p_image->shrink_x2();
diff --git a/modules/tga/image_loader_tga.cpp b/modules/tga/image_loader_tga.cpp
index a3c0f5ded7..6ee408d472 100644
--- a/modules/tga/image_loader_tga.cpp
+++ b/modules/tga/image_loader_tga.cpp
@@ -199,7 +199,7 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff
}
}
- image_data_w = PoolVector<uint8_t>::Write();
+ image_data_w.release();
p_image->create(width, height, 0, Image::FORMAT_RGBA8, image_data);
diff --git a/modules/theora/SCsub b/modules/theora/SCsub
index 785eca4c41..ff65d2f8ec 100644
--- a/modules/theora/SCsub
+++ b/modules/theora/SCsub
@@ -66,7 +66,7 @@ if env['builtin_libtheora']:
thirdparty_sources += thirdparty_sources_x86_vc
if (env["x86_libtheora_opt_gcc"] or env["x86_libtheora_opt_vc"]):
- env_theora.Append(CPPFLAGS=["-DOC_X86_ASM"])
+ env_theora.Append(CPPDEFINES=["OC_X86_ASM"])
thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
diff --git a/modules/theora/config.py b/modules/theora/config.py
index 7504166237..c7713d7607 100644
--- a/modules/theora/config.py
+++ b/modules/theora/config.py
@@ -6,7 +6,6 @@ def configure(env):
def get_doc_classes():
return [
- "ResourceImporterTheora",
"VideoStreamTheora",
]
diff --git a/modules/theora/video_stream_theora.h b/modules/theora/video_stream_theora.h
index 85d73d3c0d..0c37d33358 100644
--- a/modules/theora/video_stream_theora.h
+++ b/modules/theora/video_stream_theora.h
@@ -186,7 +186,6 @@ public:
};
class ResourceFormatLoaderTheora : public ResourceFormatLoader {
- GDCLASS(ResourceFormatLoaderTheora, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/tinyexr/image_loader_tinyexr.cpp b/modules/tinyexr/image_loader_tinyexr.cpp
index bd84a28c84..74a584821a 100644
--- a/modules/tinyexr/image_loader_tinyexr.cpp
+++ b/modules/tinyexr/image_loader_tinyexr.cpp
@@ -122,13 +122,13 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f
}
if (idxG == -1) {
- ERR_PRINT("TinyEXR: G channel not found.")
+ ERR_PRINT("TinyEXR: G channel not found.");
// @todo { free exr_image }
return ERR_FILE_CORRUPT;
}
if (idxB == -1) {
- ERR_PRINT("TinyEXR: B channel not found.")
+ ERR_PRINT("TinyEXR: B channel not found.");
// @todo { free exr_image }
return ERR_FILE_CORRUPT;
}
@@ -235,7 +235,7 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f
p_image->create(exr_image.width, exr_image.height, false, format, imgdata);
- w = PoolVector<uint8_t>::Write();
+ w.release();
FreeEXRHeader(&exr_header);
FreeEXRImage(&exr_image);
diff --git a/modules/upnp/SCsub b/modules/upnp/SCsub
index 6d669ab73b..3f56a69594 100644
--- a/modules/upnp/SCsub
+++ b/modules/upnp/SCsub
@@ -23,10 +23,11 @@ if env['builtin_miniupnpc']:
"portlistingparse.c",
"upnpreplyparse.c",
]
- thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
+ thirdparty_sources = [thirdparty_dir + "miniupnpc/" + file for file in thirdparty_sources]
env_upnp.Prepend(CPPPATH=[thirdparty_dir])
- env_upnp.Append(CPPFLAGS=["-DMINIUPNP_STATICLIB"])
+ env_upnp.Append(CPPDEFINES=["MINIUPNP_STATICLIB"])
+ env_upnp.Append(CPPDEFINES=["MINIUPNPC_SET_SOCKET_TIMEOUT"])
env_thirdparty = env_upnp.Clone()
env_thirdparty.disable_warnings()
diff --git a/modules/upnp/doc_classes/UPNP.xml b/modules/upnp/doc_classes/UPNP.xml
index 0516ea9d54..aac0932995 100644
--- a/modules/upnp/doc_classes/UPNP.xml
+++ b/modules/upnp/doc_classes/UPNP.xml
@@ -5,6 +5,17 @@
</brief_description>
<description>
Provides UPNP functionality to discover [UPNPDevice]s on the local network and execute commands on them, like managing port mappings (port forwarding) and querying the local and remote network IP address. Note that methods on this class are synchronous and block the calling thread.
+ To forward a specific port:
+ [codeblock]
+ const PORT = 7777
+ var upnp = UPNP.new()
+ upnp.discover(2000, 2, "InternetGatewayDevice")
+ upnp.add_port_mapping(port)
+ [/codeblock]
+ To close a specific port (e.g. after you have finished using it):
+ [codeblock]
+ upnp.delete_port_mapping(port)
+ [/codeblock]
</description>
<tutorials>
</tutorials>
@@ -123,13 +134,13 @@
</method>
</methods>
<members>
- <member name="discover_ipv6" type="bool" setter="set_discover_ipv6" getter="is_discover_ipv6">
+ <member name="discover_ipv6" type="bool" setter="set_discover_ipv6" getter="is_discover_ipv6" default="false">
If [code]true[/code], IPv6 is used for [UPNPDevice] discovery.
</member>
- <member name="discover_local_port" type="int" setter="set_discover_local_port" getter="get_discover_local_port">
+ <member name="discover_local_port" type="int" setter="set_discover_local_port" getter="get_discover_local_port" default="0">
If [code]0[/code], the local port to use for discovery is chosen automatically by the system. If [code]1[/code], discovery will be done from the source port 1900 (same as destination port). Otherwise, the value will be used as the port.
</member>
- <member name="discover_multicast_if" type="String" setter="set_discover_multicast_if" getter="get_discover_multicast_if">
+ <member name="discover_multicast_if" type="String" setter="set_discover_multicast_if" getter="get_discover_multicast_if" default="&quot;&quot;">
Multicast interface to use for discovery. Uses the default multicast interface if empty.
</member>
</members>
@@ -171,7 +182,7 @@
No port maps are available. May also be returned if port mapping functionality is not available.
</constant>
<constant name="UPNP_RESULT_CONFLICT_WITH_OTHER_MECHANISM" value="12" enum="UPNPResult">
- Conflict with other mechanism. May be returned instead of [code]UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING[/code] if a port mapping conflicts with an existing one.
+ Conflict with other mechanism. May be returned instead of [constant UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING] if a port mapping conflicts with an existing one.
</constant>
<constant name="UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING" value="13" enum="UPNPResult">
Conflict with an existing port mapping.
diff --git a/modules/upnp/doc_classes/UPNPDevice.xml b/modules/upnp/doc_classes/UPNPDevice.xml
index 1d9a728365..4d3a0f4f1d 100644
--- a/modules/upnp/doc_classes/UPNPDevice.xml
+++ b/modules/upnp/doc_classes/UPNPDevice.xml
@@ -53,22 +53,22 @@
</method>
</methods>
<members>
- <member name="description_url" type="String" setter="set_description_url" getter="get_description_url">
+ <member name="description_url" type="String" setter="set_description_url" getter="get_description_url" default="&quot;&quot;">
URL to the device description.
</member>
- <member name="igd_control_url" type="String" setter="set_igd_control_url" getter="get_igd_control_url">
+ <member name="igd_control_url" type="String" setter="set_igd_control_url" getter="get_igd_control_url" default="&quot;&quot;">
IDG control URL.
</member>
- <member name="igd_our_addr" type="String" setter="set_igd_our_addr" getter="get_igd_our_addr">
+ <member name="igd_our_addr" type="String" setter="set_igd_our_addr" getter="get_igd_our_addr" default="&quot;&quot;">
Address of the local machine in the network connecting it to this [UPNPDevice].
</member>
- <member name="igd_service_type" type="String" setter="set_igd_service_type" getter="get_igd_service_type">
+ <member name="igd_service_type" type="String" setter="set_igd_service_type" getter="get_igd_service_type" default="&quot;&quot;">
IGD service type.
</member>
- <member name="igd_status" type="int" setter="set_igd_status" getter="get_igd_status" enum="UPNPDevice.IGDStatus">
+ <member name="igd_status" type="int" setter="set_igd_status" getter="get_igd_status" enum="UPNPDevice.IGDStatus" default="9">
IGD status. See [enum IGDStatus].
</member>
- <member name="service_type" type="String" setter="set_service_type" getter="get_service_type">
+ <member name="service_type" type="String" setter="set_service_type" getter="get_service_type" default="&quot;&quot;">
Service type.
</member>
</members>
diff --git a/modules/vhacd/SCsub b/modules/vhacd/SCsub
index 161aed2eb9..e581fb7bb2 100644
--- a/modules/vhacd/SCsub
+++ b/modules/vhacd/SCsub
@@ -10,22 +10,21 @@ env_vhacd = env_modules.Clone()
thirdparty_dir = "#thirdparty/vhacd/"
thirdparty_sources = [
-"src/vhacdManifoldMesh.cpp",
-"src/FloatMath.cpp",
-"src/vhacdMesh.cpp",
-"src/vhacdICHull.cpp",
-"src/vhacdVolume.cpp",
-"src/VHACD-ASYNC.cpp",
-"src/btAlignedAllocator.cpp",
-"src/vhacdRaycastMesh.cpp",
-"src/VHACD.cpp",
-"src/btConvexHullComputer.cpp"
+ "src/vhacdManifoldMesh.cpp",
+ "src/FloatMath.cpp",
+ "src/vhacdMesh.cpp",
+ "src/vhacdICHull.cpp",
+ "src/vhacdVolume.cpp",
+ "src/VHACD-ASYNC.cpp",
+ "src/btAlignedAllocator.cpp",
+ "src/vhacdRaycastMesh.cpp",
+ "src/VHACD.cpp",
+ "src/btConvexHullComputer.cpp"
]
thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
env_vhacd.Prepend(CPPPATH=[thirdparty_dir + "/inc"])
-env_vhacd.Append(CPPFLAGS=["-DGODOT_ENET"])
# upstream uses c++11
if not env.msvc:
diff --git a/modules/visual_script/config.py b/modules/visual_script/config.py
index 07a0450734..04e1a40b81 100644
--- a/modules/visual_script/config.py
+++ b/modules/visual_script/config.py
@@ -6,6 +6,7 @@ def configure(env):
def get_doc_classes():
return [
+ "@VisualScript",
"VisualScriptBasicTypeConstant",
"VisualScriptBuiltinFunc",
"VisualScriptClassConstant",
diff --git a/modules/gdnative/doc_classes/ResourceFormatLoaderVideoStreamGDNative.xml b/modules/visual_script/doc_classes/@VisualScript.xml
index cd8b336778..8d9408e6d4 100644
--- a/modules/gdnative/doc_classes/ResourceFormatLoaderVideoStreamGDNative.xml
+++ b/modules/visual_script/doc_classes/@VisualScript.xml
@@ -1,8 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
-<class name="ResourceFormatLoaderVideoStreamGDNative" inherits="ResourceFormatLoader" category="Core" version="3.2">
+<class name="@VisualScript" category="Core" version="3.2">
<brief_description>
+ Built-in visual script functions.
</brief_description>
<description>
+ A list of built-in visual script functions, see [VisualScriptBuiltinFunc] and [VisualScript].
</description>
<tutorials>
</tutorials>
diff --git a/modules/visual_script/doc_classes/VisualScript.xml b/modules/visual_script/doc_classes/VisualScript.xml
index 8f0d881f30..0d95075152 100644
--- a/modules/visual_script/doc_classes/VisualScript.xml
+++ b/modules/visual_script/doc_classes/VisualScript.xml
@@ -252,7 +252,7 @@
<argument index="0" name="name" type="String">
</argument>
<description>
- Returns the info for a given variable as a dictionary. The information includes its name, type, hint and usage.
+ Returns the information for a given variable as a dictionary. The information includes its name, type, hint and usage.
</description>
</method>
<method name="has_custom_signal" qualifiers="const">
diff --git a/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml b/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml
index b591dc9a51..6dc54dbc03 100644
--- a/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml
+++ b/modules/visual_script/doc_classes/VisualScriptBasicTypeConstant.xml
@@ -11,7 +11,7 @@
<methods>
</methods>
<members>
- <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type">
+ <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type" default="0">
The type to get the constant from.
</member>
<member name="constant" type="String" setter="set_basic_type_constant" getter="get_basic_type_constant">
diff --git a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml
index 74d5f29c02..470a3a5e35 100644
--- a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml
+++ b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml
@@ -12,7 +12,7 @@
<methods>
</methods>
<members>
- <member name="function" type="int" setter="set_func" getter="get_func" enum="VisualScriptBuiltinFunc.BuiltinFunc">
+ <member name="function" type="int" setter="set_func" getter="get_func" enum="VisualScriptBuiltinFunc.BuiltinFunc" default="0">
The function to be executed.
</member>
</members>
@@ -102,115 +102,119 @@
</constant>
<constant name="MATH_RANGE_LERP" value="28" enum="BuiltinFunc">
</constant>
- <constant name="MATH_DECTIME" value="29" enum="BuiltinFunc">
- Return the result of 'value' decreased by 'step' * 'amount'.
+ <constant name="MATH_MOVE_TOWARD" value="29" enum="BuiltinFunc">
+ Moves the number toward a value, based on the third input.
</constant>
- <constant name="MATH_RANDOMIZE" value="30" enum="BuiltinFunc">
+ <constant name="MATH_DECTIME" value="30" enum="BuiltinFunc">
+ Return the result of [code]value[/code] decreased by [code]step[/code] * [code]amount[/code].
+ </constant>
+ <constant name="MATH_RANDOMIZE" value="31" enum="BuiltinFunc">
Randomize the seed (or the internal state) of the random number generator. Current implementation reseeds using a number based on time.
</constant>
- <constant name="MATH_RAND" value="31" enum="BuiltinFunc">
+ <constant name="MATH_RAND" value="32" enum="BuiltinFunc">
Return a random 32 bits integer value. To obtain a random value between 0 to N (where N is smaller than 2^32 - 1), you can use it with the remainder function.
</constant>
- <constant name="MATH_RANDF" value="32" enum="BuiltinFunc">
+ <constant name="MATH_RANDF" value="33" enum="BuiltinFunc">
Return a random floating-point value between 0 and 1. To obtain a random value between 0 to N, you can use it with multiplication.
</constant>
- <constant name="MATH_RANDOM" value="33" enum="BuiltinFunc">
+ <constant name="MATH_RANDOM" value="34" enum="BuiltinFunc">
Return a random floating-point value between the two inputs.
</constant>
- <constant name="MATH_SEED" value="34" enum="BuiltinFunc">
+ <constant name="MATH_SEED" value="35" enum="BuiltinFunc">
Set the seed for the random number generator.
</constant>
- <constant name="MATH_RANDSEED" value="35" enum="BuiltinFunc">
+ <constant name="MATH_RANDSEED" value="36" enum="BuiltinFunc">
Return a random value from the given seed, along with the new seed.
</constant>
- <constant name="MATH_DEG2RAD" value="36" enum="BuiltinFunc">
+ <constant name="MATH_DEG2RAD" value="37" enum="BuiltinFunc">
Convert the input from degrees to radians.
</constant>
- <constant name="MATH_RAD2DEG" value="37" enum="BuiltinFunc">
+ <constant name="MATH_RAD2DEG" value="38" enum="BuiltinFunc">
Convert the input from radians to degrees.
</constant>
- <constant name="MATH_LINEAR2DB" value="38" enum="BuiltinFunc">
+ <constant name="MATH_LINEAR2DB" value="39" enum="BuiltinFunc">
Convert the input from linear volume to decibel volume.
</constant>
- <constant name="MATH_DB2LINEAR" value="39" enum="BuiltinFunc">
+ <constant name="MATH_DB2LINEAR" value="40" enum="BuiltinFunc">
Convert the input from decibel volume to linear volume.
</constant>
- <constant name="MATH_POLAR2CARTESIAN" value="40" enum="BuiltinFunc">
- Converts a 2D point expressed in the polar coordinate system (a distance from the origin [code]r[/code] and an angle [code]th[/code]) to the cartesian coordinate system (x and y axis).
+ <constant name="MATH_POLAR2CARTESIAN" value="41" enum="BuiltinFunc">
+ Converts a 2D point expressed in the polar coordinate system (a distance from the origin [code]r[/code] and an angle [code]th[/code]) to the cartesian coordinate system (X and Y axis).
</constant>
- <constant name="MATH_CARTESIAN2POLAR" value="41" enum="BuiltinFunc">
- Converts a 2D point expressed in the cartesian coordinate system (x and y axis) to the polar coordinate system (a distance from the origin and an angle).
+ <constant name="MATH_CARTESIAN2POLAR" value="42" enum="BuiltinFunc">
+ Converts a 2D point expressed in the cartesian coordinate system (X and Y axis) to the polar coordinate system (a distance from the origin and an angle).
</constant>
- <constant name="MATH_WRAP" value="42" enum="BuiltinFunc">
+ <constant name="MATH_WRAP" value="43" enum="BuiltinFunc">
</constant>
- <constant name="MATH_WRAPF" value="43" enum="BuiltinFunc">
+ <constant name="MATH_WRAPF" value="44" enum="BuiltinFunc">
</constant>
- <constant name="LOGIC_MAX" value="44" enum="BuiltinFunc">
+ <constant name="LOGIC_MAX" value="45" enum="BuiltinFunc">
Return the greater of the two numbers, also known as their maximum.
</constant>
- <constant name="LOGIC_MIN" value="45" enum="BuiltinFunc">
+ <constant name="LOGIC_MIN" value="46" enum="BuiltinFunc">
Return the lesser of the two numbers, also known as their minimum.
</constant>
- <constant name="LOGIC_CLAMP" value="46" enum="BuiltinFunc">
+ <constant name="LOGIC_CLAMP" value="47" enum="BuiltinFunc">
Return the input clamped inside the given range, ensuring the result is never outside it. Equivalent to [code]min(max(input, range_low), range_high)[/code].
</constant>
- <constant name="LOGIC_NEAREST_PO2" value="47" enum="BuiltinFunc">
+ <constant name="LOGIC_NEAREST_PO2" value="48" enum="BuiltinFunc">
Return the nearest power of 2 to the input.
</constant>
- <constant name="OBJ_WEAKREF" value="48" enum="BuiltinFunc">
+ <constant name="OBJ_WEAKREF" value="49" enum="BuiltinFunc">
Create a [WeakRef] from the input.
</constant>
- <constant name="FUNC_FUNCREF" value="49" enum="BuiltinFunc">
+ <constant name="FUNC_FUNCREF" value="50" enum="BuiltinFunc">
Create a [FuncRef] from the input.
</constant>
- <constant name="TYPE_CONVERT" value="50" enum="BuiltinFunc">
+ <constant name="TYPE_CONVERT" value="51" enum="BuiltinFunc">
Convert between types.
</constant>
- <constant name="TYPE_OF" value="51" enum="BuiltinFunc">
+ <constant name="TYPE_OF" value="52" enum="BuiltinFunc">
Return the type of the input as an integer. Check [enum Variant.Type] for the integers that might be returned.
</constant>
- <constant name="TYPE_EXISTS" value="52" enum="BuiltinFunc">
+ <constant name="TYPE_EXISTS" value="53" enum="BuiltinFunc">
Checks if a type is registered in the [ClassDB].
</constant>
- <constant name="TEXT_CHAR" value="53" enum="BuiltinFunc">
+ <constant name="TEXT_CHAR" value="54" enum="BuiltinFunc">
Return a character with the given ascii value.
</constant>
- <constant name="TEXT_STR" value="54" enum="BuiltinFunc">
+ <constant name="TEXT_STR" value="55" enum="BuiltinFunc">
Convert the input to a string.
</constant>
- <constant name="TEXT_PRINT" value="55" enum="BuiltinFunc">
+ <constant name="TEXT_PRINT" value="56" enum="BuiltinFunc">
Print the given string to the output window.
</constant>
- <constant name="TEXT_PRINTERR" value="56" enum="BuiltinFunc">
+ <constant name="TEXT_PRINTERR" value="57" enum="BuiltinFunc">
Print the given string to the standard error output.
</constant>
- <constant name="TEXT_PRINTRAW" value="57" enum="BuiltinFunc">
+ <constant name="TEXT_PRINTRAW" value="58" enum="BuiltinFunc">
Print the given string to the standard output, without adding a newline.
</constant>
- <constant name="VAR_TO_STR" value="58" enum="BuiltinFunc">
+ <constant name="VAR_TO_STR" value="59" enum="BuiltinFunc">
Serialize a [Variant] to a string.
</constant>
- <constant name="STR_TO_VAR" value="59" enum="BuiltinFunc">
- Deserialize a [Variant] from a string serialized using [code]VAR_TO_STR[/code].
+ <constant name="STR_TO_VAR" value="60" enum="BuiltinFunc">
+ Deserialize a [Variant] from a string serialized using [constant VAR_TO_STR].
</constant>
- <constant name="VAR_TO_BYTES" value="60" enum="BuiltinFunc">
+ <constant name="VAR_TO_BYTES" value="61" enum="BuiltinFunc">
Serialize a [Variant] to a [PoolByteArray].
</constant>
- <constant name="BYTES_TO_VAR" value="61" enum="BuiltinFunc">
- Deserialize a [Variant] from a [PoolByteArray] serialized using [code]VAR_TO_BYTES[/code].
+ <constant name="BYTES_TO_VAR" value="62" enum="BuiltinFunc">
+ Deserialize a [Variant] from a [PoolByteArray] serialized using [constant VAR_TO_BYTES].
</constant>
- <constant name="COLORN" value="62" enum="BuiltinFunc">
- Return the [Color] with the given name and alpha ranging from 0 to 1. Note: names are defined in color_names.inc.
+ <constant name="COLORN" value="63" enum="BuiltinFunc">
+ Return the [Color] with the given name and alpha ranging from 0 to 1
+ [b]Note:[/b] Names are defined in [code]color_names.inc[/code].
</constant>
- <constant name="MATH_SMOOTHSTEP" value="63" enum="BuiltinFunc">
- Return a number smoothly interpolated between the first two inputs, based on the third input. Similar to [code]MATH_LERP[/code], but interpolates faster at the beginning and slower at the end. Using Hermite interpolation formula:
+ <constant name="MATH_SMOOTHSTEP" value="64" enum="BuiltinFunc">
+ Return a number smoothly interpolated between the first two inputs, based on the third input. Similar to [constant MATH_LERP], but interpolates faster at the beginning and slower at the end. Using Hermite interpolation formula:
[codeblock]
var t = clamp((weight - from) / (to - from), 0.0, 1.0)
return t * t * (3.0 - 2.0 * t)
[/codeblock]
</constant>
- <constant name="FUNC_MAX" value="64" enum="BuiltinFunc">
- The maximum value the [member function] property can have.
+ <constant name="FUNC_MAX" value="65" enum="BuiltinFunc">
+ Represents the size of the [enum BuiltinFunc] enum.
</constant>
</constants>
</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptClassConstant.xml b/modules/visual_script/doc_classes/VisualScriptClassConstant.xml
index 6e48e7c416..49ea7850ef 100644
--- a/modules/visual_script/doc_classes/VisualScriptClassConstant.xml
+++ b/modules/visual_script/doc_classes/VisualScriptClassConstant.xml
@@ -4,7 +4,7 @@
Gets a constant from a given class.
</brief_description>
<description>
- This node returns a constant from a given class, such as [constant @GlobalScope.TYPE_INT]. See the given class' documentation for available constants.
+ This node returns a constant from a given class, such as [constant TYPE_INT]. See the given class' documentation for available constants.
[b]Input Ports:[/b]
none
[b]Output Ports:[/b]
@@ -15,10 +15,10 @@
<methods>
</methods>
<members>
- <member name="base_type" type="String" setter="set_base_type" getter="get_base_type">
+ <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default="&quot;Object&quot;">
The constant's parent class.
</member>
- <member name="constant" type="String" setter="set_class_constant" getter="get_class_constant">
+ <member name="constant" type="String" setter="set_class_constant" getter="get_class_constant" default="&quot;&quot;">
The constant to return. See the given class for its available constants.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptComment.xml b/modules/visual_script/doc_classes/VisualScriptComment.xml
index 9652654610..2538bc8356 100644
--- a/modules/visual_script/doc_classes/VisualScriptComment.xml
+++ b/modules/visual_script/doc_classes/VisualScriptComment.xml
@@ -12,13 +12,13 @@
<methods>
</methods>
<members>
- <member name="description" type="String" setter="set_description" getter="get_description">
+ <member name="description" type="String" setter="set_description" getter="get_description" default="&quot;&quot;">
The text inside the comment node.
</member>
- <member name="size" type="Vector2" setter="set_size" getter="get_size">
+ <member name="size" type="Vector2" setter="set_size" getter="get_size" default="Vector2( 150, 150 )">
The comment node's size (in pixels).
</member>
- <member name="title" type="String" setter="set_title" getter="get_title">
+ <member name="title" type="String" setter="set_title" getter="get_title" default="&quot;Comment&quot;">
The comment node's title.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptConstant.xml b/modules/visual_script/doc_classes/VisualScriptConstant.xml
index b15af8e4ea..eb12fc3731 100644
--- a/modules/visual_script/doc_classes/VisualScriptConstant.xml
+++ b/modules/visual_script/doc_classes/VisualScriptConstant.xml
@@ -15,7 +15,7 @@
<methods>
</methods>
<members>
- <member name="type" type="int" setter="set_constant_type" getter="get_constant_type" enum="Variant.Type">
+ <member name="type" type="int" setter="set_constant_type" getter="get_constant_type" enum="Variant.Type" default="0">
The constant's type.
</member>
<member name="value" type="Variant" setter="set_constant_value" getter="get_constant_value">
diff --git a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml
index 1ab9f807fb..b079653591 100644
--- a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml
+++ b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml
@@ -45,7 +45,7 @@
<argument index="0" name="idx" type="int">
</argument>
<description>
- Return the specified input port's type. See the TYPE_* enum in [@GlobalScope].
+ Return the specified input port's type. See the [code]TYPE_*[/code] enum in [@GlobalScope].
</description>
</method>
<method name="_get_output_sequence_port_count" qualifiers="virtual">
@@ -86,7 +86,7 @@
<argument index="0" name="idx" type="int">
</argument>
<description>
- Return the specified output's type. See the TYPE_* enum in [@GlobalScope].
+ Return the specified output's type. See the [code]TYPE_*[/code] enum in [@GlobalScope].
</description>
</method>
<method name="_get_text" qualifiers="virtual">
@@ -125,9 +125,9 @@
Execute the custom node's logic, returning the index of the output sequence port to use or a [String] when there is an error.
The [code]inputs[/code] array contains the values of the input ports.
[code]outputs[/code] is an array whose indices should be set to the respective outputs.
- The [code]start_mode[/code] is usually [code]START_MODE_BEGIN_SEQUENCE[/code], unless you have used the STEP_* constants.
+ The [code]start_mode[/code] is usually [constant START_MODE_BEGIN_SEQUENCE], unless you have used the [code]STEP_*[/code] constants.
[code]working_mem[/code] is an array which can be used to persist information between runs of the custom node.
- When returning, you can mask the returned value with one of the STEP_* constants.
+ When returning, you can mask the returned value with one of the [code]STEP_*[/code] constants.
</description>
</method>
</methods>
diff --git a/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml b/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml
index a0eed5b753..c8543287b4 100644
--- a/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml
+++ b/modules/visual_script/doc_classes/VisualScriptDeconstruct.xml
@@ -11,7 +11,7 @@
<methods>
</methods>
<members>
- <member name="type" type="int" setter="set_deconstruct_type" getter="get_deconstruct_type" enum="Variant.Type">
+ <member name="type" type="int" setter="set_deconstruct_type" getter="get_deconstruct_type" enum="Variant.Type" default="0">
The type to deconstruct.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml b/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml
index 623aa1ba86..1a567905a9 100644
--- a/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml
+++ b/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml
@@ -15,7 +15,7 @@
<methods>
</methods>
<members>
- <member name="signal" type="String" setter="set_signal" getter="get_signal">
+ <member name="signal" type="String" setter="set_signal" getter="get_signal" default="&quot;&quot;">
The signal to emit.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml b/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml
index 525389366a..05bd87ec22 100644
--- a/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml
+++ b/modules/visual_script/doc_classes/VisualScriptEngineSingleton.xml
@@ -11,7 +11,7 @@
<methods>
</methods>
<members>
- <member name="constant" type="String" setter="set_singleton" getter="get_singleton">
+ <member name="constant" type="String" setter="set_singleton" getter="get_singleton" default="&quot;&quot;">
The singleton's name.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml b/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml
index e4d0bb7672..f7f86e8c80 100644
--- a/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml
+++ b/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml
@@ -11,23 +11,23 @@
<members>
<member name="base_script" type="String" setter="set_base_script" getter="get_base_script">
</member>
- <member name="base_type" type="String" setter="set_base_type" getter="get_base_type">
+ <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default="&quot;Object&quot;">
</member>
<member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type">
</member>
- <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptFunctionCall.CallMode">
+ <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptFunctionCall.CallMode" default="0">
</member>
- <member name="function" type="String" setter="set_function" getter="get_function">
+ <member name="function" type="String" setter="set_function" getter="get_function" default="&quot;&quot;">
</member>
<member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path">
</member>
- <member name="rpc_call_mode" type="int" setter="set_rpc_call_mode" getter="get_rpc_call_mode" enum="VisualScriptFunctionCall.RPCCallMode">
+ <member name="rpc_call_mode" type="int" setter="set_rpc_call_mode" getter="get_rpc_call_mode" enum="VisualScriptFunctionCall.RPCCallMode" default="0">
</member>
<member name="singleton" type="String" setter="set_singleton" getter="get_singleton">
</member>
<member name="use_default_args" type="int" setter="set_use_default_args" getter="get_use_default_args">
</member>
- <member name="validate" type="bool" setter="set_validate" getter="get_validate">
+ <member name="validate" type="bool" setter="set_validate" getter="get_validate" default="true">
</member>
</members>
<constants>
diff --git a/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml b/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml
index 4099a351e6..6c70dc7dc4 100644
--- a/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml
+++ b/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml
@@ -9,7 +9,7 @@
<methods>
</methods>
<members>
- <member name="constant" type="int" setter="set_global_constant" getter="get_global_constant">
+ <member name="constant" type="int" setter="set_global_constant" getter="get_global_constant" default="0">
</member>
</members>
<constants>
diff --git a/modules/visual_script/doc_classes/VisualScriptInputAction.xml b/modules/visual_script/doc_classes/VisualScriptInputAction.xml
index 4bd1430cf6..8c942813b2 100644
--- a/modules/visual_script/doc_classes/VisualScriptInputAction.xml
+++ b/modules/visual_script/doc_classes/VisualScriptInputAction.xml
@@ -9,9 +9,9 @@
<methods>
</methods>
<members>
- <member name="action" type="String" setter="set_action_name" getter="get_action_name">
+ <member name="action" type="String" setter="set_action_name" getter="get_action_name" default="&quot;&quot;">
</member>
- <member name="mode" type="int" setter="set_action_mode" getter="get_action_mode" enum="VisualScriptInputAction.Mode">
+ <member name="mode" type="int" setter="set_action_mode" getter="get_action_mode" enum="VisualScriptInputAction.Mode" default="0">
</member>
</members>
<constants>
diff --git a/modules/visual_script/doc_classes/VisualScriptLocalVar.xml b/modules/visual_script/doc_classes/VisualScriptLocalVar.xml
index 5d061ea79f..8c21c3f0bc 100644
--- a/modules/visual_script/doc_classes/VisualScriptLocalVar.xml
+++ b/modules/visual_script/doc_classes/VisualScriptLocalVar.xml
@@ -15,10 +15,10 @@
<methods>
</methods>
<members>
- <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type">
+ <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type" default="0">
The local variable's type.
</member>
- <member name="var_name" type="String" setter="set_var_name" getter="get_var_name">
+ <member name="var_name" type="String" setter="set_var_name" getter="get_var_name" default="&quot;new_local&quot;">
The local variable's name.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml b/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml
index 049195d890..a981432cdb 100644
--- a/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml
+++ b/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml
@@ -17,10 +17,10 @@
<methods>
</methods>
<members>
- <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type">
+ <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type" default="0">
The local variable's type.
</member>
- <member name="var_name" type="String" setter="set_var_name" getter="get_var_name">
+ <member name="var_name" type="String" setter="set_var_name" getter="get_var_name" default="&quot;new_local&quot;">
The local variable's name.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptMathConstant.xml b/modules/visual_script/doc_classes/VisualScriptMathConstant.xml
index 430f9ee7d4..3be392aef5 100644
--- a/modules/visual_script/doc_classes/VisualScriptMathConstant.xml
+++ b/modules/visual_script/doc_classes/VisualScriptMathConstant.xml
@@ -15,7 +15,7 @@
<methods>
</methods>
<members>
- <member name="constant" type="int" setter="set_math_constant" getter="get_math_constant" enum="VisualScriptMathConstant.MathConstant">
+ <member name="constant" type="int" setter="set_math_constant" getter="get_math_constant" enum="VisualScriptMathConstant.MathConstant" default="0">
The math constant.
</member>
</members>
@@ -45,6 +45,7 @@
Not a number: [code]nan[/code]
</constant>
<constant name="MATH_CONSTANT_MAX" value="8" enum="MathConstant">
+ Represents the size of the [enum MathConstant] enum.
</constant>
</constants>
</class>
diff --git a/modules/visual_script/doc_classes/VisualScriptOperator.xml b/modules/visual_script/doc_classes/VisualScriptOperator.xml
index a0827972e0..80449ac521 100644
--- a/modules/visual_script/doc_classes/VisualScriptOperator.xml
+++ b/modules/visual_script/doc_classes/VisualScriptOperator.xml
@@ -14,9 +14,9 @@
<methods>
</methods>
<members>
- <member name="operator" type="int" setter="set_operator" getter="get_operator" enum="Variant.Operator">
+ <member name="operator" type="int" setter="set_operator" getter="get_operator" enum="Variant.Operator" default="6">
</member>
- <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type">
+ <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type" default="0">
</member>
</members>
<constants>
diff --git a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml
index 697a31ca46..af1e8e68e8 100644
--- a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml
+++ b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml
@@ -11,7 +11,7 @@
<members>
<member name="base_script" type="String" setter="set_base_script" getter="get_base_script">
</member>
- <member name="base_type" type="String" setter="set_base_type" getter="get_base_type">
+ <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default="&quot;Object&quot;">
</member>
<member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type">
</member>
@@ -19,9 +19,9 @@
</member>
<member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path">
</member>
- <member name="property" type="String" setter="set_property" getter="get_property">
+ <member name="property" type="String" setter="set_property" getter="get_property" default="&quot;&quot;">
</member>
- <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertyGet.CallMode">
+ <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertyGet.CallMode" default="0">
</member>
</members>
<constants>
diff --git a/modules/visual_script/doc_classes/VisualScriptPropertySet.xml b/modules/visual_script/doc_classes/VisualScriptPropertySet.xml
index c41e3781d4..380c196caf 100644
--- a/modules/visual_script/doc_classes/VisualScriptPropertySet.xml
+++ b/modules/visual_script/doc_classes/VisualScriptPropertySet.xml
@@ -9,11 +9,11 @@
<methods>
</methods>
<members>
- <member name="assign_op" type="int" setter="set_assign_op" getter="get_assign_op" enum="VisualScriptPropertySet.AssignOp">
+ <member name="assign_op" type="int" setter="set_assign_op" getter="get_assign_op" enum="VisualScriptPropertySet.AssignOp" default="0">
</member>
<member name="base_script" type="String" setter="set_base_script" getter="get_base_script">
</member>
- <member name="base_type" type="String" setter="set_base_type" getter="get_base_type">
+ <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default="&quot;Object&quot;">
</member>
<member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type">
</member>
@@ -21,9 +21,9 @@
</member>
<member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path">
</member>
- <member name="property" type="String" setter="set_property" getter="get_property">
+ <member name="property" type="String" setter="set_property" getter="get_property" default="&quot;&quot;">
</member>
- <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertySet.CallMode">
+ <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertySet.CallMode" default="0">
</member>
</members>
<constants>
diff --git a/modules/visual_script/doc_classes/VisualScriptResourcePath.xml b/modules/visual_script/doc_classes/VisualScriptResourcePath.xml
index 40862b810b..da37bbbb2c 100644
--- a/modules/visual_script/doc_classes/VisualScriptResourcePath.xml
+++ b/modules/visual_script/doc_classes/VisualScriptResourcePath.xml
@@ -9,7 +9,7 @@
<methods>
</methods>
<members>
- <member name="path" type="String" setter="set_resource_path" getter="get_resource_path">
+ <member name="path" type="String" setter="set_resource_path" getter="get_resource_path" default="&quot;&quot;">
</member>
</members>
<constants>
diff --git a/modules/visual_script/doc_classes/VisualScriptReturn.xml b/modules/visual_script/doc_classes/VisualScriptReturn.xml
index 40c8963efe..9a81c671d4 100644
--- a/modules/visual_script/doc_classes/VisualScriptReturn.xml
+++ b/modules/visual_script/doc_classes/VisualScriptReturn.xml
@@ -16,10 +16,10 @@
<methods>
</methods>
<members>
- <member name="return_enabled" type="bool" setter="set_enable_return_value" getter="is_return_value_enabled">
+ <member name="return_enabled" type="bool" setter="set_enable_return_value" getter="is_return_value_enabled" default="false">
If [code]true[/code], the [code]return[/code] input port is available.
</member>
- <member name="return_type" type="int" setter="set_return_type" getter="get_return_type" enum="Variant.Type">
+ <member name="return_type" type="int" setter="set_return_type" getter="get_return_type" enum="Variant.Type" default="0">
The return value's data type.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptSceneNode.xml b/modules/visual_script/doc_classes/VisualScriptSceneNode.xml
index 81ef4ceedc..99f4acbd27 100644
--- a/modules/visual_script/doc_classes/VisualScriptSceneNode.xml
+++ b/modules/visual_script/doc_classes/VisualScriptSceneNode.xml
@@ -15,7 +15,7 @@
<methods>
</methods>
<members>
- <member name="node_path" type="NodePath" setter="set_node_path" getter="get_node_path">
+ <member name="node_path" type="NodePath" setter="set_node_path" getter="get_node_path" default="NodePath(&quot;.&quot;)">
The node's path in the scene tree.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptSelect.xml b/modules/visual_script/doc_classes/VisualScriptSelect.xml
index 3b1e7f7f02..e6a6cd5a48 100644
--- a/modules/visual_script/doc_classes/VisualScriptSelect.xml
+++ b/modules/visual_script/doc_classes/VisualScriptSelect.xml
@@ -17,7 +17,7 @@
<methods>
</methods>
<members>
- <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type">
+ <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type" default="0">
The input variables' type.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptSequence.xml b/modules/visual_script/doc_classes/VisualScriptSequence.xml
index 26af15b404..2ceceb199f 100644
--- a/modules/visual_script/doc_classes/VisualScriptSequence.xml
+++ b/modules/visual_script/doc_classes/VisualScriptSequence.xml
@@ -17,7 +17,7 @@
<methods>
</methods>
<members>
- <member name="steps" type="int" setter="set_steps" getter="get_steps">
+ <member name="steps" type="int" setter="set_steps" getter="get_steps" default="1">
The number of steps in the sequence.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptSwitch.xml b/modules/visual_script/doc_classes/VisualScriptSwitch.xml
index 35929b16ac..3e3b88ebe0 100644
--- a/modules/visual_script/doc_classes/VisualScriptSwitch.xml
+++ b/modules/visual_script/doc_classes/VisualScriptSwitch.xml
@@ -4,7 +4,7 @@
Branches program flow based on a given input's value.
</brief_description>
<description>
- Branches the flow based on an input's value. Use "Case Count" in the Inspector to set the number of branches and each comparison's optional type.
+ Branches the flow based on an input's value. Use [b]Case Count[/b] in the Inspector to set the number of branches and each comparison's optional type.
[b]Input Ports:[/b]
- Sequence: [code]'input' is[/code]
- Data (variant): [code]=[/code]
diff --git a/modules/visual_script/doc_classes/VisualScriptTypeCast.xml b/modules/visual_script/doc_classes/VisualScriptTypeCast.xml
index a9e920bca6..999a190a9a 100644
--- a/modules/visual_script/doc_classes/VisualScriptTypeCast.xml
+++ b/modules/visual_script/doc_classes/VisualScriptTypeCast.xml
@@ -9,9 +9,9 @@
<methods>
</methods>
<members>
- <member name="base_script" type="String" setter="set_base_script" getter="get_base_script">
+ <member name="base_script" type="String" setter="set_base_script" getter="get_base_script" default="&quot;&quot;">
</member>
- <member name="base_type" type="String" setter="set_base_type" getter="get_base_type">
+ <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default="&quot;Object&quot;">
</member>
</members>
<constants>
diff --git a/modules/visual_script/doc_classes/VisualScriptVariableGet.xml b/modules/visual_script/doc_classes/VisualScriptVariableGet.xml
index e1c7c4e4d4..40e461294b 100644
--- a/modules/visual_script/doc_classes/VisualScriptVariableGet.xml
+++ b/modules/visual_script/doc_classes/VisualScriptVariableGet.xml
@@ -15,7 +15,7 @@
<methods>
</methods>
<members>
- <member name="var_name" type="String" setter="set_variable" getter="get_variable">
+ <member name="var_name" type="String" setter="set_variable" getter="get_variable" default="&quot;&quot;">
The variable's name.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptVariableSet.xml b/modules/visual_script/doc_classes/VisualScriptVariableSet.xml
index 7339482908..6c53ad61b4 100644
--- a/modules/visual_script/doc_classes/VisualScriptVariableSet.xml
+++ b/modules/visual_script/doc_classes/VisualScriptVariableSet.xml
@@ -16,7 +16,7 @@
<methods>
</methods>
<members>
- <member name="var_name" type="String" setter="set_variable" getter="get_variable">
+ <member name="var_name" type="String" setter="set_variable" getter="get_variable" default="&quot;&quot;">
The variable's name.
</member>
</members>
diff --git a/modules/visual_script/doc_classes/VisualScriptYield.xml b/modules/visual_script/doc_classes/VisualScriptYield.xml
index 9f61a5f88c..c506e6db01 100644
--- a/modules/visual_script/doc_classes/VisualScriptYield.xml
+++ b/modules/visual_script/doc_classes/VisualScriptYield.xml
@@ -9,7 +9,7 @@
<methods>
</methods>
<members>
- <member name="mode" type="int" setter="set_yield_mode" getter="get_yield_mode" enum="VisualScriptYield.YieldMode">
+ <member name="mode" type="int" setter="set_yield_mode" getter="get_yield_mode" enum="VisualScriptYield.YieldMode" default="1">
</member>
<member name="wait_time" type="float" setter="set_wait_time" getter="get_wait_time">
</member>
diff --git a/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml b/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml
index 6791375182..b9d7aedaab 100644
--- a/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml
+++ b/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml
@@ -9,13 +9,13 @@
<methods>
</methods>
<members>
- <member name="base_type" type="String" setter="set_base_type" getter="get_base_type">
+ <member name="base_type" type="String" setter="set_base_type" getter="get_base_type" default="&quot;Object&quot;">
</member>
- <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptYieldSignal.CallMode">
+ <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptYieldSignal.CallMode" default="0">
</member>
<member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path">
</member>
- <member name="signal" type="String" setter="set_signal" getter="get_signal">
+ <member name="signal" type="String" setter="set_signal" getter="get_signal" default="&quot;&quot;">
</member>
</members>
<constants>
diff --git a/modules/visual_script/icons/icon_visual_script.svg b/modules/visual_script/icons/icon_visual_script.svg
new file mode 100644
index 0000000000..f6475d590e
--- /dev/null
+++ b/modules/visual_script/icons/icon_visual_script.svg
@@ -0,0 +1,6 @@
+<svg width="16" height="16" version="1.1" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
+<g transform="translate(0 -1036.4)">
+<ellipse cx="3" cy="1039.4" r="2" fill="#6e6e6e"/>
+<path transform="translate(0 1036.4)" d="m7 1l-0.56445 2.2578a5 5 0 0 0 -0.68945 0.2793l-1.9883-1.1934-1.4141 1.4141 1.1953 1.9941a5 5 0 0 0 -0.28516 0.68555l-2.2539 0.5625v2h5.2715a2 2 0 0 1 -0.27148 -1 2 2 0 0 1 2 -2 2 2 0 0 1 2 2 2 2 0 0 1 -0.26953 1h5.2695v-2l-2.2578-0.56445a5 5 0 0 0 -0.2793 -0.6875l1.1934-1.9902-1.4141-1.4141-1.9941 1.1953a5 5 0 0 0 -0.68555 -0.28516l-0.5625-2.2539h-2zm-4 9v6h2a3 3 0 0 0 3 -3v-3h-2v3a1 1 0 0 1 -1 1v-4h-2zm8 0a2 2 0 0 0 -1.7324 1 2 2 0 0 0 0 2 2 2 0 0 0 1.7324 1h-2v2h2a2 2 0 0 0 1.7324 -1 2 2 0 0 0 0 -2 2 2 0 0 0 -1.7324 -1h2v-2h-2z" fill="#e0e0e0"/>
+</g>
+</svg>
diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp
index 8f311d11f4..b816e37936 100644
--- a/modules/visual_script/visual_script.cpp
+++ b/modules/visual_script/visual_script.cpp
@@ -46,15 +46,7 @@ bool VisualScriptNode::is_breakpoint() const {
return breakpoint;
}
-void VisualScriptNode::_notification(int p_what) {
-
- if (p_what == NOTIFICATION_POSTINITIALIZE) {
- validate_input_default_values();
- }
-}
-
void VisualScriptNode::ports_changed_notify() {
- validate_input_default_values();
emit_signal("ports_changed");
}
@@ -273,11 +265,7 @@ void VisualScript::_node_ports_changed(int p_id) {
Function &func = functions[function];
Ref<VisualScriptNode> vsn = func.nodes[p_id].node;
- if (OS::get_singleton()->get_main_loop() &&
- Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop()) &&
- Engine::get_singleton()->is_editor_hint()) {
- vsn->validate_input_default_values(); //force validate default values when editing on editor
- }
+ vsn->validate_input_default_values();
//must revalidate all the functions
@@ -353,6 +341,7 @@ void VisualScript::add_node(const StringName &p_func, int p_id, const Ref<Visual
Ref<VisualScriptNode> vsn = p_node;
vsn->connect("ports_changed", this, "_node_ports_changed", varray(p_id));
vsn->scripts_used.insert(this);
+ vsn->validate_input_default_values(); // Validate when fully loaded
func.nodes[p_id] = nd;
}
@@ -1498,7 +1487,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
Variant **output_args = (Variant **)(input_args + max_input_args);
int flow_max = f->flow_stack_size;
int *flow_stack = flow_max ? (int *)(output_args + max_output_args) : (int *)NULL;
- int *pass_stack = flow_stack + flow_max;
+ int *pass_stack = flow_stack ? (int *)(flow_stack + flow_max) : (int *)NULL;
String error_str;
@@ -1703,7 +1692,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p
if ((ret == output || ret & VisualScriptNodeInstance::STEP_FLAG_PUSH_STACK_BIT) && node->sequence_output_count) {
//if no exit bit was set, and has sequence outputs, guess next node
- if (output < 0 || output >= node->sequence_output_count) {
+ if (output >= node->sequence_output_count) {
r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
error_str = RTR("Node returned an invalid sequence output: ") + itos(output);
error = true;
@@ -1916,7 +1905,7 @@ Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p
Variant **output_args = (Variant **)(input_args + max_input_args);
int flow_max = f->flow_stack_size;
int *flow_stack = flow_max ? (int *)(output_args + max_output_args) : (int *)NULL;
- int *pass_stack = flow_stack + flow_max;
+ int *pass_stack = flow_stack ? (int *)(flow_stack + flow_max) : (int *)NULL;
for (int i = 0; i < f->node_count; i++) {
sequence_bits[i] = false; //all starts as false
diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h
index 91748d077b..098c28370d 100644
--- a/modules/visual_script/visual_script.h
+++ b/modules/visual_script/visual_script.h
@@ -39,7 +39,7 @@ class VisualScriptNodeInstance;
class VisualScript;
class VisualScriptNode : public Resource {
- GDCLASS(VisualScriptNode, Resource)
+ GDCLASS(VisualScriptNode, Resource);
friend class VisualScript;
@@ -54,7 +54,6 @@ class VisualScriptNode : public Resource {
void validate_input_default_values();
protected:
- void _notification(int p_what);
void ports_changed_notify();
static void _bind_methods();
@@ -166,7 +165,7 @@ public:
class VisualScript : public Script {
- GDCLASS(VisualScript, Script)
+ GDCLASS(VisualScript, Script);
RES_BASE_EXTENSION("vs");
diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp
index d207656705..6c9c6b0fc8 100644
--- a/modules/visual_script/visual_script_builtin_funcs.cpp
+++ b/modules/visual_script/visual_script_builtin_funcs.cpp
@@ -68,6 +68,7 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX
"lerp",
"inverse_lerp",
"range_lerp",
+ "move_toward",
"dectime",
"randomize",
"randi",
@@ -103,6 +104,7 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX
"bytes2var",
"color_named",
"smoothstep",
+ "posmod",
};
VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::find_function(const String &p_string) {
@@ -191,6 +193,7 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) {
case MATH_ATAN2:
case MATH_FMOD:
case MATH_FPOSMOD:
+ case MATH_POSMOD:
case MATH_POW:
case MATH_EASE:
case MATH_STEPIFY:
@@ -206,6 +209,7 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) {
case MATH_LERP:
case MATH_INVERSE_LERP:
case MATH_SMOOTHSTEP:
+ case MATH_MOVE_TOWARD:
case MATH_DECTIME:
case MATH_WRAP:
case MATH_WRAPF:
@@ -259,7 +263,16 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
case MATH_ASIN:
case MATH_ACOS:
case MATH_ATAN:
- case MATH_SQRT: {
+ case MATH_SQRT:
+ case MATH_FLOOR:
+ case MATH_CEIL:
+ case MATH_ROUND:
+ case MATH_ABS:
+ case MATH_SIGN:
+ case MATH_LOG:
+ case MATH_EXP:
+ case MATH_ISNAN:
+ case MATH_ISINF: {
return PropertyInfo(Variant::REAL, "s");
} break;
case MATH_ATAN2: {
@@ -269,32 +282,25 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
return PropertyInfo(Variant::REAL, "x");
} break;
case MATH_FMOD:
- case MATH_FPOSMOD: {
+ case MATH_FPOSMOD:
+ case LOGIC_MAX:
+ case LOGIC_MIN: {
if (p_idx == 0)
- return PropertyInfo(Variant::REAL, "x");
+ return PropertyInfo(Variant::REAL, "a");
else
- return PropertyInfo(Variant::REAL, "y");
+ return PropertyInfo(Variant::REAL, "b");
} break;
- case MATH_FLOOR:
- case MATH_CEIL:
- case MATH_ROUND:
- case MATH_ABS:
- case MATH_SIGN: {
- return PropertyInfo(Variant::REAL, "s");
-
+ case MATH_POSMOD: {
+ if (p_idx == 0)
+ return PropertyInfo(Variant::INT, "a");
+ else
+ return PropertyInfo(Variant::INT, "b");
} break;
-
case MATH_POW: {
if (p_idx == 0)
- return PropertyInfo(Variant::REAL, "x");
+ return PropertyInfo(Variant::REAL, "base");
else
- return PropertyInfo(Variant::REAL, "y");
- } break;
- case MATH_LOG:
- case MATH_EXP:
- case MATH_ISNAN:
- case MATH_ISINF: {
- return PropertyInfo(Variant::REAL, "s");
+ return PropertyInfo(Variant::REAL, "exp");
} break;
case MATH_EASE: {
if (p_idx == 0)
@@ -311,14 +317,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
else
return PropertyInfo(Variant::REAL, "steps");
} break;
- case MATH_LERP: {
- if (p_idx == 0)
- return PropertyInfo(Variant::REAL, "from");
- else if (p_idx == 1)
- return PropertyInfo(Variant::REAL, "to");
- else
- return PropertyInfo(Variant::REAL, "weight");
- } break;
+ case MATH_LERP:
case MATH_INVERSE_LERP: {
if (p_idx == 0)
return PropertyInfo(Variant::REAL, "from");
@@ -347,6 +346,14 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
else
return PropertyInfo(Variant::REAL, "weight");
} break;
+ case MATH_MOVE_TOWARD: {
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "from");
+ else if (p_idx == 1)
+ return PropertyInfo(Variant::REAL, "to");
+ else
+ return PropertyInfo(Variant::REAL, "delta");
+ } break;
case MATH_DECTIME: {
if (p_idx == 0)
return PropertyInfo(Variant::REAL, "value");
@@ -355,12 +362,8 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
else
return PropertyInfo(Variant::REAL, "step");
} break;
- case MATH_RANDOMIZE: {
-
- } break;
- case MATH_RAND: {
-
- } break;
+ case MATH_RANDOMIZE:
+ case MATH_RAND:
case MATH_RANDF: {
} break;
@@ -370,9 +373,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
else
return PropertyInfo(Variant::REAL, "to");
} break;
- case MATH_SEED: {
- return PropertyInfo(Variant::INT, "seed");
- } break;
+ case MATH_SEED:
case MATH_RANDSEED: {
return PropertyInfo(Variant::INT, "seed");
} break;
@@ -408,26 +409,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
else
return PropertyInfo(Variant::INT, "max");
} break;
- case MATH_WRAPF: {
- if (p_idx == 0)
- return PropertyInfo(Variant::REAL, "value");
- else if (p_idx == 1)
- return PropertyInfo(Variant::REAL, "min");
- else
- return PropertyInfo(Variant::REAL, "max");
- } break;
- case LOGIC_MAX: {
- if (p_idx == 0)
- return PropertyInfo(Variant::REAL, "a");
- else
- return PropertyInfo(Variant::REAL, "b");
- } break;
- case LOGIC_MIN: {
- if (p_idx == 0)
- return PropertyInfo(Variant::REAL, "a");
- else
- return PropertyInfo(Variant::REAL, "b");
- } break;
+ case MATH_WRAPF:
case LOGIC_CLAMP: {
if (p_idx == 0)
return PropertyInfo(Variant::REAL, "value");
@@ -440,20 +422,15 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
return PropertyInfo(Variant::INT, "value");
} break;
case OBJ_WEAKREF: {
-
return PropertyInfo(Variant::OBJECT, "source");
-
} break;
case FUNC_FUNCREF: {
-
if (p_idx == 0)
return PropertyInfo(Variant::OBJECT, "instance");
else
return PropertyInfo(Variant::STRING, "funcname");
-
} break;
case TYPE_CONVERT: {
-
if (p_idx == 0)
return PropertyInfo(Variant::NIL, "what");
else
@@ -461,45 +438,24 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
} break;
case TYPE_OF: {
return PropertyInfo(Variant::NIL, "what");
-
} break;
case TYPE_EXISTS: {
-
return PropertyInfo(Variant::STRING, "type");
-
} break;
case TEXT_CHAR: {
-
return PropertyInfo(Variant::INT, "ascii");
-
- } break;
- case TEXT_STR: {
-
- return PropertyInfo(Variant::NIL, "value");
-
- } break;
- case TEXT_PRINT: {
-
- return PropertyInfo(Variant::NIL, "value");
-
- } break;
- case TEXT_PRINTERR: {
- return PropertyInfo(Variant::NIL, "value");
-
} break;
+ case TEXT_STR:
+ case TEXT_PRINT:
+ case TEXT_PRINTERR:
case TEXT_PRINTRAW: {
-
return PropertyInfo(Variant::NIL, "value");
-
- } break;
- case VAR_TO_STR: {
- return PropertyInfo(Variant::NIL, "var");
-
} break;
case STR_TO_VAR: {
return PropertyInfo(Variant::STRING, "string");
} break;
+ case VAR_TO_STR:
case VAR_TO_BYTES: {
if (p_idx == 0)
return PropertyInfo(Variant::NIL, "var");
@@ -515,12 +471,10 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
return PropertyInfo(Variant::BOOL, "allow_objects");
} break;
case COLORN: {
-
if (p_idx == 0)
return PropertyInfo(Variant::STRING, "name");
else
return PropertyInfo(Variant::REAL, "alpha");
-
} break;
case FUNC_MAX: {
}
@@ -551,6 +505,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons
case MATH_CEIL: {
t = Variant::REAL;
} break;
+ case MATH_POSMOD:
case MATH_ROUND: {
t = Variant::INT;
} break;
@@ -580,6 +535,7 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons
case MATH_INVERSE_LERP:
case MATH_RANGE_LERP:
case MATH_SMOOTHSTEP:
+ case MATH_MOVE_TOWARD:
case MATH_DECTIME: {
t = Variant::REAL;
@@ -795,6 +751,12 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
VALIDATE_ARG_NUM(1);
*r_return = Math::fposmod((double)*p_inputs[0], (double)*p_inputs[1]);
} break;
+ case VisualScriptBuiltinFunc::MATH_POSMOD: {
+
+ VALIDATE_ARG_NUM(0);
+ VALIDATE_ARG_NUM(1);
+ *r_return = Math::posmod((int)*p_inputs[0], (int)*p_inputs[1]);
+ } break;
case VisualScriptBuiltinFunc::MATH_FLOOR: {
VALIDATE_ARG_NUM(0);
@@ -916,6 +878,13 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in
VALIDATE_ARG_NUM(2);
*r_return = Math::smoothstep((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
} break;
+ case VisualScriptBuiltinFunc::MATH_MOVE_TOWARD: {
+
+ VALIDATE_ARG_NUM(0);
+ VALIDATE_ARG_NUM(1);
+ VALIDATE_ARG_NUM(2);
+ *r_return = Math::move_toward((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
+ } break;
case VisualScriptBuiltinFunc::MATH_DECTIME: {
VALIDATE_ARG_NUM(0);
@@ -1347,6 +1316,7 @@ void VisualScriptBuiltinFunc::_bind_methods() {
BIND_ENUM_CONSTANT(MATH_SQRT);
BIND_ENUM_CONSTANT(MATH_FMOD);
BIND_ENUM_CONSTANT(MATH_FPOSMOD);
+ BIND_ENUM_CONSTANT(MATH_POSMOD);
BIND_ENUM_CONSTANT(MATH_FLOOR);
BIND_ENUM_CONSTANT(MATH_CEIL);
BIND_ENUM_CONSTANT(MATH_ROUND);
@@ -1363,6 +1333,7 @@ void VisualScriptBuiltinFunc::_bind_methods() {
BIND_ENUM_CONSTANT(MATH_LERP);
BIND_ENUM_CONSTANT(MATH_INVERSE_LERP);
BIND_ENUM_CONSTANT(MATH_RANGE_LERP);
+ BIND_ENUM_CONSTANT(MATH_MOVE_TOWARD);
BIND_ENUM_CONSTANT(MATH_DECTIME);
BIND_ENUM_CONSTANT(MATH_RANDOMIZE);
BIND_ENUM_CONSTANT(MATH_RAND);
@@ -1435,6 +1406,7 @@ void register_visual_script_builtin_func_node() {
VisualScriptLanguage::singleton->add_register_func("functions/built_in/sqrt", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SQRT>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/fmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FMOD>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/fposmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FPOSMOD>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/posmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_POSMOD>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/floor", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FLOOR>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/ceil", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_CEIL>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/round", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ROUND>);
@@ -1453,6 +1425,7 @@ void register_visual_script_builtin_func_node() {
VisualScriptLanguage::singleton->add_register_func("functions/built_in/inverse_lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_INVERSE_LERP>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/range_lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANGE_LERP>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/smoothstep", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SMOOTHSTEP>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/move_toward", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_MOVE_TOWARD>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/dectime", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DECTIME>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/randomize", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDOMIZE>);
VisualScriptLanguage::singleton->add_register_func("functions/built_in/rand", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RAND>);
diff --git a/modules/visual_script/visual_script_builtin_funcs.h b/modules/visual_script/visual_script_builtin_funcs.h
index 50854c16b1..7821e0eb2d 100644
--- a/modules/visual_script/visual_script_builtin_funcs.h
+++ b/modules/visual_script/visual_script_builtin_funcs.h
@@ -35,7 +35,8 @@
class VisualScriptBuiltinFunc : public VisualScriptNode {
- GDCLASS(VisualScriptBuiltinFunc, VisualScriptNode)
+ GDCLASS(VisualScriptBuiltinFunc, VisualScriptNode);
+
public:
enum BuiltinFunc {
MATH_SIN,
@@ -67,6 +68,7 @@ public:
MATH_LERP,
MATH_INVERSE_LERP,
MATH_RANGE_LERP,
+ MATH_MOVE_TOWARD,
MATH_DECTIME,
MATH_RANDOMIZE,
MATH_RAND,
@@ -102,6 +104,7 @@ public:
BYTES_TO_VAR,
COLORN,
MATH_SMOOTHSTEP,
+ MATH_POSMOD,
FUNC_MAX
};
diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp
index 6bbfb1ec5c..31d5e4665a 100644
--- a/modules/visual_script/visual_script_editor.cpp
+++ b/modules/visual_script/visual_script_editor.cpp
@@ -46,7 +46,7 @@
#ifdef TOOLS_ENABLED
class VisualScriptEditorSignalEdit : public Object {
- GDCLASS(VisualScriptEditorSignalEdit, Object)
+ GDCLASS(VisualScriptEditorSignalEdit, Object);
StringName sig;
@@ -186,7 +186,7 @@ public:
class VisualScriptEditorVariableEdit : public Object {
- GDCLASS(VisualScriptEditorVariableEdit, Object)
+ GDCLASS(VisualScriptEditorVariableEdit, Object);
StringName var;
@@ -341,74 +341,74 @@ static Color _color_from_type(Variant::Type p_type, bool dark_theme = true) {
Color color;
if (dark_theme)
switch (p_type) {
- case Variant::NIL: color = Color::html("#69ecbd"); break;
-
- case Variant::BOOL: color = Color::html("#8da6f0"); break;
- case Variant::INT: color = Color::html("#7dc6ef"); break;
- case Variant::REAL: color = Color::html("#61daf4"); break;
- case Variant::STRING: color = Color::html("#6ba7ec"); break;
-
- case Variant::VECTOR2: color = Color::html("#bd91f1"); break;
- case Variant::RECT2: color = Color::html("#f191a5"); break;
- case Variant::VECTOR3: color = Color::html("#d67dee"); break;
- case Variant::TRANSFORM2D: color = Color::html("#c4ec69"); break;
- case Variant::PLANE: color = Color::html("#f77070"); break;
- case Variant::QUAT: color = Color::html("#ec69a3"); break;
- case Variant::AABB: color = Color::html("#ee7991"); break;
- case Variant::BASIS: color = Color::html("#e3ec69"); break;
- case Variant::TRANSFORM: color = Color::html("#f6a86e"); break;
-
- case Variant::COLOR: color = Color::html("#9dff70"); break;
- case Variant::NODE_PATH: color = Color::html("#6993ec"); break;
- case Variant::_RID: color = Color::html("#69ec9a"); break;
- case Variant::OBJECT: color = Color::html("#79f3e8"); break;
- case Variant::DICTIONARY: color = Color::html("#77edb1"); break;
-
- case Variant::ARRAY: color = Color::html("#e0e0e0"); break;
- case Variant::POOL_BYTE_ARRAY: color = Color::html("#aaf4c8"); break;
- case Variant::POOL_INT_ARRAY: color = Color::html("#afdcf5"); break;
- case Variant::POOL_REAL_ARRAY: color = Color::html("#97e7f8"); break;
- case Variant::POOL_STRING_ARRAY: color = Color::html("#9dc4f2"); break;
- case Variant::POOL_VECTOR2_ARRAY: color = Color::html("#d1b3f5"); break;
- case Variant::POOL_VECTOR3_ARRAY: color = Color::html("#df9bf2"); break;
- case Variant::POOL_COLOR_ARRAY: color = Color::html("#e9ff97"); break;
+ case Variant::NIL: color = Color(0.41, 0.93, 0.74); break;
+
+ case Variant::BOOL: color = Color(0.55, 0.65, 0.94); break;
+ case Variant::INT: color = Color(0.49, 0.78, 0.94); break;
+ case Variant::REAL: color = Color(0.38, 0.85, 0.96); break;
+ case Variant::STRING: color = Color(0.42, 0.65, 0.93); break;
+
+ case Variant::VECTOR2: color = Color(0.74, 0.57, 0.95); break;
+ case Variant::RECT2: color = Color(0.95, 0.57, 0.65); break;
+ case Variant::VECTOR3: color = Color(0.84, 0.49, 0.93); break;
+ case Variant::TRANSFORM2D: color = Color(0.77, 0.93, 0.41); break;
+ case Variant::PLANE: color = Color(0.97, 0.44, 0.44); break;
+ case Variant::QUAT: color = Color(0.93, 0.41, 0.64); break;
+ case Variant::AABB: color = Color(0.93, 0.47, 0.57); break;
+ case Variant::BASIS: color = Color(0.89, 0.93, 0.41); break;
+ case Variant::TRANSFORM: color = Color(0.96, 0.66, 0.43); break;
+
+ case Variant::COLOR: color = Color(0.62, 1.0, 0.44); break;
+ case Variant::NODE_PATH: color = Color(0.41, 0.58, 0.93); break;
+ case Variant::_RID: color = Color(0.41, 0.93, 0.6); break;
+ case Variant::OBJECT: color = Color(0.47, 0.95, 0.91); break;
+ case Variant::DICTIONARY: color = Color(0.47, 0.93, 0.69); break;
+
+ case Variant::ARRAY: color = Color(0.88, 0.88, 0.88); break;
+ case Variant::POOL_BYTE_ARRAY: color = Color(0.67, 0.96, 0.78); break;
+ case Variant::POOL_INT_ARRAY: color = Color(0.69, 0.86, 0.96); break;
+ case Variant::POOL_REAL_ARRAY: color = Color(0.59, 0.91, 0.97); break;
+ case Variant::POOL_STRING_ARRAY: color = Color(0.62, 0.77, 0.95); break;
+ case Variant::POOL_VECTOR2_ARRAY: color = Color(0.82, 0.7, 0.96); break;
+ case Variant::POOL_VECTOR3_ARRAY: color = Color(0.87, 0.61, 0.95); break;
+ case Variant::POOL_COLOR_ARRAY: color = Color(0.91, 1.0, 0.59); break;
default:
color.set_hsv(p_type / float(Variant::VARIANT_MAX), 0.7, 0.7);
}
else
switch (p_type) {
- case Variant::NIL: color = Color::html("#25e3a0"); break;
-
- case Variant::BOOL: color = Color::html("#6d8eeb"); break;
- case Variant::INT: color = Color::html("#4fb2e9"); break;
- case Variant::REAL: color = Color::html("#27ccf0"); break;
- case Variant::STRING: color = Color::html("#4690e7"); break;
-
- case Variant::VECTOR2: color = Color::html("#ad76ee"); break;
- case Variant::RECT2: color = Color::html("#ee758e"); break;
- case Variant::VECTOR3: color = Color::html("#dc6aed"); break;
- case Variant::TRANSFORM2D: color = Color::html("#96ce1a"); break;
- case Variant::PLANE: color = Color::html("#f77070"); break;
- case Variant::QUAT: color = Color::html("#ec69a3"); break;
- case Variant::AABB: color = Color::html("#ee7991"); break;
- case Variant::BASIS: color = Color::html("#b2bb19"); break;
- case Variant::TRANSFORM: color = Color::html("#f49047"); break;
-
- case Variant::COLOR: color = Color::html("#3cbf00"); break;
- case Variant::NODE_PATH: color = Color::html("#6993ec"); break;
- case Variant::_RID: color = Color::html("#2ce573"); break;
- case Variant::OBJECT: color = Color::html("#12d5c3"); break;
- case Variant::DICTIONARY: color = Color::html("#57e99f"); break;
-
- case Variant::ARRAY: color = Color::html("#737373"); break;
- case Variant::POOL_BYTE_ARRAY: color = Color::html("#61ea98"); break;
- case Variant::POOL_INT_ARRAY: color = Color::html("#61baeb"); break;
- case Variant::POOL_REAL_ARRAY: color = Color::html("#40d3f2"); break;
- case Variant::POOL_STRING_ARRAY: color = Color::html("#609fea"); break;
- case Variant::POOL_VECTOR2_ARRAY: color = Color::html("#9d5dea"); break;
- case Variant::POOL_VECTOR3_ARRAY: color = Color::html("#ca5aea"); break;
- case Variant::POOL_COLOR_ARRAY: color = Color::html("#92ba00"); break;
+ case Variant::NIL: color = Color(0.15, 0.89, 0.63); break;
+
+ case Variant::BOOL: color = Color(0.43, 0.56, 0.92); break;
+ case Variant::INT: color = Color(0.31, 0.7, 0.91); break;
+ case Variant::REAL: color = Color(0.15, 0.8, 0.94); break;
+ case Variant::STRING: color = Color(0.27, 0.56, 0.91); break;
+
+ case Variant::VECTOR2: color = Color(0.68, 0.46, 0.93); break;
+ case Variant::RECT2: color = Color(0.93, 0.46, 0.56); break;
+ case Variant::VECTOR3: color = Color(0.86, 0.42, 0.93); break;
+ case Variant::TRANSFORM2D: color = Color(0.59, 0.81, 0.1); break;
+ case Variant::PLANE: color = Color(0.97, 0.44, 0.44); break;
+ case Variant::QUAT: color = Color(0.93, 0.41, 0.64); break;
+ case Variant::AABB: color = Color(0.93, 0.47, 0.57); break;
+ case Variant::BASIS: color = Color(0.7, 0.73, 0.1); break;
+ case Variant::TRANSFORM: color = Color(0.96, 0.56, 0.28); break;
+
+ case Variant::COLOR: color = Color(0.24, 0.75, 0.0); break;
+ case Variant::NODE_PATH: color = Color(0.41, 0.58, 0.93); break;
+ case Variant::_RID: color = Color(0.17, 0.9, 0.45); break;
+ case Variant::OBJECT: color = Color(0.07, 0.84, 0.76); break;
+ case Variant::DICTIONARY: color = Color(0.34, 0.91, 0.62); break;
+
+ case Variant::ARRAY: color = Color(0.45, 0.45, 0.45); break;
+ case Variant::POOL_BYTE_ARRAY: color = Color(0.38, 0.92, 0.6); break;
+ case Variant::POOL_INT_ARRAY: color = Color(0.38, 0.73, 0.92); break;
+ case Variant::POOL_REAL_ARRAY: color = Color(0.25, 0.83, 0.95); break;
+ case Variant::POOL_STRING_ARRAY: color = Color(0.38, 0.62, 0.92); break;
+ case Variant::POOL_VECTOR2_ARRAY: color = Color(0.62, 0.36, 0.92); break;
+ case Variant::POOL_VECTOR3_ARRAY: color = Color(0.79, 0.35, 0.92); break;
+ case Variant::POOL_COLOR_ARRAY: color = Color(0.57, 0.73, 0.0); break;
default:
color.set_hsv(p_type / float(Variant::VARIANT_MAX), 0.3, 0.3);
@@ -1099,6 +1099,9 @@ void VisualScriptEditor::_expression_text_changed(const String &p_text, int p_id
void VisualScriptEditor::_available_node_doubleclicked() {
+ if (edited_func == String())
+ return;
+
TreeItem *item = nodes->get_selected();
if (!item)
@@ -1107,7 +1110,6 @@ void VisualScriptEditor::_available_node_doubleclicked() {
String which = item->get_metadata(0);
if (which == String())
return;
-
Vector2 ofs = graph->get_scroll_ofs() + graph->get_size() * 0.5;
if (graph->is_using_snap()) {
@@ -2111,6 +2113,9 @@ void VisualScriptEditor::clear_executing_line() {
void VisualScriptEditor::trim_trailing_whitespace() {
}
+void VisualScriptEditor::insert_final_newline() {
+}
+
void VisualScriptEditor::convert_indent_to_spaces() {
}
@@ -3049,19 +3054,19 @@ void VisualScriptEditor::_notification(int p_what) {
List<Pair<String, Color> > colors;
if (dark_theme) {
- colors.push_back(Pair<String, Color>("flow_control", Color::html("#f4f4f4")));
- colors.push_back(Pair<String, Color>("functions", Color::html("#f58581")));
- colors.push_back(Pair<String, Color>("data", Color::html("#80f6cf")));
- colors.push_back(Pair<String, Color>("operators", Color::html("#ab97df")));
- colors.push_back(Pair<String, Color>("custom", Color::html("#80bbf6")));
- colors.push_back(Pair<String, Color>("constants", Color::html("#f680b0")));
+ colors.push_back(Pair<String, Color>("flow_control", Color(0.96, 0.96, 0.96)));
+ colors.push_back(Pair<String, Color>("functions", Color(0.96, 0.52, 0.51)));
+ colors.push_back(Pair<String, Color>("data", Color(0.5, 0.96, 0.81)));
+ colors.push_back(Pair<String, Color>("operators", Color(0.67, 0.59, 0.87)));
+ colors.push_back(Pair<String, Color>("custom", Color(0.5, 0.73, 0.96)));
+ colors.push_back(Pair<String, Color>("constants", Color(0.96, 0.5, 0.69)));
} else {
- colors.push_back(Pair<String, Color>("flow_control", Color::html("#424242")));
- colors.push_back(Pair<String, Color>("functions", Color::html("#f26661")));
- colors.push_back(Pair<String, Color>("data", Color::html("#13bb83")));
- colors.push_back(Pair<String, Color>("operators", Color::html("#8265d0")));
- colors.push_back(Pair<String, Color>("custom", Color::html("#4ea0f2")));
- colors.push_back(Pair<String, Color>("constants", Color::html("#f02f7d")));
+ colors.push_back(Pair<String, Color>("flow_control", Color(0.26, 0.26, 0.26)));
+ colors.push_back(Pair<String, Color>("functions", Color(0.95, 0.4, 0.38)));
+ colors.push_back(Pair<String, Color>("data", Color(0.07, 0.73, 0.51)));
+ colors.push_back(Pair<String, Color>("operators", Color(0.51, 0.4, 0.82)));
+ colors.push_back(Pair<String, Color>("custom", Color(0.31, 0.63, 0.95)));
+ colors.push_back(Pair<String, Color>("constants", Color(0.94, 0.18, 0.49)));
}
for (List<Pair<String, Color> >::Element *E = colors.front(); E; E = E->next()) {
@@ -3619,7 +3624,6 @@ VisualScriptEditor::VisualScriptEditor() {
edit_signal_dialog = memnew(AcceptDialog);
edit_signal_dialog->get_ok()->set_text(TTR("Close"));
add_child(edit_signal_dialog);
- edit_signal_dialog->set_title(TTR("Edit Signal Arguments:"));
signal_editor = memnew(VisualScriptEditorSignalEdit);
edit_signal_edit = memnew(EditorInspector);
@@ -3630,7 +3634,6 @@ VisualScriptEditor::VisualScriptEditor() {
edit_variable_dialog = memnew(AcceptDialog);
edit_variable_dialog->get_ok()->set_text(TTR("Close"));
add_child(edit_variable_dialog);
- edit_variable_dialog->set_title(TTR("Edit Variable:"));
variable_editor = memnew(VisualScriptEditorVariableEdit);
edit_variable_edit = memnew(EditorInspector);
@@ -3641,7 +3644,6 @@ VisualScriptEditor::VisualScriptEditor() {
select_base_type = memnew(CreateDialog);
select_base_type->set_base_type("Object"); //anything goes
select_base_type->connect("create", this, "_change_base_type_callback");
- select_base_type->get_ok()->set_text(TTR("Change"));
add_child(select_base_type);
undo_redo = EditorNode::get_singleton()->get_undo_redo();
@@ -3759,4 +3761,7 @@ void _VisualScriptEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("remove_custom_node", "name", "category"), &_VisualScriptEditor::remove_custom_node);
ADD_SIGNAL(MethodInfo("custom_nodes_updated"));
}
+
+void VisualScriptEditor::validate() {
+}
#endif
diff --git a/modules/visual_script/visual_script_editor.h b/modules/visual_script/visual_script_editor.h
index 3d3a49f672..4f302d1d72 100644
--- a/modules/visual_script/visual_script_editor.h
+++ b/modules/visual_script/visual_script_editor.h
@@ -44,7 +44,7 @@ class VisualScriptEditorVariableEdit;
#ifdef TOOLS_ENABLED
class VisualScriptEditor : public ScriptEditorBase {
- GDCLASS(VisualScriptEditor, ScriptEditorBase)
+ GDCLASS(VisualScriptEditor, ScriptEditorBase);
enum {
TYPE_SEQUENCE = 1000,
@@ -266,6 +266,7 @@ public:
virtual void set_executing_line(int p_line);
virtual void clear_executing_line();
virtual void trim_trailing_whitespace();
+ virtual void insert_final_newline();
virtual void convert_indent_to_spaces();
virtual void convert_indent_to_tabs();
virtual void ensure_focus();
@@ -280,6 +281,7 @@ public:
virtual Control *get_edit_menu();
virtual void clear_edit_menu();
virtual bool can_lose_focus_on_node_selection() { return false; }
+ virtual void validate();
static void register_editor();
diff --git a/modules/visual_script/visual_script_expression.cpp b/modules/visual_script/visual_script_expression.cpp
index 772092fabe..4b74c088e0 100644
--- a/modules/visual_script/visual_script_expression.cpp
+++ b/modules/visual_script/visual_script_expression.cpp
@@ -1130,7 +1130,7 @@ VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
if (next_op == -1) {
_set_error("Yet another parser bug....");
- ERR_FAIL_COND_V(next_op == -1, NULL);
+ ERR_FAIL_V(NULL);
}
// OK! create operator..
diff --git a/modules/visual_script/visual_script_expression.h b/modules/visual_script/visual_script_expression.h
index 3b2e3b9f78..3a045d2cf7 100644
--- a/modules/visual_script/visual_script_expression.h
+++ b/modules/visual_script/visual_script_expression.h
@@ -36,7 +36,7 @@
class VisualScriptExpression : public VisualScriptNode {
- GDCLASS(VisualScriptExpression, VisualScriptNode)
+ GDCLASS(VisualScriptExpression, VisualScriptNode);
friend class VisualScriptNodeInstanceExpression;
struct Input {
diff --git a/modules/visual_script/visual_script_flow_control.h b/modules/visual_script/visual_script_flow_control.h
index a42605a50e..d3c7aa68e3 100644
--- a/modules/visual_script/visual_script_flow_control.h
+++ b/modules/visual_script/visual_script_flow_control.h
@@ -35,7 +35,7 @@
class VisualScriptReturn : public VisualScriptNode {
- GDCLASS(VisualScriptReturn, VisualScriptNode)
+ GDCLASS(VisualScriptReturn, VisualScriptNode);
Variant::Type type;
bool with_value;
@@ -72,7 +72,7 @@ public:
class VisualScriptCondition : public VisualScriptNode {
- GDCLASS(VisualScriptCondition, VisualScriptNode)
+ GDCLASS(VisualScriptCondition, VisualScriptNode);
protected:
static void _bind_methods();
@@ -100,7 +100,7 @@ public:
class VisualScriptWhile : public VisualScriptNode {
- GDCLASS(VisualScriptWhile, VisualScriptNode)
+ GDCLASS(VisualScriptWhile, VisualScriptNode);
protected:
static void _bind_methods();
@@ -128,7 +128,7 @@ public:
class VisualScriptIterator : public VisualScriptNode {
- GDCLASS(VisualScriptIterator, VisualScriptNode)
+ GDCLASS(VisualScriptIterator, VisualScriptNode);
protected:
static void _bind_methods();
@@ -156,7 +156,7 @@ public:
class VisualScriptSequence : public VisualScriptNode {
- GDCLASS(VisualScriptSequence, VisualScriptNode)
+ GDCLASS(VisualScriptSequence, VisualScriptNode);
int steps;
@@ -189,7 +189,7 @@ public:
class VisualScriptSwitch : public VisualScriptNode {
- GDCLASS(VisualScriptSwitch, VisualScriptNode)
+ GDCLASS(VisualScriptSwitch, VisualScriptNode);
struct Case {
Variant::Type type;
@@ -231,7 +231,7 @@ public:
class VisualScriptTypeCast : public VisualScriptNode {
- GDCLASS(VisualScriptTypeCast, VisualScriptNode)
+ GDCLASS(VisualScriptTypeCast, VisualScriptNode);
StringName base_type;
String script;
diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp
index 8fa7d2c0d4..c330fa1bc0 100644
--- a/modules/visual_script/visual_script_func_nodes.cpp
+++ b/modules/visual_script/visual_script_func_nodes.cpp
@@ -51,10 +51,7 @@ int VisualScriptFunctionCall::get_output_sequence_port_count() const {
bool VisualScriptFunctionCall::has_input_sequence_port() const {
- if ((method_cache.flags & METHOD_FLAG_CONST && call_mode != CALL_MODE_INSTANCE) || (call_mode == CALL_MODE_BASIC_TYPE && Variant::is_method_const(basic_type, function)))
- return false;
- else
- return true;
+ return !((method_cache.flags & METHOD_FLAG_CONST && call_mode != CALL_MODE_INSTANCE) || (call_mode == CALL_MODE_BASIC_TYPE && Variant::is_method_const(basic_type, function)));
}
#ifdef TOOLS_ENABLED
@@ -573,7 +570,6 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const
Node *bnode = _get_base_node();
if (bnode) {
property.hint_string = bnode->get_path(); //convert to loong string
- } else {
}
}
}
@@ -949,7 +945,7 @@ int VisualScriptPropertySet::get_output_sequence_port_count() const {
bool VisualScriptPropertySet::has_input_sequence_port() const {
- return call_mode != CALL_MODE_BASIC_TYPE ? true : false;
+ return call_mode != CALL_MODE_BASIC_TYPE;
}
Node *VisualScriptPropertySet::_get_base_node() const {
@@ -1030,7 +1026,6 @@ void VisualScriptPropertySet::_adjust_input_index(PropertyInfo &pinfo) const {
}
PropertyInfo VisualScriptPropertySet::get_input_value_port_info(int p_idx) const {
-
if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) {
if (p_idx == 0) {
PropertyInfo pi;
@@ -1038,8 +1033,16 @@ PropertyInfo VisualScriptPropertySet::get_input_value_port_info(int p_idx) const
pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower());
_adjust_input_index(pi);
return pi;
- } else {
- p_idx--;
+ }
+ }
+
+ List<PropertyInfo> props;
+ ClassDB::get_property_list(_get_base_type(), &props, true);
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
+ if (E->get().name == property) {
+ PropertyInfo pinfo = PropertyInfo(E->get().type, "value", PROPERTY_HINT_TYPE_STRING, E->get().hint_string);
+ _adjust_input_index(pinfo);
+ return pinfo;
}
}
@@ -1053,6 +1056,13 @@ PropertyInfo VisualScriptPropertySet::get_output_value_port_info(int p_idx) cons
if (call_mode == CALL_MODE_BASIC_TYPE) {
return PropertyInfo(basic_type, "out");
} else if (call_mode == CALL_MODE_INSTANCE) {
+ List<PropertyInfo> props;
+ ClassDB::get_property_list(_get_base_type(), &props, true);
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
+ if (E->get().name == property) {
+ return PropertyInfo(E->get().type, "pass", PROPERTY_HINT_TYPE_STRING, E->get().hint_string);
+ }
+ }
return PropertyInfo(Variant::OBJECT, "pass", PROPERTY_HINT_TYPE_STRING, get_base_type());
} else {
return PropertyInfo();
@@ -1355,7 +1365,6 @@ void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const {
Node *bnode = _get_base_node();
if (bnode) {
property.hint_string = bnode->get_path(); //convert to loong string
- } else {
}
}
}
@@ -1797,22 +1806,18 @@ PropertyInfo VisualScriptPropertyGet::get_input_value_port_info(int p_idx) const
pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type);
pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower());
return pi;
- } else {
- p_idx--;
}
}
return PropertyInfo();
}
PropertyInfo VisualScriptPropertyGet::get_output_value_port_info(int p_idx) const {
-
- if (index != StringName()) {
-
- Variant v;
- Variant::CallError ce;
- v = Variant::construct(type_cache, NULL, 0, ce);
- Variant i = v.get(index);
- return PropertyInfo(i.get_type(), "value." + String(index));
+ List<PropertyInfo> props;
+ ClassDB::get_property_list(_get_base_type(), &props, true);
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
+ if (E->get().name == property) {
+ return PropertyInfo(E->get().type, "value." + String(index));
+ }
}
return PropertyInfo(type_cache, "value");
@@ -2076,7 +2081,6 @@ void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const {
Node *bnode = _get_base_node();
if (bnode) {
property.hint_string = bnode->get_path(); //convert to loong string
- } else {
}
}
}
diff --git a/modules/visual_script/visual_script_func_nodes.h b/modules/visual_script/visual_script_func_nodes.h
index 7b1e7871b6..11eb96293b 100644
--- a/modules/visual_script/visual_script_func_nodes.h
+++ b/modules/visual_script/visual_script_func_nodes.h
@@ -35,7 +35,8 @@
class VisualScriptFunctionCall : public VisualScriptNode {
- GDCLASS(VisualScriptFunctionCall, VisualScriptNode)
+ GDCLASS(VisualScriptFunctionCall, VisualScriptNode);
+
public:
enum CallMode {
CALL_MODE_SELF,
@@ -137,7 +138,8 @@ VARIANT_ENUM_CAST(VisualScriptFunctionCall::RPCCallMode);
class VisualScriptPropertySet : public VisualScriptNode {
- GDCLASS(VisualScriptPropertySet, VisualScriptNode)
+ GDCLASS(VisualScriptPropertySet, VisualScriptNode);
+
public:
enum CallMode {
CALL_MODE_SELF,
@@ -242,7 +244,8 @@ VARIANT_ENUM_CAST(VisualScriptPropertySet::AssignOp);
class VisualScriptPropertyGet : public VisualScriptNode {
- GDCLASS(VisualScriptPropertyGet, VisualScriptNode)
+ GDCLASS(VisualScriptPropertyGet, VisualScriptNode);
+
public:
enum CallMode {
CALL_MODE_SELF,
@@ -323,7 +326,7 @@ VARIANT_ENUM_CAST(VisualScriptPropertyGet::CallMode);
class VisualScriptEmitSignal : public VisualScriptNode {
- GDCLASS(VisualScriptEmitSignal, VisualScriptNode)
+ GDCLASS(VisualScriptEmitSignal, VisualScriptNode);
private:
StringName name;
diff --git a/modules/visual_script/visual_script_nodes.h b/modules/visual_script/visual_script_nodes.h
index b3d199fb38..762a1bdfb6 100644
--- a/modules/visual_script/visual_script_nodes.h
+++ b/modules/visual_script/visual_script_nodes.h
@@ -35,7 +35,7 @@
class VisualScriptFunction : public VisualScriptNode {
- GDCLASS(VisualScriptFunction, VisualScriptNode)
+ GDCLASS(VisualScriptFunction, VisualScriptNode);
struct Argument {
String name;
@@ -105,7 +105,7 @@ public:
class VisualScriptOperator : public VisualScriptNode {
- GDCLASS(VisualScriptOperator, VisualScriptNode)
+ GDCLASS(VisualScriptOperator, VisualScriptNode);
Variant::Type typed;
Variant::Operator op;
@@ -141,7 +141,7 @@ public:
class VisualScriptSelect : public VisualScriptNode {
- GDCLASS(VisualScriptSelect, VisualScriptNode)
+ GDCLASS(VisualScriptSelect, VisualScriptNode);
Variant::Type typed;
@@ -174,7 +174,7 @@ public:
class VisualScriptVariableGet : public VisualScriptNode {
- GDCLASS(VisualScriptVariableGet, VisualScriptNode)
+ GDCLASS(VisualScriptVariableGet, VisualScriptNode);
StringName variable;
@@ -207,7 +207,7 @@ public:
class VisualScriptVariableSet : public VisualScriptNode {
- GDCLASS(VisualScriptVariableSet, VisualScriptNode)
+ GDCLASS(VisualScriptVariableSet, VisualScriptNode);
StringName variable;
@@ -240,7 +240,7 @@ public:
class VisualScriptConstant : public VisualScriptNode {
- GDCLASS(VisualScriptConstant, VisualScriptNode)
+ GDCLASS(VisualScriptConstant, VisualScriptNode);
Variant::Type type;
Variant value;
@@ -277,7 +277,7 @@ public:
class VisualScriptPreload : public VisualScriptNode {
- GDCLASS(VisualScriptPreload, VisualScriptNode)
+ GDCLASS(VisualScriptPreload, VisualScriptNode);
Ref<Resource> preload;
@@ -309,7 +309,7 @@ public:
class VisualScriptIndexGet : public VisualScriptNode {
- GDCLASS(VisualScriptIndexGet, VisualScriptNode)
+ GDCLASS(VisualScriptIndexGet, VisualScriptNode);
public:
virtual int get_output_sequence_port_count() const;
@@ -333,7 +333,7 @@ public:
class VisualScriptIndexSet : public VisualScriptNode {
- GDCLASS(VisualScriptIndexSet, VisualScriptNode)
+ GDCLASS(VisualScriptIndexSet, VisualScriptNode);
public:
virtual int get_output_sequence_port_count() const;
@@ -357,7 +357,7 @@ public:
class VisualScriptGlobalConstant : public VisualScriptNode {
- GDCLASS(VisualScriptGlobalConstant, VisualScriptNode)
+ GDCLASS(VisualScriptGlobalConstant, VisualScriptNode);
int index;
@@ -388,7 +388,7 @@ public:
class VisualScriptClassConstant : public VisualScriptNode {
- GDCLASS(VisualScriptClassConstant, VisualScriptNode)
+ GDCLASS(VisualScriptClassConstant, VisualScriptNode);
StringName base_type;
StringName name;
@@ -425,7 +425,7 @@ public:
class VisualScriptBasicTypeConstant : public VisualScriptNode {
- GDCLASS(VisualScriptBasicTypeConstant, VisualScriptNode)
+ GDCLASS(VisualScriptBasicTypeConstant, VisualScriptNode);
Variant::Type type;
StringName name;
@@ -463,7 +463,8 @@ public:
class VisualScriptMathConstant : public VisualScriptNode {
- GDCLASS(VisualScriptMathConstant, VisualScriptNode)
+ GDCLASS(VisualScriptMathConstant, VisualScriptNode);
+
public:
enum MathConstant {
MATH_CONSTANT_ONE,
@@ -512,7 +513,7 @@ VARIANT_ENUM_CAST(VisualScriptMathConstant::MathConstant)
class VisualScriptEngineSingleton : public VisualScriptNode {
- GDCLASS(VisualScriptEngineSingleton, VisualScriptNode)
+ GDCLASS(VisualScriptEngineSingleton, VisualScriptNode);
String singleton;
@@ -545,7 +546,7 @@ public:
class VisualScriptSceneNode : public VisualScriptNode {
- GDCLASS(VisualScriptSceneNode, VisualScriptNode)
+ GDCLASS(VisualScriptSceneNode, VisualScriptNode);
NodePath path;
@@ -580,7 +581,7 @@ public:
class VisualScriptSceneTree : public VisualScriptNode {
- GDCLASS(VisualScriptSceneTree, VisualScriptNode)
+ GDCLASS(VisualScriptSceneTree, VisualScriptNode);
protected:
virtual void _validate_property(PropertyInfo &property) const;
@@ -610,7 +611,7 @@ public:
class VisualScriptResourcePath : public VisualScriptNode {
- GDCLASS(VisualScriptResourcePath, VisualScriptNode)
+ GDCLASS(VisualScriptResourcePath, VisualScriptNode);
String path;
@@ -642,7 +643,7 @@ public:
class VisualScriptSelf : public VisualScriptNode {
- GDCLASS(VisualScriptSelf, VisualScriptNode)
+ GDCLASS(VisualScriptSelf, VisualScriptNode);
protected:
static void _bind_methods();
@@ -671,7 +672,7 @@ public:
class VisualScriptCustomNode : public VisualScriptNode {
- GDCLASS(VisualScriptCustomNode, VisualScriptNode)
+ GDCLASS(VisualScriptCustomNode, VisualScriptNode);
protected:
static void _bind_methods();
@@ -719,7 +720,7 @@ VARIANT_ENUM_CAST(VisualScriptCustomNode::StartMode);
class VisualScriptSubCall : public VisualScriptNode {
- GDCLASS(VisualScriptSubCall, VisualScriptNode)
+ GDCLASS(VisualScriptSubCall, VisualScriptNode);
protected:
static void _bind_methods();
@@ -747,7 +748,7 @@ public:
class VisualScriptComment : public VisualScriptNode {
- GDCLASS(VisualScriptComment, VisualScriptNode)
+ GDCLASS(VisualScriptComment, VisualScriptNode);
String title;
String description;
@@ -788,7 +789,7 @@ public:
class VisualScriptConstructor : public VisualScriptNode {
- GDCLASS(VisualScriptConstructor, VisualScriptNode)
+ GDCLASS(VisualScriptConstructor, VisualScriptNode);
Variant::Type type;
MethodInfo constructor;
@@ -824,7 +825,7 @@ public:
class VisualScriptLocalVar : public VisualScriptNode {
- GDCLASS(VisualScriptLocalVar, VisualScriptNode)
+ GDCLASS(VisualScriptLocalVar, VisualScriptNode);
StringName name;
Variant::Type type;
@@ -860,7 +861,7 @@ public:
class VisualScriptLocalVarSet : public VisualScriptNode {
- GDCLASS(VisualScriptLocalVarSet, VisualScriptNode)
+ GDCLASS(VisualScriptLocalVarSet, VisualScriptNode);
StringName name;
Variant::Type type;
@@ -897,7 +898,8 @@ public:
class VisualScriptInputAction : public VisualScriptNode {
- GDCLASS(VisualScriptInputAction, VisualScriptNode)
+ GDCLASS(VisualScriptInputAction, VisualScriptNode);
+
public:
enum Mode {
MODE_PRESSED,
@@ -944,7 +946,7 @@ VARIANT_ENUM_CAST(VisualScriptInputAction::Mode)
class VisualScriptDeconstruct : public VisualScriptNode {
- GDCLASS(VisualScriptDeconstruct, VisualScriptNode)
+ GDCLASS(VisualScriptDeconstruct, VisualScriptNode);
struct Element {
StringName name;
diff --git a/modules/visual_script/visual_script_property_selector.cpp b/modules/visual_script/visual_script_property_selector.cpp
index ceec79c0d5..1e7ed3019c 100644
--- a/modules/visual_script/visual_script_property_selector.cpp
+++ b/modules/visual_script/visual_script_property_selector.cpp
@@ -188,7 +188,6 @@ void VisualScriptPropertySelector::_update_search() {
}
}
}
- bool script_methods = false;
{
if (type != Variant::NIL) {
Variant v;
@@ -211,7 +210,7 @@ void VisualScriptPropertySelector::_update_search() {
for (List<MethodInfo>::Element *M = methods.front(); M; M = M->next()) {
String name = M->get().name.get_slice(":", 0);
- if (!script_methods && name.begins_with("_") && !(M->get().flags & METHOD_FLAG_VIRTUAL))
+ if (name.begins_with("_") && !(M->get().flags & METHOD_FLAG_VIRTUAL))
continue;
if (virtuals_only && !(M->get().flags & METHOD_FLAG_VIRTUAL))
diff --git a/modules/visual_script/visual_script_property_selector.h b/modules/visual_script/visual_script_property_selector.h
index 1588243bc1..6235e4ba1d 100644
--- a/modules/visual_script/visual_script_property_selector.h
+++ b/modules/visual_script/visual_script_property_selector.h
@@ -36,7 +36,7 @@
#include "scene/gui/rich_text_label.h"
class VisualScriptPropertySelector : public ConfirmationDialog {
- GDCLASS(VisualScriptPropertySelector, ConfirmationDialog)
+ GDCLASS(VisualScriptPropertySelector, ConfirmationDialog);
LineEdit *search_box;
Tree *search_options;
diff --git a/modules/visual_script/visual_script_yield_nodes.cpp b/modules/visual_script/visual_script_yield_nodes.cpp
index 962560cc96..ebd0f0b3cb 100644
--- a/modules/visual_script/visual_script_yield_nodes.cpp
+++ b/modules/visual_script/visual_script_yield_nodes.cpp
@@ -431,7 +431,6 @@ void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const {
Node *bnode = _get_base_node();
if (bnode) {
property.hint_string = bnode->get_path(); //convert to loong string
- } else {
}
}
}
diff --git a/modules/visual_script/visual_script_yield_nodes.h b/modules/visual_script/visual_script_yield_nodes.h
index 851bf6aa74..647f2b1e2e 100644
--- a/modules/visual_script/visual_script_yield_nodes.h
+++ b/modules/visual_script/visual_script_yield_nodes.h
@@ -35,7 +35,8 @@
class VisualScriptYield : public VisualScriptNode {
- GDCLASS(VisualScriptYield, VisualScriptNode)
+ GDCLASS(VisualScriptYield, VisualScriptNode);
+
public:
enum YieldMode {
YIELD_RETURN,
@@ -84,7 +85,8 @@ VARIANT_ENUM_CAST(VisualScriptYield::YieldMode)
class VisualScriptYieldSignal : public VisualScriptNode {
- GDCLASS(VisualScriptYieldSignal, VisualScriptNode)
+ GDCLASS(VisualScriptYieldSignal, VisualScriptNode);
+
public:
enum CallMode {
CALL_MODE_SELF,
diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cpp
index 692705e411..2f4a45f108 100644
--- a/modules/vorbis/audio_stream_ogg_vorbis.cpp
+++ b/modules/vorbis/audio_stream_ogg_vorbis.cpp
@@ -103,7 +103,7 @@ int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_buffer, int p_frames) {
int todo = p_frames;
- if (todo == 0 || todo < MIN_MIX) {
+ if (todo < MIN_MIX) {
break;
}
@@ -143,8 +143,7 @@ int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_buffer, int p_frames) {
bool ok = ov_time_seek(&vf, loop_restart_time) == 0;
if (!ok) {
playing = false;
- //ERR_EXPLAIN("loop restart time rejected");
- ERR_PRINT("loop restart time rejected")
+ ERR_PRINT("Loop restart time rejected");
}
frames_mixed = stream_srate * loop_restart_time;
diff --git a/modules/vorbis/audio_stream_ogg_vorbis.h b/modules/vorbis/audio_stream_ogg_vorbis.h
index fa9d5fe664..a37867d9f9 100644
--- a/modules/vorbis/audio_stream_ogg_vorbis.h
+++ b/modules/vorbis/audio_stream_ogg_vorbis.h
@@ -127,7 +127,6 @@ public:
};
class ResourceFormatLoaderAudioStreamOGGVorbis : public ResourceFormatLoader {
- GDCLASS(ResourceFormatLoaderAudioStreamOGGVorbis, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/webm/config.py b/modules/webm/config.py
index 72a4073423..ba4dcce2f5 100644
--- a/modules/webm/config.py
+++ b/modules/webm/config.py
@@ -6,7 +6,6 @@ def configure(env):
def get_doc_classes():
return [
- "ResourceImporterWebm",
"VideoStreamWebm",
]
diff --git a/modules/webm/libvpx/SCsub b/modules/webm/libvpx/SCsub
index a6be1380a6..14fa6c1268 100644
--- a/modules/webm/libvpx/SCsub
+++ b/modules/webm/libvpx/SCsub
@@ -323,7 +323,7 @@ if webm_cpu_x86:
elif cpu_bits == '64':
env_libvpx["ASCPU"] = 'X86_64'
- env_libvpx.Append(CPPFLAGS=['-DWEBM_X86ASM'])
+ env_libvpx.Append(CPPDEFINES=['WEBM_X86ASM'])
webm_simd_optimizations = True
@@ -337,7 +337,7 @@ if webm_cpu_arm:
env_libvpx["ASFLAGS"] = ''
env_libvpx["ASCOM"] = '$AS $ASFLAGS -o $TARGET $SOURCES'
- env_libvpx.Append(CPPFLAGS=['-DWEBM_ARMASM'])
+ env_libvpx.Append(CPPDEFINES=['WEBM_ARMASM'])
webm_simd_optimizations = True
@@ -384,8 +384,6 @@ elif webm_cpu_arm:
env_libvpx.add_source_files(env.modules_sources, [libvpx_dir + "third_party/android/cpu-features.c"])
env_libvpx_neon = env_libvpx.Clone()
- if env["platform"] == 'android' and env["android_arch"] == 'armv6':
- env_libvpx_neon.Append(CCFLAGS=['-mfpu=neon'])
env_libvpx_neon.add_source_files(env.modules_sources, libvpx_sources_arm_neon)
if env["platform"] == 'uwp':
diff --git a/modules/webm/video_stream_webm.cpp b/modules/webm/video_stream_webm.cpp
index 6485c95360..3670edc9ea 100644
--- a/modules/webm/video_stream_webm.cpp
+++ b/modules/webm/video_stream_webm.cpp
@@ -413,10 +413,11 @@ void VideoStreamPlaybackWebm::delete_pointers() {
if (audio_frame)
memdelete(audio_frame);
- for (int i = 0; i < video_frames_capacity; ++i)
- memdelete(video_frames[i]);
- if (video_frames)
+ if (video_frames) {
+ for (int i = 0; i < video_frames_capacity; ++i)
+ memdelete(video_frames[i]);
memfree(video_frames);
+ }
if (video)
memdelete(video);
diff --git a/modules/webm/video_stream_webm.h b/modules/webm/video_stream_webm.h
index 992095ba4c..ddcbb1eb08 100644
--- a/modules/webm/video_stream_webm.h
+++ b/modules/webm/video_stream_webm.h
@@ -41,7 +41,7 @@ class OpusVorbisDecoder;
class VideoStreamPlaybackWebm : public VideoStreamPlayback {
- GDCLASS(VideoStreamPlaybackWebm, VideoStreamPlayback)
+ GDCLASS(VideoStreamPlaybackWebm, VideoStreamPlayback);
String file_name;
int audio_track;
@@ -127,7 +127,6 @@ public:
};
class ResourceFormatLoaderWebm : public ResourceFormatLoader {
- GDCLASS(ResourceFormatLoaderWebm, ResourceFormatLoader)
public:
virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp
index 928a0dcbd3..630c15f140 100644
--- a/modules/webp/image_loader_webp.cpp
+++ b/modules/webp/image_loader_webp.cpp
@@ -71,7 +71,7 @@ static PoolVector<uint8_t> _webp_lossy_pack(const Ref<Image> &p_image, float p_q
w[3] = 'P';
copymem(&w[4], dst_buff, dst_size);
free(dst_buff);
- w = PoolVector<uint8_t>::Write();
+ w.release();
return dst;
}
@@ -110,7 +110,7 @@ static Ref<Image> _webp_lossy_unpack(const PoolVector<uint8_t> &p_buffer) {
//ERR_EXPLAIN("Error decoding webp! - "+p_file);
ERR_FAIL_COND_V(errdec, Ref<Image>());
- dst_w = PoolVector<uint8_t>::Write();
+ dst_w.release();
Ref<Image> img = memnew(Image(features.width, features.height, 0, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image));
return img;
@@ -137,7 +137,7 @@ Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p
} else {
errdec = WebPDecodeRGBInto(p_buffer, p_buffer_len, dst_w.ptr(), datasize, 3 * features.width) == NULL;
}
- dst_w = PoolVector<uint8_t>::Write();
+ dst_w.release();
//ERR_EXPLAIN("Error decoding webp!");
ERR_FAIL_COND_V(errdec, ERR_FILE_CORRUPT);
@@ -171,8 +171,6 @@ Error ImageLoaderWEBP::load_image(Ref<Image> p_image, FileAccess *f, bool p_forc
Error err = webp_load_image_from_buffer(p_image.ptr(), w.ptr(), src_image_len);
- w = PoolVector<uint8_t>::Write();
-
return err;
}
diff --git a/modules/webrtc/config.py b/modules/webrtc/config.py
index 2e3a18ad0e..48b4c33c5d 100644
--- a/modules/webrtc/config.py
+++ b/modules/webrtc/config.py
@@ -7,7 +7,8 @@ def configure(env):
def get_doc_classes():
return [
"WebRTCPeerConnection",
- "WebRTCDataChannel"
+ "WebRTCDataChannel",
+ "WebRTCMultiplayer"
]
def get_doc_path():
diff --git a/modules/webrtc/doc_classes/WebRTCDataChannel.xml b/modules/webrtc/doc_classes/WebRTCDataChannel.xml
index dcc14d4ddb..98715ee99b 100644
--- a/modules/webrtc/doc_classes/WebRTCDataChannel.xml
+++ b/modules/webrtc/doc_classes/WebRTCDataChannel.xml
@@ -11,85 +11,106 @@
<return type="void">
</return>
<description>
+ Closes this data channel, notifying the other peer.
</description>
</method>
<method name="get_id" qualifiers="const">
<return type="int">
</return>
<description>
+ Returns the id assigned to this channel during creation (or auto-assigned during negotiation).
+ If the channel is not negotiated out-of-band the id will only be available after the connection is established (will return [code]65535[/code] until then).
</description>
</method>
<method name="get_label" qualifiers="const">
<return type="String">
</return>
<description>
+ Returns the label assigned to this channel during creation.
</description>
</method>
<method name="get_max_packet_life_time" qualifiers="const">
<return type="int">
</return>
<description>
+ Returns the [code]maxPacketLifeTime[/code] value assigned to this channel during creation.
+ Will be [code]65535[/code] if not specified.
</description>
</method>
<method name="get_max_retransmits" qualifiers="const">
<return type="int">
</return>
<description>
+ Returns the [code]maxRetransmits[/code] value assigned to this channel during creation.
+ Will be [code]65535[/code] if not specified.
</description>
</method>
<method name="get_protocol" qualifiers="const">
<return type="String">
</return>
<description>
+ Returns the sub-protocol assigned to this channel during creation. An empty string if not specified.
</description>
</method>
<method name="get_ready_state" qualifiers="const">
<return type="int" enum="WebRTCDataChannel.ChannelState">
</return>
<description>
+ Returns the current state of this channel, see [enum ChannelState].
</description>
</method>
<method name="is_negotiated" qualifiers="const">
<return type="bool">
</return>
<description>
+ Returns [code]true[/code] if this channel was created with out-of-band configuration.
</description>
</method>
<method name="is_ordered" qualifiers="const">
<return type="bool">
</return>
<description>
+ Returns [code]true[/code] if this channel was created with ordering enabled (default).
</description>
</method>
<method name="poll">
<return type="int" enum="Error">
</return>
<description>
+ Reserved, but not used for now.
</description>
</method>
<method name="was_string_packet" qualifiers="const">
<return type="bool">
</return>
<description>
+ Returns [code]true[/code] if the last received packet was transferred as text. See [member write_mode].
</description>
</method>
</methods>
<members>
- <member name="write_mode" type="int" setter="set_write_mode" getter="get_write_mode" enum="WebRTCDataChannel.WriteMode">
+ <member name="write_mode" type="int" setter="set_write_mode" getter="get_write_mode" enum="WebRTCDataChannel.WriteMode" default="1">
+ The transfer mode to use when sending outgoing packet. Either text or binary.
</member>
</members>
<constants>
<constant name="WRITE_MODE_TEXT" value="0" enum="WriteMode">
+ Tells the channel to send data over this channel as text. An external peer (non-Godot) would receive this as a string.
</constant>
<constant name="WRITE_MODE_BINARY" value="1" enum="WriteMode">
+ Tells the channel to send data over this channel as binary. An external peer (non-Godot) would receive this as array buffer or blob.
</constant>
<constant name="STATE_CONNECTING" value="0" enum="ChannelState">
+ The channel was created, but it's still trying to connect.
</constant>
<constant name="STATE_OPEN" value="1" enum="ChannelState">
+ The channel is currently open, and data can flow over it.
</constant>
<constant name="STATE_CLOSING" value="2" enum="ChannelState">
+ The channel is being closed, no new messages will be accepted, but those already in queue will be flushed.
</constant>
<constant name="STATE_CLOSED" value="3" enum="ChannelState">
+ The channel was closed, or connection failed.
</constant>
</constants>
</class>
diff --git a/modules/webrtc/doc_classes/WebRTCMultiplayer.xml b/modules/webrtc/doc_classes/WebRTCMultiplayer.xml
new file mode 100644
index 0000000000..2b0622fffa
--- /dev/null
+++ b/modules/webrtc/doc_classes/WebRTCMultiplayer.xml
@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="WebRTCMultiplayer" inherits="NetworkedMultiplayerPeer" category="Core" version="3.2">
+ <brief_description>
+ A simple interface to create a peer-to-peer mesh network composed of [WebRTCPeerConnection] that is compatible with the [MultiplayerAPI].
+ </brief_description>
+ <description>
+ This class constructs a full mesh of [WebRTCPeerConnection] (one connection for each peer) that can be used as a [member MultiplayerAPI.network_peer].
+ You can add each [WebRTCPeerConnection] via [method add_peer] or remove them via [method remove_peer]. Peers must be added in [constant WebRTCPeerConnection.STATE_NEW] state to allow it to create the appropriate channels. This class will not create offers nor set descriptions, it will only poll them, and notify connections and disconnections.
+ [signal NetworkedMultiplayerPeer.connection_succeeded] and [signal NetworkedMultiplayerPeer.server_disconnected] will not be emitted unless [code]server_compatibility[/code] is [code]true[/code] in [method initialize]. Beside that data transfer works like in a [NetworkedMultiplayerPeer].
+ </description>
+ <tutorials>
+ </tutorials>
+ <methods>
+ <method name="add_peer">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="peer" type="WebRTCPeerConnection">
+ </argument>
+ <argument index="1" name="peer_id" type="int">
+ </argument>
+ <argument index="2" name="unreliable_lifetime" type="int" default="1">
+ </argument>
+ <description>
+ Add a new peer to the mesh with the given [code]peer_id[/code]. The [WebRTCPeerConnection] must be in state [constant WebRTCPeerConnection.STATE_NEW].
+ Three channels will be created for reliable, unreliable, and ordered transport. The value of [code]unreliable_lifetime[/code] will be passed to the [code]maxPacketLifetime[/code] option when creating unreliable and ordered channels (see [method WebRTCPeerConnection.create_data_channel]).
+ </description>
+ </method>
+ <method name="close">
+ <return type="void">
+ </return>
+ <description>
+ Close all the add peer connections and channels, freeing all resources.
+ </description>
+ </method>
+ <method name="get_peer">
+ <return type="Dictionary">
+ </return>
+ <argument index="0" name="peer_id" type="int">
+ </argument>
+ <description>
+ Return a dictionary representation of the peer with given [code]peer_id[/code] with three keys. [code]connection[/code] containing the [WebRTCPeerConnection] to this peer, [code]channels[/code] an array of three [WebRTCDataChannel], and [code]connected[/code] a boolean representing if the peer connection is currently connected (all three channels are open).
+ </description>
+ </method>
+ <method name="get_peers">
+ <return type="Dictionary">
+ </return>
+ <description>
+ Returns a dictionary which keys are the peer ids and values the peer representation as in [method get_peer]
+ </description>
+ </method>
+ <method name="has_peer">
+ <return type="bool">
+ </return>
+ <argument index="0" name="peer_id" type="int">
+ </argument>
+ <description>
+ Returns [code]true[/code] if the given [code]peer_id[/code] is in the peers map (it might not be connected though).
+ </description>
+ </method>
+ <method name="initialize">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="peer_id" type="int">
+ </argument>
+ <argument index="1" name="server_compatibility" type="bool" default="false">
+ </argument>
+ <description>
+ Initialize the multiplayer peer with the given [code]peer_id[/code] (must be between 1 and 2147483647).
+ If [code]server_compatibilty[/code] is [code]false[/code] (default), the multiplayer peer will be immediately in state [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED] and [signal NetworkedMultiplayerPeer.connection_succeeded] will not be emitted.
+ If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal NetworkedMultiplayerPeer.peer_connected] signals until a peer with id [constant NetworkedMultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal NetworkedMultiplayerPeer.connection_succeeded]. After that the signal [signal NetworkedMultiplayerPeer.peer_connected] will be emitted for every already connected peer, and any new peer that might connect. If the server peer disconnects after that, signal [signal NetworkedMultiplayerPeer.server_disconnected] will be emitted and state will become [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED].
+ </description>
+ </method>
+ <method name="remove_peer">
+ <return type="void">
+ </return>
+ <argument index="0" name="peer_id" type="int">
+ </argument>
+ <description>
+ Remove the peer with given [code]peer_id[/code] from the mesh. If the peer was connected, and [signal NetworkedMultiplayerPeer.peer_connected] was emitted for it, then [signal NetworkedMultiplayerPeer.peer_disconnected] will be emitted.
+ </description>
+ </method>
+ </methods>
+ <constants>
+ </constants>
+</class>
diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml
index 8b14c60deb..26082d73a8 100644
--- a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml
+++ b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml
@@ -1,8 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="WebRTCPeerConnection" inherits="Reference" category="Core" version="3.2">
<brief_description>
+ Interface to a WebRTC peer connection.
</brief_description>
<description>
+ A WebRTC connection between the local computer and a remote peer. Provides an interface to connect, maintain and monitor the connection.
+ Setting up a WebRTC connection between two peers from now on) may not seem a trivial task, but it can be broken down into 3 main steps:
+ - The peer that wants to initiate the connection ([code]A[/code] from now on) creates an offer and send it to the other peer ([code]B[/code] from now on).
+ - [code]B[/code] receives the offer, generate and answer, and sends it to [code]A[/code]).
+ - [code]A[/code] and [code]B[/code] then generates and exchange ICE candidates with each other.
+ After these steps, the connection should become connected. Keep on reading or look into the tutorial for more information.
</description>
<tutorials>
</tutorials>
@@ -17,12 +24,14 @@
<argument index="2" name="name" type="String">
</argument>
<description>
+ Add an ice candidate generated by a remote peer (and received over the signaling server). See [signal ice_candidate_created].
</description>
</method>
<method name="close">
<return type="void">
</return>
<description>
+ Close the peer connection and all data channels associated with it. Note, you cannot reuse this object for a new connection unless you call [method initialize].
</description>
</method>
<method name="create_data_channel">
@@ -35,18 +44,38 @@
}">
</argument>
<description>
+ Returns a new [WebRTCDataChannel] (or [code]null[/code] on failure) with given [code]label[/code] and optionally configured via the [code]options[/code] dictionary. This method can only be called when the connection is in state [constant STATE_NEW].
+ There are two ways to create a working data channel: either call [method create_data_channel] on only one of the peer and listen to [signal data_channel_received] on the other, or call [method create_data_channel] on both peers, with the same values, and the [code]negotiated[/code] option set to [code]true[/code].
+ Valid [code]options[/code] are:
+ [codeblock]
+ {
+ "negotiated": true, # When set to true (default off), means the channel is negotiated out of band. "id" must be set too. data_channel_received will not be called.
+ "id": 1, # When "negotiated" is true this value must also be set to the same value on both peer.
+
+ # Only one of maxRetransmits and maxPacketLifeTime can be specified, not both. They make the channel unreliable (but also better at real time).
+ "maxRetransmits": 1, # Specify the maximum number of attempt the peer will make to retransmits packets if they are not acknowledged.
+ "maxPacketLifeTime": 100, # Specify the maximum amount of time before giving up retransmitions of unacknowledged packets (in milliseconds).
+ "ordered": true, # When in unreliable mode (i.e. either "maxRetransmits" or "maxPacketLifetime" is set), "ordered" (true by default) specify if packet ordering is to be enforced.
+
+ "protocol": "my-custom-protocol", # A custom sub-protocol string for this channel.
+ }
+ [/codeblock]
+ [b]Note:[/b] You must keep a reference to channels created this way, or it will be closed.
</description>
</method>
<method name="create_offer">
<return type="int" enum="Error">
</return>
<description>
+ Creates a new SDP offer to start a WebRTC connection with a remote peer. At least one [WebRTCDataChannel] must have been created before calling this method.
+ If this functions returns [constant OK], [signal session_description_created] will be called when the session is ready to be sent.
</description>
</method>
<method name="get_connection_state" qualifiers="const">
<return type="int" enum="WebRTCPeerConnection.ConnectionState">
</return>
<description>
+ Returns the connection state. See [enum ConnectionState].
</description>
</method>
<method name="initialize">
@@ -57,12 +86,29 @@
}">
</argument>
<description>
+ Re-initialize this peer connection, closing any previously active connection, and going back to state [constant STATE_NEW]. A dictionary of [code]options[/code] can be passed to configure the peer connection.
+ Valid [code]options[/code] are:
+ [codeblock]
+ {
+ "iceServers": [
+ {
+ "urls": [ "stun:stun.example.com:3478" ], # One or more STUN servers.
+ },
+ {
+ "urls": [ "turn:turn.example.com:3478" ], # One or more TURN servers.
+ "username": "a_username", # Optional username for the TURN server.
+ "credentials": "a_password", # Optional password for the TURN server.
+ }
+ ]
+ }
+ [/codeblock]
</description>
</method>
<method name="poll">
<return type="int" enum="Error">
</return>
<description>
+ Call this method frequently (e.g. in [method Node._process] or [method Node._physics_process]) to properly receive signals.
</description>
</method>
<method name="set_local_description">
@@ -73,6 +119,8 @@
<argument index="1" name="sdp" type="String">
</argument>
<description>
+ Sets the SDP description of the local peer. This should be called in response to [signal session_description_created].
+ If [code]type[/code] is [code]answer[/code] the peer will start emitting [signal ice_candidate_created].
</description>
</method>
<method name="set_remote_description">
@@ -83,6 +131,9 @@
<argument index="1" name="sdp" type="String">
</argument>
<description>
+ Sets the SDP description of the remote peer. This should be called with the values generated by a remote peer and received over the signaling server.
+ If [code]type[/code] is [code]offer[/code] the peer will emit [signal session_description_created] with the appropriate answer.
+ If [code]type[/code] is [code]answer[/code] the peer will start emitting [signal ice_candidate_created].
</description>
</method>
</methods>
@@ -91,6 +142,8 @@
<argument index="0" name="channel" type="Object">
</argument>
<description>
+ Emitted when a new in-band channel is received, i.e. when the channel was created with [code]negotiated: false[/code] (default).
+ The object will be an instance of [WebRTCDataChannel]. You must keep a reference of it or it will be closed automatically. See [method create_data_channel]
</description>
</signal>
<signal name="ice_candidate_created">
@@ -101,6 +154,7 @@
<argument index="2" name="name" type="String">
</argument>
<description>
+ Emitted when a new ICE candidate has been created. The three parameters are meant to be passed to the remote peer over the signaling server.
</description>
</signal>
<signal name="session_description_created">
@@ -109,21 +163,28 @@
<argument index="1" name="sdp" type="String">
</argument>
<description>
+ Emitted after a successful call to [method create_offer] or [method set_remote_description] (when it generates an answer). The parameters are meant to be passed to [method set_local_description] on this object, and sent to the remote peer over the signaling server.
</description>
</signal>
</signals>
<constants>
<constant name="STATE_NEW" value="0" enum="ConnectionState">
+ The connection is new, data channels and an offer can be created in this state.
</constant>
<constant name="STATE_CONNECTING" value="1" enum="ConnectionState">
+ The peer is connecting, ICE is in progress, none of the transports has failed.
</constant>
<constant name="STATE_CONNECTED" value="2" enum="ConnectionState">
+ The peer is connected, all ICE transports are connected.
</constant>
<constant name="STATE_DISCONNECTED" value="3" enum="ConnectionState">
+ At least one ICE transport is disconnected.
</constant>
<constant name="STATE_FAILED" value="4" enum="ConnectionState">
+ One or more of the ICE transports failed.
</constant>
<constant name="STATE_CLOSED" value="5" enum="ConnectionState">
+ The peer connection is closed (after calling [method close] for example).
</constant>
</constants>
</class>
diff --git a/modules/webrtc/register_types.cpp b/modules/webrtc/register_types.cpp
index 44e072cc89..58b68d926b 100644
--- a/modules/webrtc/register_types.cpp
+++ b/modules/webrtc/register_types.cpp
@@ -40,6 +40,7 @@
#include "webrtc_data_channel_gdnative.h"
#include "webrtc_peer_connection_gdnative.h"
#endif
+#include "webrtc_multiplayer.h"
void register_webrtc_types() {
#ifdef JAVASCRIPT_ENABLED
@@ -54,6 +55,7 @@ void register_webrtc_types() {
ClassDB::register_class<WebRTCDataChannelGDNative>();
#endif
ClassDB::register_virtual_class<WebRTCDataChannel>();
+ ClassDB::register_class<WebRTCMultiplayer>();
}
void unregister_webrtc_types() {}
diff --git a/modules/webrtc/webrtc_data_channel_gdnative.cpp b/modules/webrtc/webrtc_data_channel_gdnative.cpp
index 4f33491af2..6362634626 100644
--- a/modules/webrtc/webrtc_data_channel_gdnative.cpp
+++ b/modules/webrtc/webrtc_data_channel_gdnative.cpp
@@ -35,6 +35,7 @@
#include "modules/gdnative/nativescript/nativescript.h"
void WebRTCDataChannelGDNative::_bind_methods() {
+ ADD_PROPERTY_DEFAULT("write_mode", WRITE_MODE_BINARY);
}
WebRTCDataChannelGDNative::WebRTCDataChannelGDNative() {
diff --git a/modules/webrtc/webrtc_data_channel_js.cpp b/modules/webrtc/webrtc_data_channel_js.cpp
index 2e7c64aa72..069918cc9c 100644
--- a/modules/webrtc/webrtc_data_channel_js.cpp
+++ b/modules/webrtc/webrtc_data_channel_js.cpp
@@ -68,7 +68,7 @@ void WebRTCDataChannelJS::_on_error() {
}
void WebRTCDataChannelJS::_on_message(uint8_t *p_data, uint32_t p_size, bool p_is_string) {
- if (in_buffer.space_left() < p_size + 5) {
+ if (in_buffer.space_left() < (int)(p_size + 5)) {
ERR_EXPLAIN("Buffer full! Dropping data");
ERR_FAIL();
}
@@ -205,30 +205,45 @@ String WebRTCDataChannelJS::get_label() const {
}
/* clang-format off */
-#define _JS_GET(PROP) \
+#define _JS_GET(PROP, DEF) \
EM_ASM_INT({ \
var dict = Module.IDHandler.get($0); \
if (!dict || !dict["channel"]) { \
- return 0; \
- }; \
- return dict["channel"].PROP; \
+ return DEF; \
+ } \
+ var out = dict["channel"].PROP; \
+ return out === null ? DEF : out; \
}, _js_id)
/* clang-format on */
bool WebRTCDataChannelJS::is_ordered() const {
- return _JS_GET(ordered);
+ return _JS_GET(ordered, true);
}
int WebRTCDataChannelJS::get_id() const {
- return _JS_GET(id);
+ return _JS_GET(id, 65535);
}
int WebRTCDataChannelJS::get_max_packet_life_time() const {
- return _JS_GET(maxPacketLifeTime);
+ // Can't use macro, webkit workaround.
+ /* clang-format off */
+ return EM_ASM_INT({
+ var dict = Module.IDHandler.get($0);
+ if (!dict || !dict["channel"]) {
+ return 65535;
+ }
+ if (dict["channel"].maxRetransmitTime !== undefined) {
+ // Guess someone didn't appreciate the standardization process.
+ return dict["channel"].maxRetransmitTime;
+ }
+ var out = dict["channel"].maxPacketLifeTime;
+ return out === null ? 65535 : out;
+ }, _js_id);
+ /* clang-format on */
}
int WebRTCDataChannelJS::get_max_retransmits() const {
- return _JS_GET(maxRetransmits);
+ return _JS_GET(maxRetransmits, 65535);
}
String WebRTCDataChannelJS::get_protocol() const {
@@ -236,7 +251,7 @@ String WebRTCDataChannelJS::get_protocol() const {
}
bool WebRTCDataChannelJS::is_negotiated() const {
- return _JS_GET(negotiated);
+ return _JS_GET(negotiated, false);
}
WebRTCDataChannelJS::WebRTCDataChannelJS() {
diff --git a/modules/webrtc/webrtc_multiplayer.cpp b/modules/webrtc/webrtc_multiplayer.cpp
new file mode 100644
index 0000000000..17dafff93a
--- /dev/null
+++ b/modules/webrtc/webrtc_multiplayer.cpp
@@ -0,0 +1,384 @@
+/*************************************************************************/
+/* webrtc_multiplayer.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "webrtc_multiplayer.h"
+
+#include "core/io/marshalls.h"
+#include "core/os/os.h"
+
+void WebRTCMultiplayer::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility"), &WebRTCMultiplayer::initialize, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayer::add_peer, DEFVAL(1));
+ ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayer::remove_peer);
+ ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayer::has_peer);
+ ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayer::get_peer);
+ ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayer::get_peers);
+ ClassDB::bind_method(D_METHOD("close"), &WebRTCMultiplayer::close);
+}
+
+void WebRTCMultiplayer::set_transfer_mode(TransferMode p_mode) {
+ transfer_mode = p_mode;
+}
+
+NetworkedMultiplayerPeer::TransferMode WebRTCMultiplayer::get_transfer_mode() const {
+ return transfer_mode;
+}
+
+void WebRTCMultiplayer::set_target_peer(int p_peer_id) {
+ target_peer = p_peer_id;
+}
+
+/* Returns the ID of the NetworkedMultiplayerPeer who sent the most recent packet: */
+int WebRTCMultiplayer::get_packet_peer() const {
+ return next_packet_peer;
+}
+
+bool WebRTCMultiplayer::is_server() const {
+ return unique_id == TARGET_PEER_SERVER;
+}
+
+void WebRTCMultiplayer::poll() {
+ if (peer_map.size() == 0)
+ return;
+
+ List<int> remove;
+ List<int> add;
+ for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) {
+ Ref<ConnectedPeer> peer = E->get();
+ peer->connection->poll();
+ // Check peer state
+ switch (peer->connection->get_connection_state()) {
+ case WebRTCPeerConnection::STATE_NEW:
+ case WebRTCPeerConnection::STATE_CONNECTING:
+ // Go to next peer, not ready yet.
+ continue;
+ case WebRTCPeerConnection::STATE_CONNECTED:
+ // Good to go, go ahead and check channel state.
+ break;
+ default:
+ // Peer is closed or in error state. Got to next peer.
+ remove.push_back(E->key());
+ continue;
+ }
+ // Check channels state
+ int ready = 0;
+ for (List<Ref<WebRTCDataChannel> >::Element *C = peer->channels.front(); C && C->get().is_valid(); C = C->next()) {
+ Ref<WebRTCDataChannel> ch = C->get();
+ switch (ch->get_ready_state()) {
+ case WebRTCDataChannel::STATE_CONNECTING:
+ continue;
+ case WebRTCDataChannel::STATE_OPEN:
+ ready++;
+ continue;
+ default:
+ // Channel was closed or in error state, remove peer id.
+ remove.push_back(E->key());
+ }
+ // We got a closed channel break out, the peer will be removed.
+ break;
+ }
+ // This peer has newly connected, and all channels are now open.
+ if (ready == peer->channels.size() && !peer->connected) {
+ peer->connected = true;
+ add.push_back(E->key());
+ }
+ }
+ // Remove disconnected peers
+ for (List<int>::Element *E = remove.front(); E; E = E->next()) {
+ remove_peer(E->get());
+ if (next_packet_peer == E->get())
+ next_packet_peer = 0;
+ }
+ // Signal newly connected peers
+ for (List<int>::Element *E = add.front(); E; E = E->next()) {
+ // Already connected to server: simply notify new peer.
+ // NOTE: Mesh is always connected.
+ if (connection_status == CONNECTION_CONNECTED)
+ emit_signal("peer_connected", E->get());
+
+ // Server emulation mode suppresses peer_conencted until server connects.
+ if (server_compat && E->get() == TARGET_PEER_SERVER) {
+ // Server connected.
+ connection_status = CONNECTION_CONNECTED;
+ emit_signal("peer_connected", TARGET_PEER_SERVER);
+ emit_signal("connection_succeeded");
+ // Notify of all previously connected peers
+ for (Map<int, Ref<ConnectedPeer> >::Element *F = peer_map.front(); F; F = F->next()) {
+ if (F->key() != 1 && F->get()->connected)
+ emit_signal("peer_connected", F->key());
+ }
+ break; // Because we already notified of all newly added peers.
+ }
+ }
+ // Fetch next packet
+ if (next_packet_peer == 0)
+ _find_next_peer();
+}
+
+void WebRTCMultiplayer::_find_next_peer() {
+ Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.find(next_packet_peer);
+ if (E) E = E->next();
+ // After last.
+ while (E) {
+ for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) {
+ if (F->get()->get_available_packet_count()) {
+ next_packet_peer = E->key();
+ return;
+ }
+ }
+ E = E->next();
+ }
+ E = peer_map.front();
+ // Before last
+ while (E) {
+ for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) {
+ if (F->get()->get_available_packet_count()) {
+ next_packet_peer = E->key();
+ return;
+ }
+ }
+ if (E->key() == (int)next_packet_peer)
+ break;
+ E = E->next();
+ }
+ // No packet found
+ next_packet_peer = 0;
+}
+
+void WebRTCMultiplayer::set_refuse_new_connections(bool p_enable) {
+ refuse_connections = p_enable;
+}
+
+bool WebRTCMultiplayer::is_refusing_new_connections() const {
+ return refuse_connections;
+}
+
+NetworkedMultiplayerPeer::ConnectionStatus WebRTCMultiplayer::get_connection_status() const {
+ return connection_status;
+}
+
+Error WebRTCMultiplayer::initialize(int p_self_id, bool p_server_compat) {
+ ERR_FAIL_COND_V(p_self_id < 0 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER);
+ unique_id = p_self_id;
+ server_compat = p_server_compat;
+
+ // Mesh and server are always connected
+ if (!server_compat || p_self_id == 1)
+ connection_status = CONNECTION_CONNECTED;
+ else
+ connection_status = CONNECTION_CONNECTING;
+ return OK;
+}
+
+int WebRTCMultiplayer::get_unique_id() const {
+ ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1);
+ return unique_id;
+}
+
+void WebRTCMultiplayer::_peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict) {
+ Array channels;
+ for (List<Ref<WebRTCDataChannel> >::Element *F = p_connected_peer->channels.front(); F; F = F->next()) {
+ channels.push_back(F->get());
+ }
+ r_dict["connection"] = p_connected_peer->connection;
+ r_dict["connected"] = p_connected_peer->connected;
+ r_dict["channels"] = channels;
+}
+
+bool WebRTCMultiplayer::has_peer(int p_peer_id) {
+ return peer_map.has(p_peer_id);
+}
+
+Dictionary WebRTCMultiplayer::get_peer(int p_peer_id) {
+ ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary());
+ Dictionary out;
+ _peer_to_dict(peer_map[p_peer_id], out);
+ return out;
+}
+
+Dictionary WebRTCMultiplayer::get_peers() {
+ Dictionary out;
+ for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) {
+ Dictionary d;
+ _peer_to_dict(E->get(), d);
+ out[E->key()] = d;
+ }
+ return out;
+}
+
+Error WebRTCMultiplayer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) {
+ ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(refuse_connections, ERR_UNAUTHORIZED);
+ // Peer must be valid, and in new state (to create data channels)
+ ERR_FAIL_COND_V(!p_peer.is_valid(), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER);
+
+ Ref<ConnectedPeer> peer = memnew(ConnectedPeer);
+ peer->connection = p_peer;
+
+ // Initialize data channels
+ Dictionary cfg;
+ cfg["negotiated"] = true;
+ cfg["ordered"] = true;
+
+ cfg["id"] = 1;
+ peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg);
+ ERR_FAIL_COND_V(!peer->channels[CH_RELIABLE].is_valid(), FAILED);
+
+ cfg["id"] = 2;
+ cfg["maxPacketLifetime"] = p_unreliable_lifetime;
+ peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg);
+ ERR_FAIL_COND_V(!peer->channels[CH_ORDERED].is_valid(), FAILED);
+
+ cfg["id"] = 3;
+ cfg["ordered"] = false;
+ peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg);
+ ERR_FAIL_COND_V(!peer->channels[CH_UNRELIABLE].is_valid(), FAILED);
+
+ peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map
+
+ return OK;
+}
+
+void WebRTCMultiplayer::remove_peer(int p_peer_id) {
+ ERR_FAIL_COND(!peer_map.has(p_peer_id));
+ Ref<ConnectedPeer> peer = peer_map[p_peer_id];
+ peer_map.erase(p_peer_id);
+ if (peer->connected) {
+ peer->connected = false;
+ emit_signal("peer_disconnected", p_peer_id);
+ if (server_compat && p_peer_id == TARGET_PEER_SERVER) {
+ emit_signal("server_disconnected");
+ connection_status = CONNECTION_DISCONNECTED;
+ }
+ }
+}
+
+Error WebRTCMultiplayer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
+ // Peer not available
+ if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) {
+ _find_next_peer();
+ ERR_FAIL_V(ERR_UNAVAILABLE);
+ }
+ for (List<Ref<WebRTCDataChannel> >::Element *E = peer_map[next_packet_peer]->channels.front(); E; E = E->next()) {
+ if (E->get()->get_available_packet_count()) {
+ Error err = E->get()->get_packet(r_buffer, r_buffer_size);
+ _find_next_peer();
+ return err;
+ }
+ }
+ // Channels for that peer were empty. Bug?
+ _find_next_peer();
+ ERR_FAIL_V(ERR_BUG);
+}
+
+Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
+ ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED);
+
+ int ch = CH_RELIABLE;
+ switch (transfer_mode) {
+ case TRANSFER_MODE_RELIABLE:
+ ch = CH_RELIABLE;
+ break;
+ case TRANSFER_MODE_UNRELIABLE_ORDERED:
+ ch = CH_ORDERED;
+ break;
+ case TRANSFER_MODE_UNRELIABLE:
+ ch = CH_UNRELIABLE;
+ break;
+ }
+
+ Map<int, Ref<ConnectedPeer> >::Element *E = NULL;
+
+ if (target_peer > 0) {
+
+ E = peer_map.find(target_peer);
+ if (!E) {
+ ERR_EXPLAIN("Invalid Target Peer: " + itos(target_peer));
+ ERR_FAIL_V(ERR_INVALID_PARAMETER);
+ }
+ ERR_FAIL_COND_V(E->value()->channels.size() <= ch, ERR_BUG);
+ ERR_FAIL_COND_V(!E->value()->channels[ch].is_valid(), ERR_BUG);
+ return E->value()->channels[ch]->put_packet(p_buffer, p_buffer_size);
+
+ } else {
+ int exclude = -target_peer;
+
+ for (Map<int, Ref<ConnectedPeer> >::Element *F = peer_map.front(); F; F = F->next()) {
+
+ // Exclude packet. If target_peer == 0 then don't exclude any packets
+ if (target_peer != 0 && F->key() == exclude)
+ continue;
+
+ ERR_CONTINUE(F->value()->channels.size() <= ch || !F->value()->channels[ch].is_valid());
+ F->value()->channels[ch]->put_packet(p_buffer, p_buffer_size);
+ }
+ }
+ return OK;
+}
+
+int WebRTCMultiplayer::get_available_packet_count() const {
+ if (next_packet_peer == 0)
+ return 0; // To be sure next call to get_packet works if size > 0 .
+ int size = 0;
+ for (Map<int, Ref<ConnectedPeer> >::Element *E = peer_map.front(); E; E = E->next()) {
+ for (List<Ref<WebRTCDataChannel> >::Element *F = E->get()->channels.front(); F; F = F->next()) {
+ size += F->get()->get_available_packet_count();
+ }
+ }
+ return size;
+}
+
+int WebRTCMultiplayer::get_max_packet_size() const {
+ return 1200;
+}
+
+void WebRTCMultiplayer::close() {
+ peer_map.clear();
+ unique_id = 0;
+ next_packet_peer = 0;
+ target_peer = 0;
+ connection_status = CONNECTION_DISCONNECTED;
+}
+
+WebRTCMultiplayer::WebRTCMultiplayer() {
+ unique_id = 0;
+ next_packet_peer = 0;
+ target_peer = 0;
+ transfer_mode = TRANSFER_MODE_RELIABLE;
+ refuse_connections = false;
+ connection_status = CONNECTION_DISCONNECTED;
+ server_compat = false;
+}
+
+WebRTCMultiplayer::~WebRTCMultiplayer() {
+ close();
+}
diff --git a/modules/mono/editor/godotsharp_builds.h b/modules/webrtc/webrtc_multiplayer.h
index 2e9050e12e..82bbfd4f68 100644
--- a/modules/mono/editor/godotsharp_builds.h
+++ b/modules/webrtc/webrtc_multiplayer.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* godotsharp_builds.h */
+/* webrtc_multiplayer.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,76 +28,89 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef GODOTSHARP_BUILDS_H
-#define GODOTSHARP_BUILDS_H
+#ifndef WEBRTC_MULTIPLAYER_H
+#define WEBRTC_MULTIPLAYER_H
-#include "../mono_gd/gd_mono.h"
-#include "mono_bottom_panel.h"
-#include "mono_build_info.h"
+#include "core/io/networked_multiplayer_peer.h"
+#include "webrtc_peer_connection.h"
-typedef void (*GodotSharpBuild_ExitCallback)(int);
+class WebRTCMultiplayer : public NetworkedMultiplayerPeer {
-class GodotSharpBuilds {
+ GDCLASS(WebRTCMultiplayer, NetworkedMultiplayerPeer);
+
+protected:
+ static void _bind_methods();
private:
- struct BuildProcess {
- Ref<MonoGCHandle> build_instance;
- MonoBuildInfo build_info;
- MonoBuildTab *build_tab;
- GodotSharpBuild_ExitCallback exit_callback;
- bool exited;
- int exit_code;
-
- void on_exit(int p_exit_code);
- void start(bool p_blocking = false);
-
- BuildProcess() {}
- BuildProcess(const MonoBuildInfo &p_build_info, GodotSharpBuild_ExitCallback p_callback = NULL);
+ enum {
+ CH_RELIABLE = 0,
+ CH_ORDERED = 1,
+ CH_UNRELIABLE = 2,
+ CH_RESERVED_MAX = 3
};
- HashMap<MonoBuildInfo, BuildProcess, MonoBuildInfo::Hasher> builds;
-
- static String _api_folder_name(APIAssembly::Type p_api_type);
+ class ConnectedPeer : public Reference {
- static GodotSharpBuilds *singleton;
+ public:
+ Ref<WebRTCPeerConnection> connection;
+ List<Ref<WebRTCDataChannel> > channels;
+ bool connected;
-public:
- enum BuildTool {
- MSBUILD_MONO,
-#ifdef WINDOWS_ENABLED
- MSBUILD_VS,
-#endif
- XBUILD // Deprecated
+ ConnectedPeer() {
+ connected = false;
+ for (int i = 0; i < CH_RESERVED_MAX; i++)
+ channels.push_front(Ref<WebRTCDataChannel>());
+ }
};
- _FORCE_INLINE_ static GodotSharpBuilds *get_singleton() { return singleton; }
+ uint32_t unique_id;
+ int target_peer;
+ int client_count;
+ bool refuse_connections;
+ ConnectionStatus connection_status;
+ TransferMode transfer_mode;
+ int next_packet_peer;
+ bool server_compat;
- static void register_internal_calls();
+ Map<int, Ref<ConnectedPeer> > peer_map;
- static void show_build_error_dialog(const String &p_message);
+ void _peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict);
+ void _find_next_peer();
- static const char *get_msbuild_issues_filename() { return "msbuild_issues.csv"; }
- static const char *get_msbuild_log_filename() { return "msbuild_log.txt"; }
+public:
+ WebRTCMultiplayer();
+ ~WebRTCMultiplayer();
- void build_exit_callback(const MonoBuildInfo &p_build_info, int p_exit_code);
+ Error initialize(int p_self_id, bool p_server_compat = false);
+ Error add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime = 1);
+ void remove_peer(int p_peer_id);
+ bool has_peer(int p_peer_id);
+ Dictionary get_peer(int p_peer_id);
+ Dictionary get_peers();
+ void close();
- void restart_build(MonoBuildTab *p_build_tab);
- void stop_build(MonoBuildTab *p_build_tab);
+ // PacketPeer
+ Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); ///< buffer is GONE after next get_packet
+ Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
+ int get_available_packet_count() const;
+ int get_max_packet_size() const;
- bool build(const MonoBuildInfo &p_build_info);
- bool build_async(const MonoBuildInfo &p_build_info, GodotSharpBuild_ExitCallback p_callback = NULL);
+ // NetworkedMultiplayerPeer
+ void set_transfer_mode(TransferMode p_mode);
+ TransferMode get_transfer_mode() const;
+ void set_target_peer(int p_peer_id);
- static bool build_api_sln(const String &p_api_sln_dir, const String &p_config);
- static bool copy_api_assembly(const String &p_src_dir, const String &p_dst_dir, const String &p_assembly_name, APIAssembly::Type p_api_type);
+ int get_unique_id() const;
+ int get_packet_peer() const;
- static bool make_api_assembly(APIAssembly::Type p_api_type);
+ bool is_server() const;
- static bool build_project_blocking(const String &p_config, const Vector<String> &p_godot_defines);
+ void poll();
- static bool editor_build_callback();
+ void set_refuse_new_connections(bool p_enable);
+ bool is_refusing_new_connections() const;
- GodotSharpBuilds();
- ~GodotSharpBuilds();
+ ConnectionStatus get_connection_status() const;
};
-#endif // GODOTSHARP_BUILDS_H
+#endif
diff --git a/modules/websocket/SCsub b/modules/websocket/SCsub
index d9e60eb6f1..033169411f 100644
--- a/modules/websocket/SCsub
+++ b/modules/websocket/SCsub
@@ -5,89 +5,26 @@ Import('env_modules')
# Thirdparty source files
-env_lws = env_modules.Clone()
-
-if env['builtin_libwebsockets'] and not env["platform"] == "javascript": # already builtin for javascript
- thirdparty_dir = "#thirdparty/libwebsockets/"
- helper_dir = "win32helpers/"
- thirdparty_sources = [
-
- "core/alloc.c",
- "core/context.c",
- "core/libwebsockets.c",
- "core/output.c",
- "core/pollfd.c",
- "core/service.c",
-
- "event-libs/poll/poll.c",
-
- "misc/base64-decode.c",
- "misc/lejp.c",
- "misc/sha-1.c",
-
- "roles/h1/ops-h1.c",
- "roles/http/header.c",
- "roles/http/client/client.c",
- "roles/http/client/client-handshake.c",
- "roles/http/server/fops-zip.c",
- "roles/http/server/lejp-conf.c",
- "roles/http/server/parsers.c",
- "roles/http/server/server.c",
- "roles/listen/ops-listen.c",
- "roles/pipe/ops-pipe.c",
- "roles/raw/ops-raw.c",
-
- "roles/ws/client-ws.c",
- "roles/ws/client-parser-ws.c",
- "roles/ws/ops-ws.c",
- "roles/ws/server-ws.c",
-
- "tls/tls.c",
- "tls/tls-client.c",
- "tls/tls-server.c",
-
- "tls/mbedtls/wrapper/library/ssl_cert.c",
- "tls/mbedtls/wrapper/library/ssl_pkey.c",
- "tls/mbedtls/wrapper/library/ssl_stack.c",
- "tls/mbedtls/wrapper/library/ssl_methods.c",
- "tls/mbedtls/wrapper/library/ssl_lib.c",
- "tls/mbedtls/wrapper/library/ssl_x509.c",
- "tls/mbedtls/wrapper/platform/ssl_port.c",
- "tls/mbedtls/wrapper/platform/ssl_pm.c",
- "tls/mbedtls/lws-genhash.c",
- "tls/mbedtls/mbedtls-client.c",
- "tls/mbedtls/lws-genrsa.c",
- "tls/mbedtls/ssl.c",
- "tls/mbedtls/mbedtls-server.c"
+env_ws = env_modules.Clone()
+
+if env['builtin_wslay'] and not env["platform"] == "javascript": # already builtin for javascript
+ wslay_dir = "#thirdparty/wslay/"
+ wslay_sources = [
+ "wslay_net.c",
+ "wslay_event.c",
+ "wslay_queue.c",
+ "wslay_stack.c",
+ "wslay_frame.c",
]
-
- if env["platform"] == "android": # Builtin getifaddrs
- thirdparty_sources += ["misc/getifaddrs.c"]
-
- if env["platform"] == "windows" or env["platform"] == "uwp": # Winsock
- thirdparty_sources += ["plat/lws-plat-win.c", helper_dir + "getopt.c", helper_dir + "getopt_long.c", helper_dir + "gettimeofday.c"]
- else: # Unix socket
- thirdparty_sources += ["plat/lws-plat-unix.c"]
-
- thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]
-
- env_lws.Prepend(CPPPATH=[thirdparty_dir])
-
- if env['builtin_mbedtls']:
- mbedtls_includes = "#thirdparty/mbedtls/include"
- env_lws.Prepend(CPPPATH=[mbedtls_includes])
-
- wrapper_includes = ["#thirdparty/libwebsockets/tls/mbedtls/wrapper/include/" + inc for inc in ["internal", "openssl", "platform", ""]]
- env_lws.Prepend(CPPPATH=wrapper_includes)
-
+ wslay_sources = [wslay_dir + s for s in wslay_sources]
+ env_ws.Prepend(CPPPATH=[wslay_dir + "includes/"])
+ env_ws.Append(CPPDEFINES=["HAVE_CONFIG_H"])
if env["platform"] == "windows" or env["platform"] == "uwp":
- env_lws.Prepend(CPPPATH=[thirdparty_dir + helper_dir])
-
- if env["platform"] == "uwp":
- env_lws.Append(CPPFLAGS=["/DLWS_MINGW_SUPPORT"])
-
- env_thirdparty = env_lws.Clone()
- env_thirdparty.disable_warnings()
- env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources)
-
-env_lws.add_source_files(env.modules_sources, "*.cpp")
+ env_ws.Append(CPPDEFINES=["HAVE_WINSOCK2_H"])
+ else:
+ env_ws.Append(CPPDEFINES=["HAVE_NETINET_IN_H"])
+ env_wslay = env_ws.Clone()
+ env_wslay.disable_warnings()
+ env_wslay.add_source_files(env.modules_sources, wslay_sources)
+
+env_ws.add_source_files(env.modules_sources, "*.cpp")
diff --git a/modules/websocket/doc_classes/WebSocketClient.xml b/modules/websocket/doc_classes/WebSocketClient.xml
index 26122dfad4..c3baf9de83 100644
--- a/modules/websocket/doc_classes/WebSocketClient.xml
+++ b/modules/websocket/doc_classes/WebSocketClient.xml
@@ -1,13 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="WebSocketClient" inherits="WebSocketMultiplayerPeer" category="Core" version="3.2">
<brief_description>
- A WebSocket client implementation
+ A WebSocket client implementation.
</brief_description>
<description>
- This class implements a WebSocket client compatible with any RFC 6455 complaint WebSocket server.
+ This class implements a WebSocket client compatible with any RFC 6455-compliant WebSocket server.
This client can be optionally used as a network peer for the [MultiplayerAPI].
After starting the client ([method connect_to_url]), you will need to [method NetworkedMultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]).
- You will received appropriate signals when connecting, disconnecting, or when new data is available.
+ You will receive appropriate signals when connecting, disconnecting, or when new data is available.
</description>
<tutorials>
</tutorials>
@@ -22,8 +22,8 @@
<argument index="2" name="gd_mp_api" type="bool" default="false">
</argument>
<description>
- Connect to the given URL requesting one of the given [code]protocols[/code] as sub-protocol.
- If [code]true[/code] is passed as [code]gd_mp_api[/code], the client will behave like a network peer for the [MultiplayerAPI], connections to non Godot servers will not work, and [signal data_received] will not be emitted.
+ Connects to the given URL requesting one of the given [code]protocols[/code] as sub-protocol. If the list empty (default), no sub-protocol will be requested.
+ If [code]true[/code] is passed as [code]gd_mp_api[/code], the client will behave like a network peer for the [MultiplayerAPI], connections to non-Godot servers will not work, and [signal data_received] will not be emitted.
If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.) on the [WebSocketPeer] returned via [code]get_peer(1)[/code] and not on this object directly (e.g. [code]get_peer(1).put_packet(data)[/code]).
</description>
</method>
@@ -35,13 +35,14 @@
<argument index="1" name="reason" type="String" default="&quot;&quot;">
</argument>
<description>
- Disconnect this client from the connected host. See [method WebSocketPeer.close] for more info.
+ Disconnects this client from the connected host. See [method WebSocketPeer.close] for more information.
</description>
</method>
</methods>
<members>
<member name="verify_ssl" type="bool" setter="set_verify_ssl_enabled" getter="is_verify_ssl_enabled">
- Enable or disable SSL certificate verification. Note: You must specify the certificates to be used in the project settings for it to work when exported.
+ If [code]true[/code], SSL certificate verification is enabled.
+ [b]Note:[/b] You must specify the certificates to be used in the Project Settings for it to work when exported.
</member>
</members>
<signals>
@@ -66,7 +67,8 @@
</signal>
<signal name="data_received">
<description>
- Emitted when a WebSocket message is received. Note: This signal is NOT emitted when used as high level multiplayer peer.
+ Emitted when a WebSocket message is received.
+ [b]Note:[/b] This signal is [i]not[/i] emitted when used as high-level multiplayer peer.
</description>
</signal>
<signal name="server_close_request">
diff --git a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml
index 8548d21323..b80a28e648 100644
--- a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml
+++ b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml
@@ -18,13 +18,32 @@
Returns the [WebSocketPeer] associated to the given [code]peer_id[/code].
</description>
</method>
+ <method name="set_buffers">
+ <return type="int" enum="Error">
+ </return>
+ <argument index="0" name="input_buffer_size_kb" type="int">
+ </argument>
+ <argument index="1" name="input_max_packets" type="int">
+ </argument>
+ <argument index="2" name="output_buffer_size_kb" type="int">
+ </argument>
+ <argument index="3" name="output_max_packets" type="int">
+ </argument>
+ <description>
+ Configures the buffer sizes for this WebSocket peer. Default values can be specified in the Project Settings under [code]network/limits[/code]. For server, values are meant per connected peer.
+ The first two parameters define the size and queued packets limits of the input buffer, the last two of the output buffer.
+ Buffer sizes are expressed in KiB, so [code]4 = 2^12 = 4096 bytes[/code]. All parameters will be rounded up to the nearest power of two.
+ [b]Note:[/b] HTML5 exports only use the input buffer since the output one is managed by browsers.
+ </description>
+ </method>
</methods>
<signals>
<signal name="peer_packet">
<argument index="0" name="peer_source" type="int">
</argument>
<description>
- Emitted when a packet is received from a peer. Note: this signal is only emitted when the client or server is configured to use Godot multiplayer API.
+ Emitted when a packet is received from a peer.
+ [b]Note:[/b] This signal is only emitted when the client or server is configured to use Godot multiplayer API.
</description>
</signal>
</signals>
diff --git a/modules/websocket/doc_classes/WebSocketPeer.xml b/modules/websocket/doc_classes/WebSocketPeer.xml
index 8a6868d311..dd95f7432e 100644
--- a/modules/websocket/doc_classes/WebSocketPeer.xml
+++ b/modules/websocket/doc_classes/WebSocketPeer.xml
@@ -18,30 +18,32 @@
<argument index="1" name="reason" type="String" default="&quot;&quot;">
</argument>
<description>
- Close this WebSocket connection. [code]code[/code] is the status code for the closure (see RFC6455 section 7.4 for a list of valid status codes). [code]reason[/code] is the human readable reason for closing the connection (can be any UTF8 string, must be less than 123 bytes).
- Note: To achieve a clean close, you will need to keep polling until either [signal WebSocketClient.connection_closed] or [signal WebSocketServer.client_disconnected] is received.
- Note: HTML5 export might not support all status codes. Please refer to browsers-specific documentation for more details.
+ Closes this WebSocket connection. [code]code[/code] is the status code for the closure (see RFC 6455 section 7.4 for a list of valid status codes). [code]reason[/code] is the human readable reason for closing the connection (can be any UTF-8 string that's smaller than 123 bytes).
+ [b]Note:[/b] To achieve a clean close, you will need to keep polling until either [signal WebSocketClient.connection_closed] or [signal WebSocketServer.client_disconnected] is received.
+ [b]Note:[/b] The HTML5 export might not support all status codes. Please refer to browser-specific documentation for more details.
</description>
</method>
<method name="get_connected_host" qualifiers="const">
<return type="String">
</return>
<description>
- Returns the IP Address of the connected peer. (Not available in HTML5 export)
+ Returns the IP address of the connected peer.
+ [b]Note:[/b] Not available in the HTML5 export.
</description>
</method>
<method name="get_connected_port" qualifiers="const">
<return type="int">
</return>
<description>
- Returns the remote port of the connected peer. (Not available in HTML5 export)
+ Returns the remote port of the connected peer.
+ [b]Note:[/b] Not available in the HTML5 export.
</description>
</method>
<method name="get_write_mode" qualifiers="const">
<return type="int" enum="WebSocketPeer.WriteMode">
</return>
<description>
- Get the current selected write mode. See [enum WriteMode].
+ Gets the current selected write mode. See [enum WriteMode].
</description>
</method>
<method name="is_connected_to_host" qualifiers="const">
@@ -70,10 +72,10 @@
</methods>
<constants>
<constant name="WRITE_MODE_TEXT" value="0" enum="WriteMode">
- Specify that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed).
+ Specifies that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed).
</constant>
<constant name="WRITE_MODE_BINARY" value="1" enum="WriteMode">
- Specify that WebSockets messages should be transferred as binary payload (any byte combination is allowed).
+ Specifies that WebSockets messages should be transferred as binary payload (any byte combination is allowed).
</constant>
</constants>
</class>
diff --git a/modules/websocket/doc_classes/WebSocketServer.xml b/modules/websocket/doc_classes/WebSocketServer.xml
index 51945d410a..63318e5874 100644
--- a/modules/websocket/doc_classes/WebSocketServer.xml
+++ b/modules/websocket/doc_classes/WebSocketServer.xml
@@ -1,12 +1,12 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="WebSocketServer" inherits="WebSocketMultiplayerPeer" category="Core" version="3.2">
<brief_description>
- A WebSocket server implementation
+ A WebSocket server implementation.
</brief_description>
<description>
- This class implements a WebSocket server that can also support the high level multiplayer API.
+ This class implements a WebSocket server that can also support the high-level multiplayer API.
After starting the server ([method listen]), you will need to [method NetworkedMultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). When clients connect, disconnect, or send data, you will receive the appropriate signal.
- Note: This class will not work in HTML5 exports due to browser restrictions.
+ [b]Note:[/b] This class will not work in HTML5 exports due to browser restrictions.
</description>
<tutorials>
</tutorials>
@@ -21,7 +21,7 @@
<argument index="2" name="reason" type="String" default="&quot;&quot;">
</argument>
<description>
- Disconnects the peer identified by [code]id[/code] from the server. See [method WebSocketPeer.close] for more info.
+ Disconnects the peer identified by [code]id[/code] from the server. See [method WebSocketPeer.close] for more information.
</description>
</method>
<method name="get_peer_address" qualifiers="const">
@@ -68,17 +68,17 @@
<argument index="2" name="gd_mp_api" type="bool" default="false">
</argument>
<description>
- Start listening on the given port.
- You can specify the desired subprotocols via the "protocols" array. If the list empty (default), "binary" will be used.
- If [code]true[/code] is passed as [code]gd_mp_api[/code], the server will behave like a network peer for the [MultiplayerAPI], connections from non Godot clients will not work, and [signal data_received] will not be emitted.
- If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.), on the [WebSocketPeer] returned via [code]get_peer(ID)[/code] to communicate with the peer with given [code]ID[/code] (e.g. [code]get_peer(ID).get_available_packet_count[/code]).
+ Starts listening on the given port.
+ You can specify the desired subprotocols via the "protocols" array. If the list empty (default), no sub-protocol will be requested.
+ If [code]true[/code] is passed as [code]gd_mp_api[/code], the server will behave like a network peer for the [MultiplayerAPI], connections from non-Godot clients will not work, and [signal data_received] will not be emitted.
+ If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.), on the [WebSocketPeer] returned via [code]get_peer(id)[/code] to communicate with the peer with given [code]id[/code] (e.g. [code]get_peer(id).get_available_packet_count[/code]).
</description>
</method>
<method name="stop">
<return type="void">
</return>
<description>
- Stop the server and clear its state.
+ Stops the server and clear its state.
</description>
</method>
</methods>
@@ -116,7 +116,8 @@
<argument index="0" name="id" type="int">
</argument>
<description>
- Emitted when a new message is received. Note: This signal is NOT emitted when used as high level multiplayer peer.
+ Emitted when a new message is received.
+ [b]Note:[/b] This signal is [i]not[/i] emitted when used as high-level multiplayer peer.
</description>
</signal>
</signals>
diff --git a/modules/websocket/emws_client.cpp b/modules/websocket/emws_client.cpp
index aafae8f1c2..409cc9f699 100644
--- a/modules/websocket/emws_client.cpp
+++ b/modules/websocket/emws_client.cpp
@@ -205,6 +205,12 @@ int EMWSClient::get_max_packet_size() const {
return (1 << _in_buf_size) - PROTO_SIZE;
}
+Error EMWSClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
+ _in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
+ _in_pkt_size = nearest_shift(p_in_packets - 1);
+ return OK;
+}
+
EMWSClient::EMWSClient() {
_in_buf_size = nearest_shift((int)GLOBAL_GET(WSC_IN_BUF) - 1) + 10;
_in_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_IN_PKT) - 1);
diff --git a/modules/websocket/emws_client.h b/modules/websocket/emws_client.h
index 9bc29c1913..1811d05eea 100644
--- a/modules/websocket/emws_client.h
+++ b/modules/websocket/emws_client.h
@@ -49,6 +49,7 @@ private:
public:
bool _is_connecting;
+ Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets);
Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocol = PoolVector<String>());
Ref<WebSocketPeer> get_peer(int p_peer_id) const;
void disconnect_from_host(int p_code = 1000, String p_reason = "");
diff --git a/modules/websocket/emws_server.cpp b/modules/websocket/emws_server.cpp
index 0eef1c4ba9..c4bb459ad0 100644
--- a/modules/websocket/emws_server.cpp
+++ b/modules/websocket/emws_server.cpp
@@ -79,6 +79,10 @@ int EMWSServer::get_max_packet_size() const {
return 0;
}
+Error EMWSServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
+ return OK;
+}
+
EMWSServer::EMWSServer() {
}
diff --git a/modules/websocket/emws_server.h b/modules/websocket/emws_server.h
index bb101cd155..a5e5b4090e 100644
--- a/modules/websocket/emws_server.h
+++ b/modules/websocket/emws_server.h
@@ -42,6 +42,7 @@ class EMWSServer : public WebSocketServer {
GDCIIMPL(EMWSServer, WebSocketServer);
public:
+ Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets);
Error listen(int p_port, PoolVector<String> p_protocols = PoolVector<String>(), bool gd_mp_api = false);
void stop();
bool is_listening() const;
diff --git a/modules/websocket/lws_client.cpp b/modules/websocket/lws_client.cpp
deleted file mode 100644
index 08df76293b..0000000000
--- a/modules/websocket/lws_client.cpp
+++ /dev/null
@@ -1,237 +0,0 @@
-/*************************************************************************/
-/* lws_client.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#ifndef JAVASCRIPT_ENABLED
-
-#include "lws_client.h"
-#include "core/io/ip.h"
-#include "core/project_settings.h"
-#if defined(LWS_OPENSSL_SUPPORT)
-#include "core/io/stream_peer_ssl.h"
-#include "tls/mbedtls/wrapper/include/openssl/ssl.h"
-#endif
-
-Error LWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocols) {
-
- ERR_FAIL_COND_V(context != NULL, FAILED);
-
- IP_Address addr;
-
- if (!p_host.is_valid_ip_address()) {
- addr = IP::get_singleton()->resolve_hostname(p_host);
- } else {
- addr = p_host;
- }
-
- ERR_FAIL_COND_V(!addr.is_valid(), ERR_INVALID_PARAMETER);
-
- // Prepare protocols
- _lws_make_protocols(this, &LWSClient::_lws_gd_callback, p_protocols, &_lws_ref);
-
- // Init lws client
- struct lws_context_creation_info info;
- struct lws_client_connect_info i;
-
- memset(&i, 0, sizeof i);
- memset(&info, 0, sizeof info);
-
- info.port = CONTEXT_PORT_NO_LISTEN;
- info.protocols = _lws_ref->lws_structs;
- info.gid = -1;
- info.uid = -1;
- //info.ws_ping_pong_interval = 5;
- info.user = _lws_ref;
-#if defined(LWS_OPENSSL_SUPPORT)
- info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
-#endif
- context = lws_create_context(&info);
-
- if (context == NULL) {
- _lws_free_ref(_lws_ref);
- _lws_ref = NULL;
- ERR_EXPLAIN("Unable to create lws context");
- ERR_FAIL_V(FAILED);
- }
-
- i.context = context;
- if (p_protocols.size() > 0)
- i.protocol = _lws_ref->lws_names;
- else
- i.protocol = NULL;
-
- if (p_ssl) {
- i.ssl_connection = LCCSCF_USE_SSL;
- if (!verify_ssl)
- i.ssl_connection |= LCCSCF_ALLOW_SELFSIGNED;
- } else {
- i.ssl_connection = 0;
- }
-
- // These CharStrings needs to survive till we call lws_client_connect_via_info
- CharString addr_ch = ((String)addr).ascii();
- CharString host_ch = p_host.utf8();
- CharString path_ch = p_path.utf8();
- i.address = addr_ch.get_data();
- i.host = host_ch.get_data();
- i.path = path_ch.get_data();
- i.port = p_port;
-
- lws_client_connect_via_info(&i);
-
- return OK;
-};
-
-int LWSClient::get_max_packet_size() const {
- return (1 << _out_buf_size) - PROTO_SIZE;
-}
-
-void LWSClient::poll() {
-
- _lws_poll();
-}
-
-int LWSClient::_handle_cb(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) {
-
- Ref<LWSPeer> peer = static_cast<Ref<LWSPeer> >(_peer);
- LWSPeer::PeerData *peer_data = (LWSPeer::PeerData *)user;
-
- switch (reason) {
-#if defined(LWS_OPENSSL_SUPPORT)
- case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: {
- PoolByteArray arr = StreamPeerSSL::get_project_cert_array();
- if (arr.size() > 0)
- SSL_CTX_add_client_CA((SSL_CTX *)user, d2i_X509(NULL, &arr.read()[0], arr.size()));
- else if (verify_ssl)
- WARN_PRINTS("No CA cert specified in project settings, SSL will not work");
- } break;
-#endif
- case LWS_CALLBACK_CLIENT_ESTABLISHED:
- peer->set_wsi(wsi, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
- peer_data->peer_id = 0;
- peer_data->force_close = false;
- peer_data->clean_close = false;
- _on_connect(lws_get_protocol(wsi)->name);
- break;
-
- case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
- _on_error();
- destroy_context();
- return -1; // We should close the connection (would probably happen anyway)
-
- case LWS_CALLBACK_WS_PEER_INITIATED_CLOSE: {
- int code;
- String reason2 = peer->get_close_reason(in, len, code);
- peer_data->clean_close = true;
- _on_close_request(code, reason2);
- return 0;
- }
-
- case LWS_CALLBACK_CLIENT_CLOSED:
- peer->close();
- destroy_context();
- _on_disconnect(peer_data->clean_close);
- return 0; // We can end here
-
- case LWS_CALLBACK_CLIENT_RECEIVE:
- peer->read_wsi(in, len);
- if (peer->get_available_packet_count() > 0)
- _on_peer_packet();
- break;
-
- case LWS_CALLBACK_CLIENT_WRITEABLE:
- if (peer_data->force_close) {
- peer->send_close_status(wsi);
- return -1;
- }
-
- peer->write_wsi();
- break;
-
- default:
- break;
- }
-
- return 0;
-}
-
-Ref<WebSocketPeer> LWSClient::get_peer(int p_peer_id) const {
-
- return _peer;
-}
-
-NetworkedMultiplayerPeer::ConnectionStatus LWSClient::get_connection_status() const {
-
- if (context == NULL)
- return CONNECTION_DISCONNECTED;
-
- if (_peer->is_connected_to_host())
- return CONNECTION_CONNECTED;
-
- return CONNECTION_CONNECTING;
-}
-
-void LWSClient::disconnect_from_host(int p_code, String p_reason) {
-
- if (context == NULL)
- return;
-
- _peer->close(p_code, p_reason);
-};
-
-IP_Address LWSClient::get_connected_host() const {
-
- return IP_Address();
-};
-
-uint16_t LWSClient::get_connected_port() const {
-
- return 1025;
-};
-
-LWSClient::LWSClient() {
- _in_buf_size = nearest_shift((int)GLOBAL_GET(WSC_IN_BUF) - 1) + 10;
- _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_IN_PKT) - 1);
- _out_buf_size = nearest_shift((int)GLOBAL_GET(WSC_OUT_BUF) - 1) + 10;
- _out_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_OUT_PKT) - 1);
-
- context = NULL;
- _lws_ref = NULL;
- _peer = Ref<LWSPeer>(memnew(LWSPeer));
-};
-
-LWSClient::~LWSClient() {
-
- invalidate_lws_ref(); // We do not want any more callback
- disconnect_from_host();
- destroy_context();
- _peer = Ref<LWSPeer>();
-};
-
-#endif // JAVASCRIPT_ENABLED
diff --git a/modules/websocket/lws_helper.cpp b/modules/websocket/lws_helper.cpp
deleted file mode 100644
index a652779960..0000000000
--- a/modules/websocket/lws_helper.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-/*************************************************************************/
-/* lws_helper.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#if !defined(JAVASCRIPT_ENABLED)
-
-#include "lws_helper.h"
-
-_LWSRef *_lws_create_ref(void *obj) {
-
- _LWSRef *out = (_LWSRef *)memalloc(sizeof(_LWSRef));
- out->is_destroying = false;
- out->free_context = false;
- out->is_polling = false;
- out->obj = obj;
- out->is_valid = true;
- out->lws_structs = NULL;
- out->lws_names = NULL;
- return out;
-}
-
-void _lws_free_ref(_LWSRef *ref) {
- // Free strings and structs
- memfree(ref->lws_structs);
- memfree(ref->lws_names);
- // Free ref
- memfree(ref);
-}
-
-bool _lws_destroy(struct lws_context *context, _LWSRef *ref) {
- if (context == NULL || ref->is_destroying)
- return false;
-
- if (ref->is_polling) {
- ref->free_context = true;
- return false;
- }
-
- ref->is_destroying = true;
- lws_context_destroy(context);
- _lws_free_ref(ref);
- return true;
-}
-
-bool _lws_poll(struct lws_context *context, _LWSRef *ref) {
-
- ERR_FAIL_COND_V(context == NULL, false);
- ERR_FAIL_COND_V(ref == NULL, false);
-
- ref->is_polling = true;
- lws_service(context, 0);
- ref->is_polling = false;
-
- if (!ref->free_context)
- return false; // Nothing to do
-
- bool is_valid = ref->is_valid; // Might have been destroyed by poll
-
- _lws_destroy(context, ref); // Will destroy context and ref
-
- return is_valid; // If the object should NULL its context and ref
-}
-
-/*
- * Prepare the protocol_structs to be fed to context.
- * Also prepare the protocol string used by the client.
- */
-void _lws_make_protocols(void *p_obj, lws_callback_function *p_callback, PoolVector<String> p_names, _LWSRef **r_lws_ref) {
- // The input strings might go away after this call, we need to copy them.
- // We will clear them when destroying the context.
- int i;
- int len = p_names.size();
- size_t data_size = sizeof(struct LWSPeer::PeerData);
- PoolVector<String>::Read pnr = p_names.read();
-
- // This is a reference connecting the object with lws keep track of status, mallocs, etc.
- // Must survive as long the context.
- // Must be freed manually when context creation fails.
- _LWSRef *ref = _lws_create_ref(p_obj);
-
- // LWS protocol structs.
- ref->lws_structs = (struct lws_protocols *)memalloc(sizeof(struct lws_protocols) * (len + 2));
- memset(ref->lws_structs, 0, sizeof(struct lws_protocols) * (len + 2));
-
- CharString strings = p_names.join(",").ascii();
- int str_len = strings.length();
-
- // Joined string of protocols, double the size: comma separated first, NULL separated last
- ref->lws_names = (char *)memalloc((str_len + 1) * 2); // Plus the terminator
-
- char *names_ptr = ref->lws_names;
- struct lws_protocols *structs_ptr = ref->lws_structs;
-
- // Comma separated protocols string to be used in client Sec-WebSocket-Protocol header
- if (str_len > 0)
- copymem(names_ptr, strings.get_data(), str_len);
- names_ptr[str_len] = '\0'; // NULL terminator
-
- // NULL terminated protocol strings to be used in protocol structs
- if (str_len > 0)
- copymem(&names_ptr[str_len + 1], strings.get_data(), str_len);
- names_ptr[(str_len * 2) + 1] = '\0'; // NULL terminator
- int pos = str_len + 1;
-
- // The first protocol is the default for any http request (before upgrade).
- // It is also used as the websocket protocol when no subprotocol is specified.
- structs_ptr[0].name = "default";
- structs_ptr[0].callback = p_callback;
- structs_ptr[0].per_session_data_size = data_size;
- structs_ptr[0].rx_buffer_size = LWS_BUF_SIZE;
- structs_ptr[0].tx_packet_size = LWS_PACKET_SIZE;
- // Add user defined protocols
- for (i = 0; i < len; i++) {
- structs_ptr[i + 1].name = (const char *)&names_ptr[pos];
- structs_ptr[i + 1].callback = p_callback;
- structs_ptr[i + 1].per_session_data_size = data_size;
- structs_ptr[i + 1].rx_buffer_size = LWS_BUF_SIZE;
- structs_ptr[i + 1].tx_packet_size = LWS_PACKET_SIZE;
- pos += pnr[i].ascii().length() + 1;
- names_ptr[pos - 1] = '\0';
- }
- // Add protocols terminator
- structs_ptr[len + 1].name = NULL;
- structs_ptr[len + 1].callback = NULL;
- structs_ptr[len + 1].per_session_data_size = 0;
- structs_ptr[len + 1].rx_buffer_size = 0;
-
- *r_lws_ref = ref;
-}
-
-#endif
diff --git a/modules/websocket/lws_helper.h b/modules/websocket/lws_helper.h
deleted file mode 100644
index 265dc4e6ad..0000000000
--- a/modules/websocket/lws_helper.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/*************************************************************************/
-/* lws_helper.h */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#ifndef LWS_HELPER_H
-#define LWS_HELPER_H
-
-#define LWS_BUF_SIZE 65536
-#define LWS_PACKET_SIZE LWS_BUF_SIZE
-
-#include "core/io/stream_peer.h"
-#include "core/os/os.h"
-#include "core/reference.h"
-#include "core/ring_buffer.h"
-#include "lws_peer.h"
-
-struct _LWSRef {
- bool free_context;
- bool is_polling;
- bool is_valid;
- bool is_destroying;
- void *obj;
- struct lws_protocols *lws_structs;
- char *lws_names;
-};
-
-_LWSRef *_lws_create_ref(void *obj);
-void _lws_free_ref(_LWSRef *ref);
-bool _lws_destroy(struct lws_context *context, _LWSRef *ref);
-bool _lws_poll(struct lws_context *context, _LWSRef *ref);
-void _lws_make_protocols(void *p_obj, lws_callback_function *p_callback, PoolVector<String> p_names, _LWSRef **r_lws_ref);
-
-/* clang-format off */
-#define LWS_HELPER(CNAME) \
-protected: \
- struct _LWSRef *_lws_ref; \
- struct lws_context *context; \
- bool _keep_servicing; \
- \
- static int _lws_gd_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { \
- \
- if (wsi == NULL) { \
- return 0; \
- } \
- \
- struct _LWSRef *ref = (struct _LWSRef *)lws_context_user(lws_get_context(wsi)); \
- if (!ref->is_valid) \
- return 0; \
- CNAME *helper = (CNAME *)ref->obj; \
- helper->_keep_servicing = true; \
- return helper->_handle_cb(wsi, reason, user, in, len); \
- } \
- \
- void invalidate_lws_ref() { \
- if (_lws_ref != NULL) \
- _lws_ref->is_valid = false; \
- } \
- \
- void destroy_context() { \
- if (_lws_destroy(context, _lws_ref)) { \
- context = NULL; \
- _lws_ref = NULL; \
- } \
- } \
- \
-public: \
- virtual int _handle_cb(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len); \
- \
- void _lws_poll() { \
- ERR_FAIL_COND(context == NULL); \
- do { \
- _keep_servicing = false; \
- if (::_lws_poll(context, _lws_ref)) { \
- context = NULL; \
- _lws_ref = NULL; \
- break; \
- } \
- } while (_keep_servicing); \
- } \
- \
-protected:
-
-/* clang-format on */
-
-#endif // LWS_HELPER_H
diff --git a/modules/websocket/lws_peer.cpp b/modules/websocket/lws_peer.cpp
deleted file mode 100644
index a7c85450fa..0000000000
--- a/modules/websocket/lws_peer.cpp
+++ /dev/null
@@ -1,270 +0,0 @@
-/*************************************************************************/
-/* lws_peer.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#ifndef JAVASCRIPT_ENABLED
-
-#include "lws_peer.h"
-
-#include "core/io/ip.h"
-
-// Needed for socket_helpers on Android at least. UNIXes has it, just include if not windows
-#if !defined(WINDOWS_ENABLED)
-#include <netinet/in.h>
-#include <sys/socket.h>
-#endif
-
-#include "drivers/unix/net_socket_posix.h"
-
-void LWSPeer::set_wsi(struct lws *p_wsi, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size) {
- ERR_FAIL_COND(wsi != NULL);
-
- _in_buffer.resize(p_in_pkt_size, p_in_buf_size);
- _out_buffer.resize(p_out_pkt_size, p_out_buf_size);
- _packet_buffer.resize((1 << MAX(p_in_buf_size, p_out_buf_size)) + LWS_PRE);
- wsi = p_wsi;
-};
-
-void LWSPeer::set_write_mode(WriteMode p_mode) {
- write_mode = p_mode;
-}
-
-LWSPeer::WriteMode LWSPeer::get_write_mode() const {
- return write_mode;
-}
-
-Error LWSPeer::read_wsi(void *in, size_t len) {
-
- ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
-
- if (lws_is_first_fragment(wsi))
- _in_size = 0;
- else if (_in_size == -1) // Trash this frame
- return ERR_FILE_CORRUPT;
-
- Error err = _in_buffer.write_packet((const uint8_t *)in, len, NULL);
-
- if (err != OK) {
- _in_buffer.discard_payload(_in_size);
- _in_size = -1;
- ERR_FAIL_V(err);
- }
-
- _in_size += len;
-
- if (lws_is_final_fragment(wsi)) {
- uint8_t is_string = lws_frame_is_binary(wsi) ? 0 : 1;
- err = _in_buffer.write_packet(NULL, _in_size, &is_string);
- if (err != OK) {
- _in_buffer.discard_payload(_in_size);
- _in_size = -1;
- ERR_FAIL_V(err);
- }
- }
-
- return OK;
-}
-
-Error LWSPeer::write_wsi() {
-
- ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
-
- PoolVector<uint8_t> tmp;
- int count = _out_buffer.packets_left();
-
- if (count == 0)
- return OK;
-
- int read = 0;
- uint8_t is_string = 0;
- PoolVector<uint8_t>::Write rw = _packet_buffer.write();
- _out_buffer.read_packet(&(rw[LWS_PRE]), _packet_buffer.size() - LWS_PRE, &is_string, read);
-
- enum lws_write_protocol mode = is_string ? LWS_WRITE_TEXT : LWS_WRITE_BINARY;
- lws_write(wsi, &(rw[LWS_PRE]), read, mode);
-
- if (count > 1)
- lws_callback_on_writable(wsi); // we want to write more!
-
- return OK;
-}
-
-Error LWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
-
- ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
-
- uint8_t is_string = write_mode == WRITE_MODE_TEXT;
- _out_buffer.write_packet(p_buffer, p_buffer_size, &is_string);
- lws_callback_on_writable(wsi); // notify that we want to write
- return OK;
-};
-
-Error LWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
-
- r_buffer_size = 0;
-
- ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
-
- if (_in_buffer.packets_left() == 0)
- return ERR_UNAVAILABLE;
-
- int read = 0;
- PoolVector<uint8_t>::Write rw = _packet_buffer.write();
- _in_buffer.read_packet(rw.ptr(), _packet_buffer.size(), &_is_string, read);
-
- *r_buffer = rw.ptr();
- r_buffer_size = read;
-
- return OK;
-};
-
-int LWSPeer::get_available_packet_count() const {
-
- if (!is_connected_to_host())
- return 0;
-
- return _in_buffer.packets_left();
-};
-
-bool LWSPeer::was_string_packet() const {
-
- return _is_string;
-};
-
-bool LWSPeer::is_connected_to_host() const {
-
- return wsi != NULL;
-};
-
-String LWSPeer::get_close_reason(void *in, size_t len, int &r_code) {
- String s;
- r_code = 0;
- if (len < 2) // From docs this should not happen
- return s;
-
- const uint8_t *b = (const uint8_t *)in;
- r_code = b[0] << 8 | b[1];
-
- if (len > 2) {
- const char *utf8 = (const char *)&b[2];
- s.parse_utf8(utf8, len - 2);
- }
- return s;
-}
-
-void LWSPeer::send_close_status(struct lws *p_wsi) {
- if (close_code == -1)
- return;
-
- int len = close_reason.size();
- ERR_FAIL_COND(len > 123); // Maximum allowed reason size in bytes
-
- lws_close_status code = (lws_close_status)close_code;
- unsigned char *reason = len > 0 ? (unsigned char *)close_reason.utf8().ptrw() : NULL;
-
- lws_close_reason(p_wsi, code, reason, len);
-
- close_code = -1;
- close_reason = "";
-}
-
-void LWSPeer::close(int p_code, String p_reason) {
- if (wsi != NULL) {
- close_code = p_code;
- close_reason = p_reason;
- PeerData *data = ((PeerData *)lws_wsi_user(wsi));
- data->force_close = true;
- data->clean_close = true;
- lws_callback_on_writable(wsi); // Notify that we want to disconnect
- } else {
- close_code = -1;
- close_reason = "";
- }
- wsi = NULL;
- _in_buffer.clear();
- _out_buffer.clear();
- _in_size = 0;
- _is_string = 0;
- _packet_buffer.resize(0);
-};
-
-IP_Address LWSPeer::get_connected_host() const {
-
- ERR_FAIL_COND_V(!is_connected_to_host(), IP_Address());
-
- IP_Address ip;
- uint16_t port = 0;
-
- struct sockaddr_storage addr;
- socklen_t len = sizeof(addr);
-
- int fd = lws_get_socket_fd(wsi);
- ERR_FAIL_COND_V(fd == -1, IP_Address());
-
- int ret = getpeername(fd, (struct sockaddr *)&addr, &len);
- ERR_FAIL_COND_V(ret != 0, IP_Address());
-
- NetSocketPosix::_set_ip_port(&addr, ip, port);
-
- return ip;
-};
-
-uint16_t LWSPeer::get_connected_port() const {
-
- ERR_FAIL_COND_V(!is_connected_to_host(), 0);
-
- IP_Address ip;
- uint16_t port = 0;
-
- struct sockaddr_storage addr;
- socklen_t len = sizeof(addr);
-
- int fd = lws_get_socket_fd(wsi);
- ERR_FAIL_COND_V(fd == -1, 0);
-
- int ret = getpeername(fd, (struct sockaddr *)&addr, &len);
- ERR_FAIL_COND_V(ret != 0, 0);
-
- NetSocketPosix::_set_ip_port(&addr, ip, port);
-
- return port;
-};
-
-LWSPeer::LWSPeer() {
- wsi = NULL;
- write_mode = WRITE_MODE_BINARY;
- close();
-};
-
-LWSPeer::~LWSPeer() {
-
- close();
-};
-
-#endif // JAVASCRIPT_ENABLED
diff --git a/modules/websocket/lws_server.cpp b/modules/websocket/lws_server.cpp
deleted file mode 100644
index 61ccdca74a..0000000000
--- a/modules/websocket/lws_server.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/*************************************************************************/
-/* lws_server.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#ifndef JAVASCRIPT_ENABLED
-
-#include "lws_server.h"
-#include "core/os/os.h"
-#include "core/project_settings.h"
-
-Error LWSServer::listen(int p_port, PoolVector<String> p_protocols, bool gd_mp_api) {
-
- ERR_FAIL_COND_V(context != NULL, FAILED);
-
- _is_multiplayer = gd_mp_api;
-
- struct lws_context_creation_info info;
- memset(&info, 0, sizeof info);
-
- // Prepare lws protocol structs
- _lws_make_protocols(this, &LWSServer::_lws_gd_callback, p_protocols, &_lws_ref);
-
- info.port = p_port;
- info.user = _lws_ref;
- info.protocols = _lws_ref->lws_structs;
- info.gid = -1;
- info.uid = -1;
- //info.ws_ping_pong_interval = 5;
-
- context = lws_create_context(&info);
-
- if (context == NULL) {
- _lws_free_ref(_lws_ref);
- _lws_ref = NULL;
- ERR_EXPLAIN("Unable to create LWS context");
- ERR_FAIL_V(FAILED);
- }
-
- return OK;
-}
-
-bool LWSServer::is_listening() const {
- return context != NULL;
-}
-
-int LWSServer::get_max_packet_size() const {
- return (1 << _out_buf_size) - PROTO_SIZE;
-}
-
-int LWSServer::_handle_cb(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) {
-
- LWSPeer::PeerData *peer_data = (LWSPeer::PeerData *)user;
-
- switch (reason) {
- case LWS_CALLBACK_HTTP:
- // no http for now
- // closing immediately returning -1;
- return -1;
-
- case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
- // check header here?
- break;
-
- case LWS_CALLBACK_ESTABLISHED: {
- int32_t id = _gen_unique_id();
-
- Ref<LWSPeer> peer = Ref<LWSPeer>(memnew(LWSPeer));
- peer->set_wsi(wsi, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
- _peer_map[id] = peer;
-
- peer_data->peer_id = id;
- peer_data->force_close = false;
- peer_data->clean_close = false;
- _on_connect(id, lws_get_protocol(wsi)->name);
- break;
- }
-
- case LWS_CALLBACK_WS_PEER_INITIATED_CLOSE: {
- if (peer_data == NULL)
- return 0;
-
- int32_t id = peer_data->peer_id;
- if (_peer_map.has(id)) {
- int code;
- Ref<LWSPeer> peer = _peer_map[id];
- String reason2 = peer->get_close_reason(in, len, code);
- peer_data->clean_close = true;
- _on_close_request(id, code, reason2);
- }
- return 0;
- }
-
- case LWS_CALLBACK_CLOSED: {
- if (peer_data == NULL)
- return 0;
- int32_t id = peer_data->peer_id;
- bool clean = peer_data->clean_close;
- if (_peer_map.has(id)) {
- _peer_map[id]->close();
- _peer_map.erase(id);
- }
- _on_disconnect(id, clean);
- return 0; // we can end here
- }
-
- case LWS_CALLBACK_RECEIVE: {
- int32_t id = peer_data->peer_id;
- if (_peer_map.has(id)) {
- static_cast<Ref<LWSPeer> >(_peer_map[id])->read_wsi(in, len);
- if (_peer_map[id]->get_available_packet_count() > 0)
- _on_peer_packet(id);
- }
- break;
- }
-
- case LWS_CALLBACK_SERVER_WRITEABLE: {
- int id = peer_data->peer_id;
- if (peer_data->force_close) {
- if (_peer_map.has(id)) {
- Ref<LWSPeer> peer = _peer_map[id];
- peer->send_close_status(wsi);
- }
- return -1;
- }
-
- if (_peer_map.has(id))
- static_cast<Ref<LWSPeer> >(_peer_map[id])->write_wsi();
- break;
- }
-
- default:
- break;
- }
-
- return 0;
-}
-
-void LWSServer::stop() {
- if (context == NULL)
- return;
-
- _peer_map.clear();
- destroy_context();
- context = NULL;
-}
-
-bool LWSServer::has_peer(int p_id) const {
- return _peer_map.has(p_id);
-}
-
-Ref<WebSocketPeer> LWSServer::get_peer(int p_id) const {
- ERR_FAIL_COND_V(!has_peer(p_id), NULL);
- return _peer_map[p_id];
-}
-
-IP_Address LWSServer::get_peer_address(int p_peer_id) const {
- ERR_FAIL_COND_V(!has_peer(p_peer_id), IP_Address());
-
- return _peer_map[p_peer_id]->get_connected_host();
-}
-
-int LWSServer::get_peer_port(int p_peer_id) const {
- ERR_FAIL_COND_V(!has_peer(p_peer_id), 0);
-
- return _peer_map[p_peer_id]->get_connected_port();
-}
-
-void LWSServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
- ERR_FAIL_COND(!has_peer(p_peer_id));
-
- get_peer(p_peer_id)->close(p_code, p_reason);
-}
-
-LWSServer::LWSServer() {
- _in_buf_size = nearest_shift((int)GLOBAL_GET(WSS_IN_BUF) - 1) + 10;
- _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_IN_PKT) - 1);
- _out_buf_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_BUF) - 1) + 10;
- _out_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_PKT) - 1);
- context = NULL;
- _lws_ref = NULL;
-}
-
-LWSServer::~LWSServer() {
- invalidate_lws_ref(); // we do not want any more callbacks
- stop();
-}
-
-#endif // JAVASCRIPT_ENABLED
diff --git a/modules/websocket/register_types.cpp b/modules/websocket/register_types.cpp
index 39bf3de982..1c808f0d5c 100644
--- a/modules/websocket/register_types.cpp
+++ b/modules/websocket/register_types.cpp
@@ -37,9 +37,8 @@
#include "emws_peer.h"
#include "emws_server.h"
#else
-#include "lws_client.h"
-#include "lws_peer.h"
-#include "lws_server.h"
+#include "wsl_client.h"
+#include "wsl_server.h"
#endif
void register_websocket_types() {
@@ -64,9 +63,9 @@ void register_websocket_types() {
EMWSClient::make_default();
EMWSServer::make_default();
#else
- LWSPeer::make_default();
- LWSClient::make_default();
- LWSServer::make_default();
+ WSLPeer::make_default();
+ WSLClient::make_default();
+ WSLServer::make_default();
#endif
ClassDB::register_virtual_class<WebSocketMultiplayerPeer>();
diff --git a/modules/websocket/websocket_client.h b/modules/websocket/websocket_client.h
index c464d97c7f..7ddb9468a5 100644
--- a/modules/websocket/websocket_client.h
+++ b/modules/websocket/websocket_client.h
@@ -67,6 +67,8 @@ public:
void _on_disconnect(bool p_was_clean);
void _on_error();
+ virtual Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) = 0;
+
WebSocketClient();
~WebSocketClient();
};
diff --git a/modules/websocket/websocket_multiplayer_peer.cpp b/modules/websocket/websocket_multiplayer_peer.cpp
index 6aab8a7e81..e24cb850ec 100644
--- a/modules/websocket/websocket_multiplayer_peer.cpp
+++ b/modules/websocket/websocket_multiplayer_peer.cpp
@@ -87,6 +87,7 @@ void WebSocketMultiplayerPeer::_clear() {
void WebSocketMultiplayerPeer::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_buffers", "input_buffer_size_kb", "input_max_packets", "output_buffer_size_kb", "output_max_packets"), &WebSocketMultiplayerPeer::set_buffers);
ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebSocketMultiplayerPeer::get_peer);
ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "peer_source")));
@@ -190,7 +191,7 @@ void WebSocketMultiplayerPeer::_send_sys(Ref<WebSocketPeer> p_peer, uint8_t p_ty
p_peer->put_packet(&(message.read()[0]), message.size());
}
-PoolVector<uint8_t> WebSocketMultiplayerPeer::_make_pkt(uint32_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size) {
+PoolVector<uint8_t> WebSocketMultiplayerPeer::_make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size) {
PoolVector<uint8_t> out;
out.resize(PROTO_SIZE + p_data_size);
diff --git a/modules/websocket/websocket_multiplayer_peer.h b/modules/websocket/websocket_multiplayer_peer.h
index b050449ee0..e3ab0784ab 100644
--- a/modules/websocket/websocket_multiplayer_peer.h
+++ b/modules/websocket/websocket_multiplayer_peer.h
@@ -41,7 +41,7 @@ class WebSocketMultiplayerPeer : public NetworkedMultiplayerPeer {
GDCLASS(WebSocketMultiplayerPeer, NetworkedMultiplayerPeer);
private:
- PoolVector<uint8_t> _make_pkt(uint32_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size);
+ PoolVector<uint8_t> _make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size);
void _store_pkt(int32_t p_source, int32_t p_dest, const uint8_t *p_data, uint32_t p_data_size);
Error _server_relay(int32_t p_from, int32_t p_to, const uint8_t *p_buffer, uint32_t p_buffer_size);
@@ -82,7 +82,7 @@ public:
/* NetworkedMultiplayerPeer */
void set_transfer_mode(TransferMode p_mode);
TransferMode get_transfer_mode() const;
- void set_target_peer(int p_peer_id);
+ void set_target_peer(int p_target_peer);
int get_packet_peer() const;
int get_unique_id() const;
virtual bool is_server() const = 0;
@@ -97,6 +97,7 @@ public:
virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
/* WebSocketPeer */
+ virtual Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) = 0;
virtual Ref<WebSocketPeer> get_peer(int p_peer_id) const = 0;
void _process_multiplayer(Ref<WebSocketPeer> p_peer, uint32_t p_peer_id);
diff --git a/modules/websocket/websocket_server.h b/modules/websocket/websocket_server.h
index 7a94c4047b..83c0c10419 100644
--- a/modules/websocket/websocket_server.h
+++ b/modules/websocket/websocket_server.h
@@ -62,6 +62,8 @@ public:
void _on_disconnect(int32_t p_peer_id, bool p_was_clean);
void _on_close_request(int32_t p_peer_id, int p_code, String p_reason);
+ virtual Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) = 0;
+
WebSocketServer();
~WebSocketServer();
};
diff --git a/modules/websocket/wsl_client.cpp b/modules/websocket/wsl_client.cpp
new file mode 100644
index 0000000000..86374e8f80
--- /dev/null
+++ b/modules/websocket/wsl_client.cpp
@@ -0,0 +1,363 @@
+/*************************************************************************/
+/* wsl_client.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef JAVASCRIPT_ENABLED
+
+#include "wsl_client.h"
+#include "core/io/ip.h"
+#include "core/project_settings.h"
+
+void WSLClient::_do_handshake() {
+ if (_requested < _request.size() - 1) {
+ int sent = 0;
+ Error err = _connection->put_partial_data(((const uint8_t *)_request.get_data() + _requested), _request.size() - _requested - 1, sent);
+ // Sending handshake failed
+ if (err != OK) {
+ disconnect_from_host();
+ _on_error();
+ return;
+ }
+ _requested += sent;
+
+ } else {
+ int read = 0;
+ while (true) {
+ if (_resp_pos >= WSL_MAX_HEADER_SIZE) {
+ // Header is too big
+ disconnect_from_host();
+ _on_error();
+ ERR_EXPLAIN("Response headers too big");
+ ERR_FAIL();
+ }
+ Error err = _connection->get_partial_data(&_resp_buf[_resp_pos], 1, read);
+ if (err == ERR_FILE_EOF) {
+ // We got a disconnect.
+ disconnect_from_host();
+ _on_error();
+ return;
+ } else if (err != OK) {
+ // Got some error.
+ disconnect_from_host();
+ _on_error();
+ return;
+ } else if (read != 1) {
+ // Busy, wait next poll.
+ break;
+ }
+ // Check "\r\n\r\n" header terminator
+ char *r = (char *)_resp_buf;
+ int l = _resp_pos;
+ if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
+ r[l - 3] = '\0';
+ String protocol;
+ // Response is over, verify headers and create peer.
+ if (!_verify_headers(protocol)) {
+ disconnect_from_host();
+ _on_error();
+ ERR_EXPLAIN("Invalid response headers");
+ ERR_FAIL();
+ }
+ // Create peer.
+ WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
+ data->obj = this;
+ data->conn = _connection;
+ data->is_server = false;
+ data->id = 1;
+ _peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
+ _on_connect(protocol);
+ break;
+ }
+ _resp_pos += 1;
+ }
+ }
+}
+
+bool WSLClient::_verify_headers(String &r_protocol) {
+ String s = (char *)_resp_buf;
+ Vector<String> psa = s.split("\r\n");
+ int len = psa.size();
+ if (len < 4) {
+ ERR_EXPLAIN("Not enough response headers.");
+ ERR_FAIL_V(false);
+ }
+
+ Vector<String> req = psa[0].split(" ", false);
+ if (req.size() < 2) {
+ ERR_EXPLAIN("Invalid protocol or status code.");
+ ERR_FAIL_V(false);
+ }
+ // Wrong protocol
+ if (req[0] != "HTTP/1.1" || req[1] != "101") {
+ ERR_EXPLAIN("Invalid protocol or status code.");
+ ERR_FAIL_V(false);
+ }
+
+ Map<String, String> headers;
+ for (int i = 1; i < len; i++) {
+ Vector<String> header = psa[i].split(":", false, 1);
+ if (header.size() != 2) {
+ ERR_EXPLAIN("Invalid header -> " + psa[i]);
+ ERR_FAIL_V(false);
+ }
+ String name = header[0].to_lower();
+ String value = header[1].strip_edges();
+ if (headers.has(name))
+ headers[name] += "," + value;
+ else
+ headers[name] = value;
+ }
+
+#define _WLS_EXPLAIN(NAME, VALUE) \
+ ERR_EXPLAIN("Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'");
+#define _WLS_CHECK(NAME, VALUE) \
+ _WLS_EXPLAIN(NAME, VALUE); \
+ ERR_FAIL_COND_V(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false);
+#define _WLS_CHECK_NC(NAME, VALUE) \
+ _WLS_EXPLAIN(NAME, VALUE); \
+ ERR_FAIL_COND_V(!headers.has(NAME) || headers[NAME] != VALUE, false);
+ _WLS_CHECK("connection", "upgrade");
+ _WLS_CHECK("upgrade", "websocket");
+ _WLS_CHECK_NC("sec-websocket-accept", WSLPeer::compute_key_response(_key));
+ if (_protocols.size() == 0) {
+ // We didn't request a custom protocol
+ ERR_FAIL_COND_V(headers.has("sec-websocket-protocol"), false);
+ } else {
+ ERR_FAIL_COND_V(!headers.has("sec-websocket-protocol"), false);
+ r_protocol = headers["sec-websocket-protocol"];
+ bool valid = false;
+ for (int i = 0; i < _protocols.size(); i++) {
+ if (_protocols[i] != r_protocol)
+ continue;
+ valid = true;
+ break;
+ }
+ if (!valid)
+ return false;
+ }
+#undef _WLS_CHECK_NC
+#undef _WLS_CHECK
+#undef _WLS_EXPLAIN
+
+ return true;
+}
+
+Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocols) {
+
+ ERR_FAIL_COND_V(_connection.is_valid(), ERR_ALREADY_IN_USE);
+
+ _peer = Ref<WSLPeer>(memnew(WSLPeer));
+ IP_Address addr;
+
+ if (!p_host.is_valid_ip_address()) {
+ addr = IP::get_singleton()->resolve_hostname(p_host);
+ } else {
+ addr = p_host;
+ }
+
+ ERR_FAIL_COND_V(!addr.is_valid(), ERR_INVALID_PARAMETER);
+
+ String port = "";
+ if ((p_port != 80 && !p_ssl) || (p_port != 443 && p_ssl)) {
+ port = ":" + itos(p_port);
+ }
+
+ Error err = _tcp->connect_to_host(addr, p_port);
+ if (err != OK) {
+ _on_error();
+ _tcp->disconnect_from_host();
+ return err;
+ }
+ _connection = _tcp;
+ _use_ssl = p_ssl;
+ _host = p_host;
+ _protocols = p_protocols;
+
+ _key = WSLPeer::generate_key();
+ // TODO custom extra headers (allow overriding this too?)
+ String request = "GET " + p_path + " HTTP/1.1\r\n";
+ request += "Host: " + p_host + port + "\r\n";
+ request += "Upgrade: websocket\r\n";
+ request += "Connection: Upgrade\r\n";
+ request += "Sec-WebSocket-Key: " + _key + "\r\n";
+ request += "Sec-WebSocket-Version: 13\r\n";
+ if (p_protocols.size() > 0) {
+ request += "Sec-WebSocket-Protocol: ";
+ for (int i = 0; i < p_protocols.size(); i++) {
+ if (i != 0)
+ request += ",";
+ request += p_protocols[i];
+ }
+ request += "\r\n";
+ }
+ request += "\r\n";
+ _request = request.utf8();
+
+ return OK;
+}
+
+int WSLClient::get_max_packet_size() const {
+ return (1 << _out_buf_size) - PROTO_SIZE;
+}
+
+void WSLClient::poll() {
+ if (_peer->is_connected_to_host()) {
+ _peer->poll();
+ if (!_peer->is_connected_to_host()) {
+ _on_disconnect(_peer->close_code != -1);
+ disconnect_from_host();
+ }
+ return;
+ }
+
+ if (_connection.is_null())
+ return; // Not connected.
+
+ switch (_tcp->get_status()) {
+ case StreamPeerTCP::STATUS_NONE:
+ // Clean close
+ _on_error();
+ disconnect_from_host();
+ break;
+ case StreamPeerTCP::STATUS_CONNECTED: {
+ Ref<StreamPeerSSL> ssl;
+ if (_use_ssl) {
+ if (_connection == _tcp) {
+ // Start SSL handshake
+ ssl = Ref<StreamPeerSSL>(StreamPeerSSL::create());
+ ERR_EXPLAIN("SSL is not available in this build");
+ ERR_FAIL_COND(ssl.is_null());
+ ssl->set_blocking_handshake_enabled(false);
+ if (ssl->connect_to_stream(_tcp, verify_ssl, _host) != OK) {
+ _on_error();
+ disconnect_from_host();
+ return;
+ }
+ _connection = ssl;
+ } else {
+ ssl = static_cast<Ref<StreamPeerSSL> >(_connection);
+ ERR_FAIL_COND(ssl.is_null()); // Bug?
+ ssl->poll();
+ }
+ if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING)
+ return; // Need more polling.
+ else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) {
+ _on_error();
+ disconnect_from_host();
+ return; // Error.
+ }
+ }
+ // Do websocket handshake.
+ _do_handshake();
+ } break;
+ case StreamPeerTCP::STATUS_ERROR:
+ _on_error();
+ disconnect_from_host();
+ break;
+ case StreamPeerTCP::STATUS_CONNECTING:
+ break; // Wait for connection
+ }
+}
+
+Ref<WebSocketPeer> WSLClient::get_peer(int p_peer_id) const {
+
+ ERR_FAIL_COND_V(p_peer_id != 1, NULL);
+
+ return _peer;
+}
+
+NetworkedMultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const {
+
+ if (_peer->is_connected_to_host())
+ return CONNECTION_CONNECTED;
+
+ if (_tcp->is_connected_to_host())
+ return CONNECTION_CONNECTING;
+
+ return CONNECTION_DISCONNECTED;
+}
+
+void WSLClient::disconnect_from_host(int p_code, String p_reason) {
+
+ _peer->close(p_code, p_reason);
+ _connection = Ref<StreamPeer>(NULL);
+ _tcp = Ref<StreamPeerTCP>(memnew(StreamPeerTCP));
+
+ _key = "";
+ _host = "";
+ _protocols.resize(0);
+ _use_ssl = false;
+
+ _request = "";
+ _requested = 0;
+
+ memset(_resp_buf, 0, sizeof(_resp_buf));
+ _resp_pos = 0;
+}
+
+IP_Address WSLClient::get_connected_host() const {
+
+ return IP_Address();
+}
+
+uint16_t WSLClient::get_connected_port() const {
+
+ return 1025;
+}
+
+Error WSLClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
+ ERR_EXPLAIN("Buffers sizes can only be set before listening or connecting");
+ ERR_FAIL_COND_V(_connection.is_valid(), FAILED);
+
+ _in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
+ _in_pkt_size = nearest_shift(p_in_packets - 1);
+ _out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
+ _out_pkt_size = nearest_shift(p_out_packets - 1);
+ return OK;
+}
+
+WSLClient::WSLClient() {
+ _in_buf_size = nearest_shift((int)GLOBAL_GET(WSC_IN_BUF) - 1) + 10;
+ _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_IN_PKT) - 1);
+ _out_buf_size = nearest_shift((int)GLOBAL_GET(WSC_OUT_BUF) - 1) + 10;
+ _out_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_OUT_PKT) - 1);
+
+ _peer.instance();
+ _tcp.instance();
+ disconnect_from_host();
+}
+
+WSLClient::~WSLClient() {
+
+ _peer->close_now();
+ _peer->invalidate();
+ disconnect_from_host();
+}
+
+#endif // JAVASCRIPT_ENABLED
diff --git a/modules/websocket/lws_client.h b/modules/websocket/wsl_client.h
index b3a1237550..57dfd635b7 100644
--- a/modules/websocket/lws_client.h
+++ b/modules/websocket/wsl_client.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* lws_client.h */
+/* wsl_client.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,21 +28,21 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef LWSCLIENT_H
-#define LWSCLIENT_H
+#ifndef WSLCLIENT_H
+#define WSLCLIENT_H
#ifndef JAVASCRIPT_ENABLED
#include "core/error_list.h"
-#include "lws_helper.h"
-#include "lws_peer.h"
+#include "core/io/stream_peer_ssl.h"
+#include "core/io/stream_peer_tcp.h"
#include "websocket_client.h"
+#include "wsl_peer.h"
+#include "wslay/wslay.h"
-class LWSClient : public WebSocketClient {
+class WSLClient : public WebSocketClient {
- GDCIIMPL(LWSClient, WebSocketClient);
-
- LWS_HELPER(LWSClient);
+ GDCIIMPL(WSLClient, WebSocketClient);
private:
int _in_buf_size;
@@ -50,7 +50,28 @@ private:
int _out_buf_size;
int _out_pkt_size;
+ Ref<WSLPeer> _peer;
+ Ref<StreamPeerTCP> _tcp;
+ Ref<StreamPeer> _connection;
+
+ CharString _request;
+ int _requested;
+
+ uint8_t _resp_buf[WSL_MAX_HEADER_SIZE];
+ int _resp_pos;
+
+ String _response;
+
+ String _key;
+ String _host;
+ PoolVector<String> _protocols;
+ bool _use_ssl;
+
+ void _do_handshake();
+ bool _verify_headers(String &r_protocol);
+
public:
+ Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets);
Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocol = PoolVector<String>());
int get_max_packet_size() const;
Ref<WebSocketPeer> get_peer(int p_peer_id) const;
@@ -60,10 +81,10 @@ public:
virtual ConnectionStatus get_connection_status() const;
virtual void poll();
- LWSClient();
- ~LWSClient();
+ WSLClient();
+ ~WSLClient();
};
#endif // JAVASCRIPT_ENABLED
-#endif // LWSCLIENT_H
+#endif // WSLCLIENT_H
diff --git a/modules/websocket/wsl_peer.cpp b/modules/websocket/wsl_peer.cpp
new file mode 100644
index 0000000000..b11bd2b70f
--- /dev/null
+++ b/modules/websocket/wsl_peer.cpp
@@ -0,0 +1,339 @@
+/*************************************************************************/
+/* lws_peer.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef JAVASCRIPT_ENABLED
+
+#include "wsl_peer.h"
+
+#include "wsl_client.h"
+#include "wsl_server.h"
+
+#include "core/math/crypto_core.h"
+#include "core/math/random_number_generator.h"
+#include "core/os/os.h"
+
+String WSLPeer::generate_key() {
+ // Random key
+ RandomNumberGenerator rng;
+ rng.set_seed(OS::get_singleton()->get_unix_time());
+ PoolVector<uint8_t> bkey;
+ int len = 16; // 16 bytes, as per RFC
+ bkey.resize(len);
+ PoolVector<uint8_t>::Write w = bkey.write();
+ for (int i = 0; i < len; i++) {
+ w[i] = (uint8_t)rng.randi_range(0, 255);
+ }
+ return CryptoCore::b64_encode_str(&w[0], len);
+}
+
+String WSLPeer::compute_key_response(String p_key) {
+ String key = p_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // Magic UUID as per RFC
+ Vector<uint8_t> sha = key.sha1_buffer();
+ return CryptoCore::b64_encode_str(sha.ptr(), sha.size());
+}
+
+void WSLPeer::_wsl_destroy(struct PeerData **p_data) {
+ if (!p_data || !(*p_data))
+ return;
+ struct PeerData *data = *p_data;
+ if (data->polling) {
+ data->destroy = true;
+ return;
+ }
+ wslay_event_context_free(data->ctx);
+ memdelete(data);
+ *p_data = NULL;
+}
+
+bool WSLPeer::_wsl_poll(struct PeerData *p_data) {
+ p_data->polling = true;
+ int err = 0;
+ if ((err = wslay_event_recv(p_data->ctx)) != 0 || (err = wslay_event_send(p_data->ctx)) != 0) {
+ print_verbose("Websocket (wslay) poll error: " + itos(err));
+ p_data->destroy = true;
+ }
+ p_data->polling = false;
+
+ if (p_data->destroy || (wslay_event_get_close_sent(p_data->ctx) && wslay_event_get_close_received(p_data->ctx))) {
+ bool valid = p_data->valid;
+ _wsl_destroy(&p_data);
+ return valid;
+ }
+ return false;
+}
+
+ssize_t wsl_recv_callback(wslay_event_context_ptr ctx, uint8_t *data, size_t len, int flags, void *user_data) {
+ struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
+ if (!peer_data->valid) {
+ wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
+ return -1;
+ }
+ Ref<StreamPeer> conn = peer_data->conn;
+ int read = 0;
+ Error err = conn->get_partial_data(data, len, read);
+ if (err != OK) {
+ print_verbose("Websocket get data error: " + itos(err) + ", read (should be 0!): " + itos(read));
+ wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
+ return -1;
+ }
+ if (read == 0) {
+ wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
+ return -1;
+ }
+ return read;
+}
+
+ssize_t wsl_send_callback(wslay_event_context_ptr ctx, const uint8_t *data, size_t len, int flags, void *user_data) {
+ struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
+ if (!peer_data->valid) {
+ wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
+ return -1;
+ }
+ Ref<StreamPeer> conn = peer_data->conn;
+ int sent = 0;
+ Error err = conn->put_partial_data(data, len, sent);
+ if (err != OK) {
+ wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE);
+ return -1;
+ }
+ if (sent == 0) {
+ wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK);
+ return -1;
+ }
+ return sent;
+}
+
+int wsl_genmask_callback(wslay_event_context_ptr ctx, uint8_t *buf, size_t len, void *user_data) {
+ RandomNumberGenerator rng;
+ // TODO maybe use crypto in the future?
+ rng.set_seed(OS::get_singleton()->get_unix_time());
+ for (unsigned int i = 0; i < len; i++) {
+ buf[i] = (uint8_t)rng.randi_range(0, 255);
+ }
+ return 0;
+}
+
+void wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event_on_msg_recv_arg *arg, void *user_data) {
+ struct WSLPeer::PeerData *peer_data = (struct WSLPeer::PeerData *)user_data;
+ if (!peer_data->valid) {
+ return;
+ }
+ WSLPeer *peer = (WSLPeer *)peer_data->peer;
+
+ if (peer->parse_message(arg) != OK)
+ return;
+
+ if (peer_data->is_server) {
+ WSLServer *helper = (WSLServer *)peer_data->obj;
+ helper->_on_peer_packet(peer_data->id);
+ } else {
+ WSLClient *helper = (WSLClient *)peer_data->obj;
+ helper->_on_peer_packet();
+ }
+}
+
+wslay_event_callbacks wsl_callbacks = {
+ wsl_recv_callback,
+ wsl_send_callback,
+ wsl_genmask_callback,
+ NULL, /* on_frame_recv_start_callback */
+ NULL, /* on_frame_recv_callback */
+ NULL, /* on_frame_recv_end_callback */
+ wsl_msg_recv_callback
+};
+
+Error WSLPeer::parse_message(const wslay_event_on_msg_recv_arg *arg) {
+ uint8_t is_string = 0;
+ if (arg->opcode == WSLAY_TEXT_FRAME) {
+ is_string = 1;
+ } else if (arg->opcode == WSLAY_CONNECTION_CLOSE) {
+ close_code = arg->status_code;
+ size_t len = arg->msg_length;
+ close_reason = "";
+ if (len > 2 /* first 2 bytes = close code */) {
+ close_reason.parse_utf8((char *)arg->msg + 2, len - 2);
+ }
+ if (!wslay_event_get_close_sent(_data->ctx)) {
+ if (_data->is_server) {
+ WSLServer *helper = (WSLServer *)_data->obj;
+ helper->_on_close_request(_data->id, close_code, close_reason);
+ } else {
+ WSLClient *helper = (WSLClient *)_data->obj;
+ helper->_on_close_request(close_code, close_reason);
+ }
+ }
+ return ERR_FILE_EOF;
+ } else if (arg->opcode != WSLAY_BINARY_FRAME) {
+ // Ping or pong
+ return ERR_SKIP;
+ }
+ _in_buffer.write_packet(arg->msg, arg->msg_length, &is_string);
+ return OK;
+}
+
+void WSLPeer::make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size) {
+ ERR_FAIL_COND(_data != NULL);
+ ERR_FAIL_COND(p_data == NULL);
+
+ _in_buffer.resize(p_in_pkt_size, p_in_buf_size);
+ _packet_buffer.resize((1 << MAX(p_in_buf_size, p_out_buf_size)));
+
+ _data = p_data;
+ _data->peer = this;
+ _data->valid = true;
+ _connection = Ref<StreamPeer>(_data->conn);
+
+ if (_data->is_server)
+ wslay_event_context_server_init(&(_data->ctx), &wsl_callbacks, _data);
+ else
+ wslay_event_context_client_init(&(_data->ctx), &wsl_callbacks, _data);
+ wslay_event_config_set_max_recv_msg_length(_data->ctx, (1 << p_in_buf_size));
+}
+
+void WSLPeer::set_write_mode(WriteMode p_mode) {
+ write_mode = p_mode;
+}
+
+WSLPeer::WriteMode WSLPeer::get_write_mode() const {
+ return write_mode;
+}
+
+void WSLPeer::poll() {
+ if (!_data)
+ return;
+
+ if (_wsl_poll(_data)) {
+ _data = NULL;
+ }
+}
+
+Error WSLPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
+
+ ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
+
+ struct wslay_event_msg msg; // Should I use fragmented?
+ msg.opcode = write_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME;
+ msg.msg = p_buffer;
+ msg.msg_length = p_buffer_size;
+
+ wslay_event_queue_msg(_data->ctx, &msg);
+ return OK;
+}
+
+Error WSLPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
+
+ r_buffer_size = 0;
+
+ ERR_FAIL_COND_V(!is_connected_to_host(), FAILED);
+
+ if (_in_buffer.packets_left() == 0)
+ return ERR_UNAVAILABLE;
+
+ int read = 0;
+ PoolVector<uint8_t>::Write rw = _packet_buffer.write();
+ _in_buffer.read_packet(rw.ptr(), _packet_buffer.size(), &_is_string, read);
+
+ *r_buffer = rw.ptr();
+ r_buffer_size = read;
+
+ return OK;
+}
+
+int WSLPeer::get_available_packet_count() const {
+
+ if (!is_connected_to_host())
+ return 0;
+
+ return _in_buffer.packets_left();
+}
+
+bool WSLPeer::was_string_packet() const {
+
+ return _is_string;
+}
+
+bool WSLPeer::is_connected_to_host() const {
+
+ return _data != NULL;
+}
+
+void WSLPeer::close_now() {
+ close(1000, "");
+ _wsl_destroy(&_data);
+}
+
+void WSLPeer::close(int p_code, String p_reason) {
+ if (_data && !wslay_event_get_close_sent(_data->ctx)) {
+ CharString cs = p_reason.utf8();
+ wslay_event_queue_close(_data->ctx, p_code, (uint8_t *)cs.ptr(), cs.size());
+ wslay_event_send(_data->ctx);
+ }
+
+ _in_buffer.clear();
+ _packet_buffer.resize(0);
+}
+
+IP_Address WSLPeer::get_connected_host() const {
+
+ ERR_FAIL_COND_V(!is_connected_to_host(), IP_Address());
+
+ IP_Address ip;
+ return ip;
+}
+
+uint16_t WSLPeer::get_connected_port() const {
+
+ ERR_FAIL_COND_V(!is_connected_to_host(), 0);
+
+ uint16_t port = 0;
+ return port;
+}
+
+void WSLPeer::invalidate() {
+ if (_data)
+ _data->valid = false;
+}
+
+WSLPeer::WSLPeer() {
+ _data = NULL;
+ _is_string = 0;
+ close_code = -1;
+ write_mode = WRITE_MODE_BINARY;
+}
+
+WSLPeer::~WSLPeer() {
+
+ close();
+ invalidate();
+ _wsl_destroy(&_data);
+ _data = NULL;
+}
+
+#endif // JAVASCRIPT_ENABLED
diff --git a/modules/websocket/lws_peer.h b/modules/websocket/wsl_peer.h
index 6771c13094..d51b304fe1 100644
--- a/modules/websocket/lws_peer.h
+++ b/modules/websocket/wsl_peer.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* lws_peer.h */
+/* wsl_peer.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,50 +28,76 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef LWSPEER_H
-#define LWSPEER_H
+#ifndef WSLPEER_H
+#define WSLPEER_H
#ifndef JAVASCRIPT_ENABLED
#include "core/error_list.h"
#include "core/io/packet_peer.h"
#include "core/ring_buffer.h"
-#include "libwebsockets.h"
-#include "lws_config.h"
#include "packet_buffer.h"
#include "websocket_peer.h"
+#include "wslay/wslay.h"
-class LWSPeer : public WebSocketPeer {
+#define WSL_MAX_HEADER_SIZE 4096
- GDCIIMPL(LWSPeer, WebSocketPeer);
+class WSLPeer : public WebSocketPeer {
+
+ GDCIIMPL(WSLPeer, WebSocketPeer);
+
+public:
+ struct PeerData {
+ bool polling;
+ bool destroy;
+ bool valid;
+ bool is_server;
+ void *obj;
+ void *peer;
+ Ref<StreamPeer> conn;
+ int id;
+ wslay_event_context_ptr ctx;
+
+ PeerData() {
+ polling = false;
+ destroy = false;
+ valid = false;
+ is_server = false;
+ id = 1;
+ ctx = NULL;
+ obj = NULL;
+ peer = NULL;
+ }
+ };
+
+ static String compute_key_response(String p_key);
+ static String generate_key();
private:
- int _in_size;
+ static bool _wsl_poll(struct PeerData *p_data);
+ static void _wsl_destroy(struct PeerData **p_data);
+
+ Ref<StreamPeer> _connection;
+ struct PeerData *_data;
uint8_t _is_string;
// Our packet info is just a boolean (is_string), using uint8_t for it.
PacketBuffer<uint8_t> _in_buffer;
- PacketBuffer<uint8_t> _out_buffer;
PoolVector<uint8_t> _packet_buffer;
- struct lws *wsi;
WriteMode write_mode;
+public:
int close_code;
String close_reason;
-
-public:
- struct PeerData {
- uint32_t peer_id;
- bool force_close;
- bool clean_close;
- };
+ void poll(); // Used by client and server.
virtual int get_available_packet_count() const;
virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size);
virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
virtual int get_max_packet_size() const { return _packet_buffer.size(); };
+ virtual void close_now();
virtual void close(int p_code = 1000, String p_reason = "");
virtual bool is_connected_to_host() const;
virtual IP_Address get_connected_host() const;
@@ -81,14 +107,12 @@ public:
virtual void set_write_mode(WriteMode p_mode);
virtual bool was_string_packet() const;
- void set_wsi(struct lws *wsi, unsigned int _in_buf_size, unsigned int _in_pkt_size, unsigned int _out_buf_size, unsigned int _out_pkt_size);
- Error read_wsi(void *in, size_t len);
- Error write_wsi();
- void send_close_status(struct lws *wsi);
- String get_close_reason(void *in, size_t len, int &r_code);
+ void make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size);
+ Error parse_message(const wslay_event_on_msg_recv_arg *arg);
+ void invalidate();
- LWSPeer();
- ~LWSPeer();
+ WSLPeer();
+ ~WSLPeer();
};
#endif // JAVASCRIPT_ENABLED
diff --git a/modules/websocket/wsl_server.cpp b/modules/websocket/wsl_server.cpp
new file mode 100644
index 0000000000..0d09a4d74e
--- /dev/null
+++ b/modules/websocket/wsl_server.cpp
@@ -0,0 +1,302 @@
+/*************************************************************************/
+/* lws_server.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef JAVASCRIPT_ENABLED
+
+#include "wsl_server.h"
+#include "core/os/os.h"
+#include "core/project_settings.h"
+
+WSLServer::PendingPeer::PendingPeer() {
+ time = 0;
+ has_request = false;
+ response_sent = 0;
+ req_pos = 0;
+ memset(req_buf, 0, sizeof(req_buf));
+}
+
+bool WSLServer::PendingPeer::_parse_request(const PoolStringArray p_protocols) {
+ Vector<String> psa = String((char *)req_buf).split("\r\n");
+ int len = psa.size();
+ if (len < 4) {
+ ERR_EXPLAIN("Not enough response headers.");
+ ERR_FAIL_V(false);
+ }
+
+ Vector<String> req = psa[0].split(" ", false);
+ if (req.size() < 2) {
+ ERR_EXPLAIN("Invalid protocol or status code.");
+ ERR_FAIL_V(false);
+ }
+ // Wrong protocol
+ if (req[0] != "GET" || req[2] != "HTTP/1.1") {
+ ERR_EXPLAIN("Invalid method or HTTP version.");
+ ERR_FAIL_V(false);
+ }
+
+ Map<String, String> headers;
+ for (int i = 1; i < len; i++) {
+ Vector<String> header = psa[i].split(":", false, 1);
+ if (header.size() != 2) {
+ ERR_EXPLAIN("Invalid header -> " + psa[i]);
+ ERR_FAIL_V(false);
+ }
+ String name = header[0].to_lower();
+ String value = header[1].strip_edges();
+ if (headers.has(name))
+ headers[name] += "," + value;
+ else
+ headers[name] = value;
+ }
+#define _WLS_CHECK(NAME, VALUE) \
+ ERR_EXPLAIN("Missing or invalid header '" + String(NAME) + "'. Expected value '" + VALUE + "'"); \
+ ERR_FAIL_COND_V(!headers.has(NAME) || headers[NAME].to_lower() != VALUE, false);
+#define _WLS_CHECK_EX(NAME) \
+ ERR_EXPLAIN("Missing header '" + String(NAME) + "'."); \
+ ERR_FAIL_COND_V(!headers.has(NAME), false);
+ _WLS_CHECK("upgrade", "websocket");
+ _WLS_CHECK("sec-websocket-version", "13");
+ _WLS_CHECK_EX("sec-websocket-key");
+ _WLS_CHECK_EX("connection");
+#undef _WLS_CHECK_EX
+#undef _WLS_CHECK
+ key = headers["sec-websocket-key"];
+ if (headers.has("sec-websocket-protocol")) {
+ Vector<String> protos = headers["sec-websocket-protocol"].split(",");
+ for (int i = 0; i < protos.size(); i++) {
+ // Check if we have the given protocol
+ for (int j = 0; j < p_protocols.size(); j++) {
+ if (protos[i] != p_protocols[j])
+ continue;
+ protocol = protos[i];
+ break;
+ }
+ // Found a protocol
+ if (protocol != "")
+ break;
+ }
+ if (protocol == "") // Invalid protocol(s) requested
+ return false;
+ } else if (p_protocols.size() > 0) // No protocol requested, but we need one
+ return false;
+ return true;
+}
+
+Error WSLServer::PendingPeer::do_handshake(PoolStringArray p_protocols) {
+ if (OS::get_singleton()->get_ticks_msec() - time > WSL_SERVER_TIMEOUT)
+ return ERR_TIMEOUT;
+ if (!has_request) {
+ int read = 0;
+ while (true) {
+ if (req_pos >= WSL_MAX_HEADER_SIZE) {
+ // Header is too big
+ ERR_EXPLAIN("Response headers too big");
+ ERR_FAIL_V(ERR_OUT_OF_MEMORY);
+ }
+ Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
+ if (err != OK) // Got an error
+ return FAILED;
+ else if (read != 1) // Busy, wait next poll
+ return ERR_BUSY;
+ char *r = (char *)req_buf;
+ int l = req_pos;
+ if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
+ r[l - 3] = '\0';
+ if (!_parse_request(p_protocols)) {
+ return FAILED;
+ }
+ String s = "HTTP/1.1 101 Switching Protocols\r\n";
+ s += "Upgrade: websocket\r\n";
+ s += "Connection: Upgrade\r\n";
+ s += "Sec-WebSocket-Accept: " + WSLPeer::compute_key_response(key) + "\r\n";
+ if (protocol != "")
+ s += "Sec-WebSocket-Protocol: " + protocol + "\r\n";
+ s += "\r\n";
+ response = s.utf8();
+ has_request = true;
+ break;
+ }
+ req_pos += 1;
+ }
+ }
+ if (has_request && response_sent < response.size() - 1) {
+ int sent = 0;
+ Error err = connection->put_partial_data((const uint8_t *)response.get_data() + response_sent, response.size() - response_sent - 1, sent);
+ if (err != OK) {
+ return err;
+ }
+ response_sent += sent;
+ }
+ if (response_sent < response.size() - 1)
+ return ERR_BUSY;
+ return OK;
+}
+
+Error WSLServer::listen(int p_port, PoolVector<String> p_protocols, bool gd_mp_api) {
+ ERR_FAIL_COND_V(is_listening(), ERR_ALREADY_IN_USE);
+
+ _is_multiplayer = gd_mp_api;
+ _protocols = p_protocols;
+ _server->listen(p_port);
+
+ return OK;
+}
+
+void WSLServer::poll() {
+
+ List<int> remove_ids;
+ for (Map<int, Ref<WebSocketPeer> >::Element *E = _peer_map.front(); E; E = E->next()) {
+ Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
+ peer->poll();
+ if (!peer->is_connected_to_host()) {
+ _on_disconnect(E->key(), peer->close_code != -1);
+ remove_ids.push_back(E->key());
+ }
+ }
+ for (List<int>::Element *E = remove_ids.front(); E; E = E->next()) {
+ _peer_map.erase(E->get());
+ }
+ remove_ids.clear();
+
+ List<Ref<PendingPeer> > remove_peers;
+ for (List<Ref<PendingPeer> >::Element *E = _pending.front(); E; E = E->next()) {
+ Ref<PendingPeer> ppeer = E->get();
+ Error err = ppeer->do_handshake(_protocols);
+ if (err == ERR_BUSY) {
+ continue;
+ } else if (err != OK) {
+ remove_peers.push_back(ppeer);
+ continue;
+ }
+ // Creating new peer
+ int32_t id = _gen_unique_id();
+
+ WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData);
+ data->obj = this;
+ data->conn = ppeer->connection;
+ data->is_server = true;
+ data->id = id;
+
+ Ref<WSLPeer> ws_peer = memnew(WSLPeer);
+ ws_peer->make_context(data, _in_buf_size, _in_pkt_size, _out_buf_size, _out_pkt_size);
+
+ _peer_map[id] = ws_peer;
+ remove_peers.push_back(ppeer);
+ _on_connect(id, ppeer->protocol);
+ }
+ for (List<Ref<PendingPeer> >::Element *E = remove_peers.front(); E; E = E->next()) {
+ _pending.erase(E->get());
+ }
+ remove_peers.clear();
+
+ if (!_server->is_listening())
+ return;
+
+ while (_server->is_connection_available()) {
+ Ref<StreamPeer> conn = _server->take_connection();
+ if (is_refusing_new_connections())
+ continue; // Conn will go out-of-scope and be closed.
+
+ Ref<PendingPeer> peer = memnew(PendingPeer);
+ peer->connection = conn;
+ peer->time = OS::get_singleton()->get_ticks_msec();
+ _pending.push_back(peer);
+ }
+}
+
+bool WSLServer::is_listening() const {
+ return _server->is_listening();
+}
+
+int WSLServer::get_max_packet_size() const {
+ return (1 << _out_buf_size) - PROTO_SIZE;
+}
+
+void WSLServer::stop() {
+ _server->stop();
+ for (Map<int, Ref<WebSocketPeer> >::Element *E = _peer_map.front(); E; E = E->next()) {
+ Ref<WSLPeer> peer = (WSLPeer *)E->get().ptr();
+ peer->close_now();
+ }
+ _pending.clear();
+ _peer_map.clear();
+}
+
+bool WSLServer::has_peer(int p_id) const {
+ return _peer_map.has(p_id);
+}
+
+Ref<WebSocketPeer> WSLServer::get_peer(int p_id) const {
+ ERR_FAIL_COND_V(!has_peer(p_id), NULL);
+ return _peer_map[p_id];
+}
+
+IP_Address WSLServer::get_peer_address(int p_peer_id) const {
+ ERR_FAIL_COND_V(!has_peer(p_peer_id), IP_Address());
+
+ return _peer_map[p_peer_id]->get_connected_host();
+}
+
+int WSLServer::get_peer_port(int p_peer_id) const {
+ ERR_FAIL_COND_V(!has_peer(p_peer_id), 0);
+
+ return _peer_map[p_peer_id]->get_connected_port();
+}
+
+void WSLServer::disconnect_peer(int p_peer_id, int p_code, String p_reason) {
+ ERR_FAIL_COND(!has_peer(p_peer_id));
+
+ get_peer(p_peer_id)->close(p_code, p_reason);
+}
+
+Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
+ ERR_EXPLAIN("Buffers sizes can only be set before listening or connecting");
+ ERR_FAIL_COND_V(_server->is_listening(), FAILED);
+
+ _in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
+ _in_pkt_size = nearest_shift(p_in_packets - 1);
+ _out_buf_size = nearest_shift(p_out_buffer - 1) + 10;
+ _out_pkt_size = nearest_shift(p_out_packets - 1);
+ return OK;
+}
+
+WSLServer::WSLServer() {
+ _in_buf_size = nearest_shift((int)GLOBAL_GET(WSS_IN_BUF) - 1) + 10;
+ _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_IN_PKT) - 1);
+ _out_buf_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_BUF) - 1) + 10;
+ _out_pkt_size = nearest_shift((int)GLOBAL_GET(WSS_OUT_PKT) - 1);
+ _server.instance();
+}
+
+WSLServer::~WSLServer() {
+ stop();
+}
+
+#endif // JAVASCRIPT_ENABLED
diff --git a/modules/websocket/lws_server.h b/modules/websocket/wsl_server.h
index 5096ee0f88..2ceb941073 100644
--- a/modules/websocket/lws_server.h
+++ b/modules/websocket/wsl_server.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* lws_server.h */
+/* wsl_server.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,30 +28,57 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef LWSSERVER_H
-#define LWSSERVER_H
+#ifndef WSLSERVER_H
+#define WSLSERVER_H
#ifndef JAVASCRIPT_ENABLED
-#include "core/reference.h"
-#include "lws_helper.h"
-#include "lws_peer.h"
#include "websocket_server.h"
+#include "wsl_peer.h"
-class LWSServer : public WebSocketServer {
+#include "core/io/stream_peer_tcp.h"
+#include "core/io/tcp_server.h"
- GDCIIMPL(LWSServer, WebSocketServer);
+#define WSL_SERVER_TIMEOUT 1000
- LWS_HELPER(LWSServer);
+class WSLServer : public WebSocketServer {
+
+ GDCIIMPL(WSLServer, WebSocketServer);
private:
- Map<int, Ref<LWSPeer> > peer_map;
+ class PendingPeer : public Reference {
+
+ private:
+ bool _parse_request(const PoolStringArray p_protocols);
+
+ public:
+ Ref<StreamPeer> connection;
+
+ int time;
+ uint8_t req_buf[WSL_MAX_HEADER_SIZE];
+ int req_pos;
+ String key;
+ String protocol;
+ bool has_request;
+ CharString response;
+ int response_sent;
+
+ PendingPeer();
+
+ Error do_handshake(const PoolStringArray p_protocols);
+ };
+
int _in_buf_size;
int _in_pkt_size;
int _out_buf_size;
int _out_pkt_size;
+ List<Ref<PendingPeer> > _pending;
+ Ref<TCP_Server> _server;
+ PoolStringArray _protocols;
+
public:
+ Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets);
Error listen(int p_port, PoolVector<String> p_protocols = PoolVector<String>(), bool gd_mp_api = false);
void stop();
bool is_listening() const;
@@ -61,12 +88,12 @@ public:
IP_Address get_peer_address(int p_peer_id) const;
int get_peer_port(int p_peer_id) const;
void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = "");
- virtual void poll() { _lws_poll(); }
+ virtual void poll();
- LWSServer();
- ~LWSServer();
+ WSLServer();
+ ~WSLServer();
};
#endif // JAVASCRIPT_ENABLED
-#endif // LWSSERVER_H
+#endif // WSLSERVER_H
diff --git a/modules/xatlas_unwrap/register_types.cpp b/modules/xatlas_unwrap/register_types.cpp
index 903b57f017..c18aa04336 100644
--- a/modules/xatlas_unwrap/register_types.cpp
+++ b/modules/xatlas_unwrap/register_types.cpp
@@ -39,57 +39,37 @@ extern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const flo
bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, const int *p_face_materials, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y) {
//set up input mesh
- xatlas::InputMesh input_mesh;
- input_mesh.indexData = malloc(sizeof(int) * p_index_count);
+ xatlas::MeshDecl input_mesh;
+ input_mesh.indexData = p_indices;
input_mesh.indexCount = p_index_count;
- input_mesh.indexFormat = xatlas::IndexFormat::Float; //really xatlas?
- input_mesh.faceMaterialData = (uint16_t *)malloc(sizeof(uint16_t) * p_index_count);
-
- for (int i = 0; i < p_index_count; i++) {
- int *index = (int *)input_mesh.indexData;
- index[i] = p_indices[i];
- }
- for (int i = 0; i < p_index_count / 3; i++) {
- uint16_t *mat_index = (uint16_t *)input_mesh.faceMaterialData;
- mat_index[i] = p_face_materials[i];
- }
+ input_mesh.indexFormat = xatlas::IndexFormat::UInt32;
input_mesh.vertexCount = p_vertex_count;
- input_mesh.vertexPositionData = malloc(sizeof(float) * p_vertex_count * 3);
+ input_mesh.vertexPositionData = p_vertices;
input_mesh.vertexPositionStride = sizeof(float) * 3;
- input_mesh.vertexNormalData = malloc(sizeof(float) * p_vertex_count * 3);
- input_mesh.vertexNormalStride = sizeof(float) * 3;
-
- //material is a better hint than this i guess?
+ input_mesh.vertexNormalData = p_normals;
+ input_mesh.vertexNormalStride = sizeof(uint32_t) * 3;
input_mesh.vertexUvData = NULL;
input_mesh.vertexUvStride = 0;
- for (int i = 0; i < p_vertex_count * 3; i++) {
- float *vertex_ptr = (float *)input_mesh.vertexPositionData;
- float *normal_ptr = (float *)input_mesh.vertexNormalData;
+ xatlas::ChartOptions chart_options;
+ xatlas::PackOptions pack_options;
- vertex_ptr[i] = p_vertices[i];
- normal_ptr[i] = p_normals[i];
- }
-
- xatlas::CharterOptions chart_options;
- xatlas::PackerOptions pack_options;
-
- pack_options.method = xatlas::PackMethod::TexelArea;
- pack_options.texelArea = 1.0 / p_texel_size;
- pack_options.quality = 3;
+ pack_options.maxChartSize = 4096;
+ pack_options.bruteForce = true;
+ pack_options.texelsPerUnit = 1.0 / p_texel_size;
xatlas::Atlas *atlas = xatlas::Create();
- printf("adding mesh..\n");
- xatlas::AddMeshError err = xatlas::AddMesh(atlas, input_mesh);
- ERR_EXPLAINC(xatlas::StringForEnum(err.code));
- ERR_FAIL_COND_V(err.code != xatlas::AddMeshErrorCode::Success, false);
+ printf("Adding mesh..\n");
+ xatlas::AddMeshError::Enum err = xatlas::AddMesh(atlas, input_mesh, 1);
+ ERR_EXPLAINC(xatlas::StringForEnum(err));
+ ERR_FAIL_COND_V(err != xatlas::AddMeshError::Enum::Success, false);
- printf("generate..\n");
- xatlas::Generate(atlas, chart_options, pack_options);
+ printf("Generate..\n");
+ xatlas::Generate(atlas, chart_options, NULL, pack_options);
- *r_size_hint_x = xatlas::GetWidth(atlas);
- *r_size_hint_y = xatlas::GetHeight(atlas);
+ *r_size_hint_x = atlas->width;
+ *r_size_hint_y = atlas->height;
float w = *r_size_hint_x;
float h = *r_size_hint_y;
@@ -98,39 +78,33 @@ bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_ver
return false; //could not bake
}
- const xatlas::OutputMesh *const *output_meshes = xatlas::GetOutputMeshes(atlas);
-
- const xatlas::OutputMesh *output = output_meshes[0];
+ const xatlas::Mesh &output = atlas->meshes[0];
- *r_vertex = (int *)malloc(sizeof(int) * output->vertexCount);
- *r_uv = (float *)malloc(sizeof(float) * output->vertexCount * 2);
- *r_index = (int *)malloc(sizeof(int) * output->indexCount);
+ *r_vertex = (int *)malloc(sizeof(int) * output.vertexCount);
+ *r_uv = (float *)malloc(sizeof(float) * output.vertexCount * 2);
+ *r_index = (int *)malloc(sizeof(int) * output.indexCount);
float max_x = 0;
float max_y = 0;
- for (uint32_t i = 0; i < output->vertexCount; i++) {
- (*r_vertex)[i] = output->vertexArray[i].xref;
- (*r_uv)[i * 2 + 0] = output->vertexArray[i].uv[0] / w;
- (*r_uv)[i * 2 + 1] = output->vertexArray[i].uv[1] / h;
- max_x = MAX(max_x, output->vertexArray[i].uv[0]);
- max_y = MAX(max_y, output->vertexArray[i].uv[1]);
+ for (uint32_t i = 0; i < output.vertexCount; i++) {
+ (*r_vertex)[i] = output.vertexArray[i].xref;
+ (*r_uv)[i * 2 + 0] = output.vertexArray[i].uv[0] / w;
+ (*r_uv)[i * 2 + 1] = output.vertexArray[i].uv[1] / h;
+ max_x = MAX(max_x, output.vertexArray[i].uv[0]);
+ max_y = MAX(max_y, output.vertexArray[i].uv[1]);
}
- printf("final texsize: %f,%f - max %f,%f\n", w, h, max_x, max_y);
- *r_vertex_count = output->vertexCount;
+ printf("Final texture size: %f,%f - max %f,%f\n", w, h, max_x, max_y);
+ *r_vertex_count = output.vertexCount;
- for (uint32_t i = 0; i < output->indexCount; i++) {
- (*r_index)[i] = output->indexArray[i];
+ for (uint32_t i = 0; i < output.indexCount; i++) {
+ (*r_index)[i] = output.indexArray[i];
}
- *r_index_count = output->indexCount;
+ *r_index_count = output.indexCount;
//xatlas::Destroy(atlas);
- free((void *)input_mesh.indexData);
- free((void *)input_mesh.vertexPositionData);
- free((void *)input_mesh.vertexNormalData);
- free((void *)input_mesh.faceMaterialData);
- printf("done");
+ printf("Done\n");
return true;
}